blob: c41ebf551c0d1d4e71e68038d7e0c19088d3d4ec [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
Andy Hung2ddee192015-12-18 17:34:44 -080039#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043
44// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070045#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046#include <media/nbaio/AudioStreamOutSink.h>
47#include <media/nbaio/MonoPipe.h>
48#include <media/nbaio/MonoPipeReader.h>
49#include <media/nbaio/Pipe.h>
50#include <media/nbaio/PipeReader.h>
51#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080052#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080053
54#include <powermanager/PowerManager.h>
55
Eric Laurent81784c32012-11-19 14:55:58 -080056#include "AudioFlinger.h"
57#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070058#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070062#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080063
Eric Laurent81784c32012-11-19 14:55:58 -080064#ifdef ADD_BATTERY_DATA
65#include <media/IMediaPlayerService.h>
66#include <media/IMediaDeathNotifier.h>
67#endif
68
Eric Laurent81784c32012-11-19 14:55:58 -080069#ifdef DEBUG_CPU_USAGE
70#include <cpustats/CentralTendencyStatistics.h>
71#include <cpustats/ThreadCpuUsage.h>
72#endif
73
74// ----------------------------------------------------------------------------
75
76// Note: the following macro is used for extremely verbose logging message. In
77// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
78// 0; but one side effect of this is to turn all LOGV's as well. Some messages
79// are so verbose that we want to suppress them even when we have ALOG_ASSERT
80// turned on. Do not uncomment the #def below unless you really know what you
81// are doing and want to see all of the extremely verbose messages.
82//#define VERY_VERY_VERBOSE_LOGGING
83#ifdef VERY_VERY_VERBOSE_LOGGING
84#define ALOGVV ALOGV
85#else
86#define ALOGVV(a...) do { } while(0)
87#endif
88
Andy Hung6770c6f2015-04-07 13:43:36 -070089// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070090#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070091template <typename T>
92static inline T min(const T& a, const T& b)
93{
94 return a < b ? a : b;
95}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070096
Andy Hungd330ee42015-04-20 13:23:41 -070097#ifndef ARRAY_SIZE
98#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
99#endif
100
Eric Laurent81784c32012-11-19 14:55:58 -0800101namespace android {
102
103// retry counts for buffer fill timeout
104// 50 * ~20msecs = 1 second
105static const int8_t kMaxTrackRetries = 50;
106static const int8_t kMaxTrackStartupRetries = 50;
107// allow less retry attempts on direct output thread.
108// direct outputs can be a scarce resource in audio hardware and should
109// be released as quickly as possible.
110static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurent51716182016-02-29 18:00:56 -0800111// retry count before removing active track in case of underrun on offloaded thread:
112// we need to make sure that AudioTrack client has enough time to send large buffers
113//FIXME may be more appropriate if expressed in time units. Need to revise how underrun is handled
114// for offloaded tracks
115static const int8_t kMaxTrackRetriesOffload = 10;
116static const int8_t kMaxTrackStartupRetriesOffload = 100;
117
Eric Laurent81784c32012-11-19 14:55:58 -0800118
119// don't warn about blocked writes or record buffer overflows more often than this
120static const nsecs_t kWarningThrottleNs = seconds(5);
121
122// RecordThread loop sleep time upon application overrun or audio HAL read error
123static const int kRecordThreadSleepUs = 5000;
124
Eric Laurent10351942014-05-08 18:49:52 -0700125// maximum time to wait in sendConfigEvent_l() for a status to be received
126static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800127
128// minimum sleep time for the mixer thread loop when tracks are active but in underrun
129static const uint32_t kMinThreadSleepTimeUs = 5000;
130// maximum divider applied to the active sleep time in the mixer thread loop
131static const uint32_t kMaxThreadSleepTimeShift = 2;
132
Andy Hung09a50072014-02-27 14:30:47 -0800133// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700134// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800135static const uint32_t kMinNormalSinkBufferSizeMs = 20;
136// maximum normal sink buffer size
137static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800138
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700139// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
140// FIXME This should be based on experimentally observed scheduling jitter
141static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
142
Eric Laurent972a1732013-09-04 09:42:59 -0700143// Offloaded output thread standby delay: allows track transition without going to standby
144static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
145
Eric Laurent51716182016-02-29 18:00:56 -0800146// Direct output thread minimum sleep time in idle or active(underrun) state
147static const nsecs_t kDirectMinSleepTimeUs = 10000;
148
149// Offloaded output bit rate in bits per second when unknown.
150// Used for sleep time calculation, so use a high default bitrate to be conservative on sleep time.
151static const uint32_t kOffloadDefaultBitRateBps = 1500000;
152
153
Eric Laurent81784c32012-11-19 14:55:58 -0800154// Whether to use fast mixer
155static const enum {
156 FastMixer_Never, // never initialize or use: for debugging only
157 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
158 // normal mixer multiplier is 1
159 FastMixer_Static, // initialize if needed, then use all the time if initialized,
160 // multiplier is calculated based on min & max normal mixer buffer size
161 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
162 // multiplier is calculated based on min & max normal mixer buffer size
163 // FIXME for FastMixer_Dynamic:
164 // Supporting this option will require fixing HALs that can't handle large writes.
165 // For example, one HAL implementation returns an error from a large write,
166 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
167 // We could either fix the HAL implementations, or provide a wrapper that breaks
168 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
169} kUseFastMixer = FastMixer_Static;
170
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700171// Whether to use fast capture
172static const enum {
173 FastCapture_Never, // never initialize or use: for debugging only
174 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
175 FastCapture_Static, // initialize if needed, then use all the time if initialized
176} kUseFastCapture = FastCapture_Static;
177
Eric Laurent81784c32012-11-19 14:55:58 -0800178// Priorities for requestPriority
179static const int kPriorityAudioApp = 2;
180static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700181static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800182
183// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
184// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800185// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
186// So for now we just assume that client is double-buffered for fast tracks.
187// FIXME It would be better for client to tell AudioFlinger the value of N,
188// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800189// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700190
191// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800192static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800193
Glenn Kasten03490092014-05-27 12:30:54 -0700194// The minimum and maximum allowed values
195static const int kFastTrackMultiplierMin = 1;
196static const int kFastTrackMultiplierMax = 2;
197
198// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
199static int sFastTrackMultiplier = kFastTrackMultiplier;
200
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700201// See Thread::readOnlyHeap().
202// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
203// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
204// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700205static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700206
Eric Laurent81784c32012-11-19 14:55:58 -0800207// ----------------------------------------------------------------------------
208
Glenn Kasten03490092014-05-27 12:30:54 -0700209static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
210
211static void sFastTrackMultiplierInit()
212{
213 char value[PROPERTY_VALUE_MAX];
214 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
215 char *endptr;
216 unsigned long ul = strtoul(value, &endptr, 0);
217 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
218 sFastTrackMultiplier = (int) ul;
219 }
220 }
221}
222
223// ----------------------------------------------------------------------------
224
Eric Laurent81784c32012-11-19 14:55:58 -0800225#ifdef ADD_BATTERY_DATA
226// To collect the amplifier usage
227static void addBatteryData(uint32_t params) {
228 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
229 if (service == NULL) {
230 // it already logged
231 return;
232 }
233
234 service->addBatteryData(params);
235}
236#endif
237
Andy Hung3f0c9022016-01-15 17:49:46 -0800238// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
239struct {
240 // call when you acquire a partial wakelock
241 void acquire(const sp<IBinder> &wakeLockToken) {
242 pthread_mutex_lock(&mLock);
243 if (wakeLockToken.get() == nullptr) {
244 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
245 } else {
246 if (mCount == 0) {
247 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
248 }
249 ++mCount;
250 }
251 pthread_mutex_unlock(&mLock);
252 }
253
254 // call when you release a partial wakelock.
255 void release(const sp<IBinder> &wakeLockToken) {
256 if (wakeLockToken.get() == nullptr) {
257 return;
258 }
259 pthread_mutex_lock(&mLock);
260 if (--mCount < 0) {
261 ALOGE("negative wakelock count");
262 mCount = 0;
263 }
264 pthread_mutex_unlock(&mLock);
265 }
266
267 // retrieves the boottime timebase offset from monotonic.
268 int64_t getBoottimeOffset() {
269 pthread_mutex_lock(&mLock);
270 int64_t boottimeOffset = mBoottimeOffset;
271 pthread_mutex_unlock(&mLock);
272 return boottimeOffset;
273 }
274
275 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
276 // and the selected timebase.
277 // Currently only TIMEBASE_BOOTTIME is allowed.
278 //
279 // This only needs to be called upon acquiring the first partial wakelock
280 // after all other partial wakelocks are released.
281 //
282 // We do an empirical measurement of the offset rather than parsing
283 // /proc/timer_list since the latter is not a formal kernel ABI.
284 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
285 int clockbase;
286 switch (timebase) {
287 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
288 clockbase = SYSTEM_TIME_BOOTTIME;
289 break;
290 default:
291 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
292 break;
293 }
294 // try three times to get the clock offset, choose the one
295 // with the minimum gap in measurements.
296 const int tries = 3;
297 nsecs_t bestGap, measured;
298 for (int i = 0; i < tries; ++i) {
299 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
300 const nsecs_t tbase = systemTime(clockbase);
301 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
302 const nsecs_t gap = tmono2 - tmono;
303 if (i == 0 || gap < bestGap) {
304 bestGap = gap;
305 measured = tbase - ((tmono + tmono2) >> 1);
306 }
307 }
308
309 // to avoid micro-adjusting, we don't change the timebase
310 // unless it is significantly different.
311 //
312 // Assumption: It probably takes more than toleranceNs to
313 // suspend and resume the device.
314 static int64_t toleranceNs = 10000; // 10 us
315 if (llabs(*offset - measured) > toleranceNs) {
316 ALOGV("Adjusting timebase offset old: %lld new: %lld",
317 (long long)*offset, (long long)measured);
318 *offset = measured;
319 }
320 }
321
322 pthread_mutex_t mLock;
323 int32_t mCount;
324 int64_t mBoottimeOffset;
325} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800326
327// ----------------------------------------------------------------------------
328// CPU Stats
329// ----------------------------------------------------------------------------
330
331class CpuStats {
332public:
333 CpuStats();
334 void sample(const String8 &title);
335#ifdef DEBUG_CPU_USAGE
336private:
337 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
338 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
339
340 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
341
342 int mCpuNum; // thread's current CPU number
343 int mCpukHz; // frequency of thread's current CPU in kHz
344#endif
345};
346
347CpuStats::CpuStats()
348#ifdef DEBUG_CPU_USAGE
349 : mCpuNum(-1), mCpukHz(-1)
350#endif
351{
352}
353
Glenn Kasten0f11b512014-01-31 16:18:54 -0800354void CpuStats::sample(const String8 &title
355#ifndef DEBUG_CPU_USAGE
356 __unused
357#endif
358 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800359#ifdef DEBUG_CPU_USAGE
360 // get current thread's delta CPU time in wall clock ns
361 double wcNs;
362 bool valid = mCpuUsage.sampleAndEnable(wcNs);
363
364 // record sample for wall clock statistics
365 if (valid) {
366 mWcStats.sample(wcNs);
367 }
368
369 // get the current CPU number
370 int cpuNum = sched_getcpu();
371
372 // get the current CPU frequency in kHz
373 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
374
375 // check if either CPU number or frequency changed
376 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
377 mCpuNum = cpuNum;
378 mCpukHz = cpukHz;
379 // ignore sample for purposes of cycles
380 valid = false;
381 }
382
383 // if no change in CPU number or frequency, then record sample for cycle statistics
384 if (valid && mCpukHz > 0) {
385 double cycles = wcNs * cpukHz * 0.000001;
386 mHzStats.sample(cycles);
387 }
388
389 unsigned n = mWcStats.n();
390 // mCpuUsage.elapsed() is expensive, so don't call it every loop
391 if ((n & 127) == 1) {
392 long long elapsed = mCpuUsage.elapsed();
393 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
394 double perLoop = elapsed / (double) n;
395 double perLoop100 = perLoop * 0.01;
396 double perLoop1k = perLoop * 0.001;
397 double mean = mWcStats.mean();
398 double stddev = mWcStats.stddev();
399 double minimum = mWcStats.minimum();
400 double maximum = mWcStats.maximum();
401 double meanCycles = mHzStats.mean();
402 double stddevCycles = mHzStats.stddev();
403 double minCycles = mHzStats.minimum();
404 double maxCycles = mHzStats.maximum();
405 mCpuUsage.resetElapsed();
406 mWcStats.reset();
407 mHzStats.reset();
408 ALOGD("CPU usage for %s over past %.1f secs\n"
409 " (%u mixer loops at %.1f mean ms per loop):\n"
410 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
411 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
412 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
413 title.string(),
414 elapsed * .000000001, n, perLoop * .000001,
415 mean * .001,
416 stddev * .001,
417 minimum * .001,
418 maximum * .001,
419 mean / perLoop100,
420 stddev / perLoop100,
421 minimum / perLoop100,
422 maximum / perLoop100,
423 meanCycles / perLoop1k,
424 stddevCycles / perLoop1k,
425 minCycles / perLoop1k,
426 maxCycles / perLoop1k);
427
428 }
429 }
430#endif
431};
432
433// ----------------------------------------------------------------------------
434// ThreadBase
435// ----------------------------------------------------------------------------
436
Glenn Kasten97b7b752014-09-28 13:04:24 -0700437// static
438const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
439{
440 switch (type) {
441 case MIXER:
442 return "MIXER";
443 case DIRECT:
444 return "DIRECT";
445 case DUPLICATING:
446 return "DUPLICATING";
447 case RECORD:
448 return "RECORD";
449 case OFFLOAD:
450 return "OFFLOAD";
451 default:
452 return "unknown";
453 }
454}
455
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800456String8 devicesToString(audio_devices_t devices)
457{
458 static const struct mapping {
459 audio_devices_t mDevices;
460 const char * mString;
461 } mappingsOut[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800462 {AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE"},
463 {AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER"},
464 {AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET"},
465 {AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE"},
466 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO"},
467 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
468 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT"},
469 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
470 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,"BLUETOOTH_A2DP_HEADPHONES"},
471 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER"},
472 {AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL"},
473 {AUDIO_DEVICE_OUT_HDMI, "HDMI"},
474 {AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET,"ANLG_DOCK_HEADSET"},
475 {AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET,"DGTL_DOCK_HEADSET"},
476 {AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY"},
477 {AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE"},
478 {AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX"},
479 {AUDIO_DEVICE_OUT_LINE, "LINE"},
480 {AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC"},
481 {AUDIO_DEVICE_OUT_SPDIF, "SPDIF"},
482 {AUDIO_DEVICE_OUT_FM, "FM"},
483 {AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE"},
484 {AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE"},
485 {AUDIO_DEVICE_OUT_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800486 {AUDIO_DEVICE_OUT_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800487 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800488 }, mappingsIn[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800489 {AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION"},
490 {AUDIO_DEVICE_IN_AMBIENT, "AMBIENT"},
491 {AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC"},
492 {AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
493 {AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET"},
494 {AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL"},
495 {AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL"},
496 {AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX"},
497 {AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC"},
498 {AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX"},
499 {AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET"},
500 {AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET"},
501 {AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY"},
502 {AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE"},
503 {AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER"},
504 {AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER"},
505 {AUDIO_DEVICE_IN_LINE, "LINE"},
506 {AUDIO_DEVICE_IN_SPDIF, "SPDIF"},
507 {AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
508 {AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK"},
509 {AUDIO_DEVICE_IN_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800510 {AUDIO_DEVICE_IN_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800511 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800512 };
513 String8 result;
514 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
515 const mapping *entry;
516 if (devices & AUDIO_DEVICE_BIT_IN) {
517 devices &= ~AUDIO_DEVICE_BIT_IN;
518 entry = mappingsIn;
519 } else {
520 entry = mappingsOut;
521 }
522 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
523 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
524 if (devices & entry->mDevices) {
525 if (!result.isEmpty()) {
526 result.append("|");
527 }
528 result.append(entry->mString);
529 }
530 }
531 if (devices & ~allDevices) {
532 if (!result.isEmpty()) {
533 result.append("|");
534 }
535 result.appendFormat("0x%X", devices & ~allDevices);
536 }
537 if (result.isEmpty()) {
538 result.append(entry->mString);
539 }
540 return result;
541}
542
543String8 inputFlagsToString(audio_input_flags_t flags)
544{
545 static const struct mapping {
546 audio_input_flags_t mFlag;
547 const char * mString;
548 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800549 {AUDIO_INPUT_FLAG_FAST, "FAST"},
550 {AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD"},
551 {AUDIO_INPUT_FLAG_RAW, "RAW"},
552 {AUDIO_INPUT_FLAG_SYNC, "SYNC"},
553 {AUDIO_INPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800554 };
555 String8 result;
556 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
557 const mapping *entry;
558 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
559 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
560 if (flags & entry->mFlag) {
561 if (!result.isEmpty()) {
562 result.append("|");
563 }
564 result.append(entry->mString);
565 }
566 }
567 if (flags & ~allFlags) {
568 if (!result.isEmpty()) {
569 result.append("|");
570 }
571 result.appendFormat("0x%X", flags & ~allFlags);
572 }
573 if (result.isEmpty()) {
574 result.append(entry->mString);
575 }
576 return result;
577}
578
579String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700580{
581 static const struct mapping {
582 audio_output_flags_t mFlag;
583 const char * mString;
584 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800585 {AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT"},
586 {AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY"},
587 {AUDIO_OUTPUT_FLAG_FAST, "FAST"},
588 {AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER"},
589 {AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,"COMPRESS_OFFLOAD"},
590 {AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING"},
591 {AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC"},
592 {AUDIO_OUTPUT_FLAG_RAW, "RAW"},
593 {AUDIO_OUTPUT_FLAG_SYNC, "SYNC"},
594 {AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO, "IEC958_NONAUDIO"},
595 {AUDIO_OUTPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten97b7b752014-09-28 13:04:24 -0700596 };
597 String8 result;
598 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
599 const mapping *entry;
600 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
601 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
602 if (flags & entry->mFlag) {
603 if (!result.isEmpty()) {
604 result.append("|");
605 }
606 result.append(entry->mString);
607 }
608 }
609 if (flags & ~allFlags) {
610 if (!result.isEmpty()) {
611 result.append("|");
612 }
613 result.appendFormat("0x%X", flags & ~allFlags);
614 }
615 if (result.isEmpty()) {
616 result.append(entry->mString);
617 }
618 return result;
619}
620
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800621const char *sourceToString(audio_source_t source)
622{
623 switch (source) {
624 case AUDIO_SOURCE_DEFAULT: return "default";
625 case AUDIO_SOURCE_MIC: return "mic";
626 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
627 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
628 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
629 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
630 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
631 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
632 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800633 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800634 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
635 case AUDIO_SOURCE_HOTWORD: return "hotword";
636 default: return "unknown";
637 }
638}
639
Eric Laurent81784c32012-11-19 14:55:58 -0800640AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700641 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800642 : Thread(false /*canCallJava*/),
643 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700644 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700645 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800646 // are set by PlaybackThread::readOutputParameters_l() or
647 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700648 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800649 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700650 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
651 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800652 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700653 mDeathRecipient(new PMDeathRecipient(this)),
Wei Jia3f273d12015-11-24 09:06:49 -0800654 mSystemReady(systemReady),
655 mNotifiedBatteryStart(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800656{
Eric Laurent296fb132015-05-01 11:38:42 -0700657 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800658}
659
660AudioFlinger::ThreadBase::~ThreadBase()
661{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700662 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700663 mConfigEvents.clear();
664
Eric Laurent81784c32012-11-19 14:55:58 -0800665 // do not lock the mutex in destructor
666 releaseWakeLock_l();
667 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800668 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800669 binder->unlinkToDeath(mDeathRecipient);
670 }
671}
672
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700673status_t AudioFlinger::ThreadBase::readyToRun()
674{
675 status_t status = initCheck();
676 if (status == NO_ERROR) {
677 ALOGI("AudioFlinger's thread %p ready to run", this);
678 } else {
679 ALOGE("No working audio driver found.");
680 }
681 return status;
682}
683
Eric Laurent81784c32012-11-19 14:55:58 -0800684void AudioFlinger::ThreadBase::exit()
685{
686 ALOGV("ThreadBase::exit");
687 // do any cleanup required for exit to succeed
688 preExit();
689 {
690 // This lock prevents the following race in thread (uniprocessor for illustration):
691 // if (!exitPending()) {
692 // // context switch from here to exit()
693 // // exit() calls requestExit(), what exitPending() observes
694 // // exit() calls signal(), which is dropped since no waiters
695 // // context switch back from exit() to here
696 // mWaitWorkCV.wait(...);
697 // // now thread is hung
698 // }
699 AutoMutex lock(mLock);
700 requestExit();
701 mWaitWorkCV.broadcast();
702 }
703 // When Thread::requestExitAndWait is made virtual and this method is renamed to
704 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
705 requestExitAndWait();
706}
707
708status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
709{
710 status_t status;
711
712 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
713 Mutex::Autolock _l(mLock);
714
Eric Laurent10351942014-05-08 18:49:52 -0700715 return sendSetParameterConfigEvent_l(keyValuePairs);
716}
717
718// sendConfigEvent_l() must be called with ThreadBase::mLock held
719// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
720status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
721{
722 status_t status = NO_ERROR;
723
Eric Laurent72e3f392015-05-20 14:43:50 -0700724 if (event->mRequiresSystemReady && !mSystemReady) {
725 event->mWaitStatus = false;
726 mPendingConfigEvents.add(event);
727 return status;
728 }
Eric Laurent10351942014-05-08 18:49:52 -0700729 mConfigEvents.add(event);
730 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800731 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700732 mLock.unlock();
733 {
734 Mutex::Autolock _l(event->mLock);
735 while (event->mWaitStatus) {
736 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
737 event->mStatus = TIMED_OUT;
738 event->mWaitStatus = false;
739 }
740 }
741 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800742 }
Eric Laurent10351942014-05-08 18:49:52 -0700743 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800744 return status;
745}
746
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700747void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800748{
749 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700750 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800751}
752
753// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700754void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800755{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700756 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700757 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800758}
759
Eric Laurent72e3f392015-05-20 14:43:50 -0700760void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
761{
762 Mutex::Autolock _l(mLock);
763 sendPrioConfigEvent_l(pid, tid, prio);
764}
765
Eric Laurent81784c32012-11-19 14:55:58 -0800766// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
767void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
768{
Eric Laurent10351942014-05-08 18:49:52 -0700769 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
770 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800771}
772
Eric Laurent10351942014-05-08 18:49:52 -0700773// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
774status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800775{
Andy Hung2ddee192015-12-18 17:34:44 -0800776 sp<ConfigEvent> configEvent;
777 AudioParameter param(keyValuePair);
778 int value;
779 if (param.getInt(String8(AUDIO_PARAMETER_MONO_OUTPUT), value) == NO_ERROR) {
780 setMasterMono_l(value != 0);
781 if (param.size() == 1) {
782 return NO_ERROR; // should be a solo parameter - we don't pass down
783 }
784 param.remove(String8(AUDIO_PARAMETER_MONO_OUTPUT));
785 configEvent = new SetParameterConfigEvent(param.toString());
786 } else {
787 configEvent = new SetParameterConfigEvent(keyValuePair);
788 }
Eric Laurent10351942014-05-08 18:49:52 -0700789 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700790}
791
Eric Laurent1c333e22014-05-20 10:48:17 -0700792status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
793 const struct audio_patch *patch,
794 audio_patch_handle_t *handle)
795{
796 Mutex::Autolock _l(mLock);
797 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
798 status_t status = sendConfigEvent_l(configEvent);
799 if (status == NO_ERROR) {
800 CreateAudioPatchConfigEventData *data =
801 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
802 *handle = data->mHandle;
803 }
804 return status;
805}
806
807status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
808 const audio_patch_handle_t handle)
809{
810 Mutex::Autolock _l(mLock);
811 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
812 return sendConfigEvent_l(configEvent);
813}
814
815
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700816// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700817void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700818{
Eric Laurent10351942014-05-08 18:49:52 -0700819 bool configChanged = false;
820
Eric Laurent81784c32012-11-19 14:55:58 -0800821 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700822 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
823 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800824 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700825 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700826 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700827 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
828 // FIXME Need to understand why this has to be done asynchronously
829 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700830 true /*asynchronous*/);
831 if (err != 0) {
832 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700833 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700834 }
835 } break;
836 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700837 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700838 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700839 } break;
840 case CFG_EVENT_SET_PARAMETER: {
841 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
842 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
843 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700844 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700845 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700846 case CFG_EVENT_CREATE_AUDIO_PATCH: {
847 CreateAudioPatchConfigEventData *data =
848 (CreateAudioPatchConfigEventData *)event->mData.get();
849 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
850 } break;
851 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
852 ReleaseAudioPatchConfigEventData *data =
853 (ReleaseAudioPatchConfigEventData *)event->mData.get();
854 event->mStatus = releaseAudioPatch_l(data->mHandle);
855 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700856 default:
Eric Laurent10351942014-05-08 18:49:52 -0700857 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700858 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800859 }
Eric Laurent10351942014-05-08 18:49:52 -0700860 {
861 Mutex::Autolock _l(event->mLock);
862 if (event->mWaitStatus) {
863 event->mWaitStatus = false;
864 event->mCond.signal();
865 }
866 }
867 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
868 }
869
870 if (configChanged) {
871 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800872 }
Eric Laurent81784c32012-11-19 14:55:58 -0800873}
874
Marco Nelissenb2208842014-02-07 14:00:50 -0800875String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
876 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700877 const audio_channel_representation_t representation =
878 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700879
880 switch (representation) {
881 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
882 if (output) {
883 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
884 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
885 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
886 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
887 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
888 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
889 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
890 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
891 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
892 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
893 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
894 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
895 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
896 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
897 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
898 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
899 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
900 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
901 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
902 } else {
903 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
904 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
905 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
906 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
907 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
908 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
909 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
910 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
911 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
912 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
913 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
914 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
915 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
916 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
917 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
918 }
919 const int len = s.length();
920 if (len > 2) {
921 char *str = s.lockBuffer(len); // needed?
922 s.unlockBuffer(len - 2); // remove trailing ", "
923 }
924 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800925 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700926 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
927 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
928 return s;
929 default:
930 s.appendFormat("unknown mask, representation:%d bits:%#x",
931 representation, audio_channel_mask_get_bits(mask));
932 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800933 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800934}
935
Glenn Kasten0f11b512014-01-31 16:18:54 -0800936void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800937{
938 const size_t SIZE = 256;
939 char buffer[SIZE];
940 String8 result;
941
942 bool locked = AudioFlinger::dumpTryLock(mLock);
943 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700944 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800945 }
946
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800947 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700948 dprintf(fd, " I/O handle: %d\n", mId);
949 dprintf(fd, " TID: %d\n", getTid());
950 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700951 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700952 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700953 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700954 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700955 dprintf(fd, " Channel count: %u\n", mChannelCount);
956 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800957 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700958 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
959 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700960 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800961 size_t numConfig = mConfigEvents.size();
962 if (numConfig) {
963 for (size_t i = 0; i < numConfig; i++) {
964 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700965 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800966 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700967 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800968 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700969 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800970 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800971 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
972 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
973 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800974
975 if (locked) {
976 mLock.unlock();
977 }
978}
979
980void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
981{
982 const size_t SIZE = 256;
983 char buffer[SIZE];
984 String8 result;
985
Marco Nelissenb2208842014-02-07 14:00:50 -0800986 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000987 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800988 write(fd, buffer, strlen(buffer));
989
Marco Nelissenb2208842014-02-07 14:00:50 -0800990 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800991 sp<EffectChain> chain = mEffectChains[i];
992 if (chain != 0) {
993 chain->dump(fd, args);
994 }
995 }
996}
997
Marco Nelissene14a5d62013-10-03 08:51:24 -0700998void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800999{
1000 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001001 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001002}
1003
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001004String16 AudioFlinger::ThreadBase::getWakeLockTag()
1005{
1006 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001007 case MIXER:
1008 return String16("AudioMix");
1009 case DIRECT:
1010 return String16("AudioDirectOut");
1011 case DUPLICATING:
1012 return String16("AudioDup");
1013 case RECORD:
1014 return String16("AudioIn");
1015 case OFFLOAD:
1016 return String16("AudioOffload");
1017 default:
1018 ALOG_ASSERT(false);
1019 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001020 }
1021}
1022
Marco Nelissene14a5d62013-10-03 08:51:24 -07001023void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001024{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001025 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001026 if (mPowerManager != 0) {
1027 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -07001028 status_t status;
1029 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -07001030 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001031 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001032 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001033 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001034 uid,
1035 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001036 } else {
Eric Laurent547789d2013-10-04 11:46:55 -07001037 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001038 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001039 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001040 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001041 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001042 }
Eric Laurent81784c32012-11-19 14:55:58 -08001043 if (status == NO_ERROR) {
1044 mWakeLockToken = binder;
1045 }
Glenn Kastend7dca052015-03-05 16:05:54 -08001046 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -08001047 }
Wei Jia3f273d12015-11-24 09:06:49 -08001048
1049 if (!mNotifiedBatteryStart) {
1050 BatteryNotifier::getInstance().noteStartAudio();
1051 mNotifiedBatteryStart = true;
1052 }
Andy Hung3f0c9022016-01-15 17:49:46 -08001053 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001054 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1055 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001056}
1057
1058void AudioFlinger::ThreadBase::releaseWakeLock()
1059{
1060 Mutex::Autolock _l(mLock);
1061 releaseWakeLock_l();
1062}
1063
1064void AudioFlinger::ThreadBase::releaseWakeLock_l()
1065{
Andy Hung3f0c9022016-01-15 17:49:46 -08001066 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001067 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001068 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001069 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001070 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
1071 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -08001072 }
1073 mWakeLockToken.clear();
1074 }
Wei Jia3f273d12015-11-24 09:06:49 -08001075
1076 if (mNotifiedBatteryStart) {
1077 BatteryNotifier::getInstance().noteStopAudio();
1078 mNotifiedBatteryStart = false;
1079 }
Eric Laurent81784c32012-11-19 14:55:58 -08001080}
1081
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001082void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
1083 Mutex::Autolock _l(mLock);
1084 updateWakeLockUids_l(uids);
1085}
1086
1087void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001088 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001089 // use checkService() to avoid blocking if power service is not up yet
1090 sp<IBinder> binder =
1091 defaultServiceManager()->checkService(String16("power"));
1092 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001093 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001094 } else {
1095 mPowerManager = interface_cast<IPowerManager>(binder);
1096 binder->linkToDeath(mDeathRecipient);
1097 }
1098 }
1099}
1100
1101void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001102 getPowerManager_l();
Andy Hung438e7572015-12-14 15:51:17 -08001103 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1104 if (mSystemReady) {
1105 ALOGE("no wake lock to update, but system ready!");
1106 } else {
1107 ALOGW("no wake lock to update, system not ready yet");
1108 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001109 return;
1110 }
1111 if (mPowerManager != 0) {
1112 sp<IBinder> binder = new BBinder();
1113 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001114 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
1115 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001116 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001117 }
1118}
1119
Eric Laurent81784c32012-11-19 14:55:58 -08001120void AudioFlinger::ThreadBase::clearPowerManager()
1121{
1122 Mutex::Autolock _l(mLock);
1123 releaseWakeLock_l();
1124 mPowerManager.clear();
1125}
1126
Glenn Kasten0f11b512014-01-31 16:18:54 -08001127void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001128{
1129 sp<ThreadBase> thread = mThread.promote();
1130 if (thread != 0) {
1131 thread->clearPowerManager();
1132 }
1133 ALOGW("power manager service died !!!");
1134}
1135
1136void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -08001137 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001138{
1139 Mutex::Autolock _l(mLock);
1140 setEffectSuspended_l(type, suspend, sessionId);
1141}
1142
1143void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001144 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001145{
1146 sp<EffectChain> chain = getEffectChain_l(sessionId);
1147 if (chain != 0) {
1148 if (type != NULL) {
1149 chain->setEffectSuspended_l(type, suspend);
1150 } else {
1151 chain->setEffectSuspendedAll_l(suspend);
1152 }
1153 }
1154
1155 updateSuspendedSessions_l(type, suspend, sessionId);
1156}
1157
1158void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1159{
1160 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1161 if (index < 0) {
1162 return;
1163 }
1164
1165 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1166 mSuspendedSessions.valueAt(index);
1167
1168 for (size_t i = 0; i < sessionEffects.size(); i++) {
1169 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1170 for (int j = 0; j < desc->mRefCount; j++) {
1171 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1172 chain->setEffectSuspendedAll_l(true);
1173 } else {
1174 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1175 desc->mType.timeLow);
1176 chain->setEffectSuspended_l(&desc->mType, true);
1177 }
1178 }
1179 }
1180}
1181
1182void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1183 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001184 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001185{
1186 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1187
1188 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1189
1190 if (suspend) {
1191 if (index >= 0) {
1192 sessionEffects = mSuspendedSessions.valueAt(index);
1193 } else {
1194 mSuspendedSessions.add(sessionId, sessionEffects);
1195 }
1196 } else {
1197 if (index < 0) {
1198 return;
1199 }
1200 sessionEffects = mSuspendedSessions.valueAt(index);
1201 }
1202
1203
1204 int key = EffectChain::kKeyForSuspendAll;
1205 if (type != NULL) {
1206 key = type->timeLow;
1207 }
1208 index = sessionEffects.indexOfKey(key);
1209
1210 sp<SuspendedSessionDesc> desc;
1211 if (suspend) {
1212 if (index >= 0) {
1213 desc = sessionEffects.valueAt(index);
1214 } else {
1215 desc = new SuspendedSessionDesc();
1216 if (type != NULL) {
1217 desc->mType = *type;
1218 }
1219 sessionEffects.add(key, desc);
1220 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1221 }
1222 desc->mRefCount++;
1223 } else {
1224 if (index < 0) {
1225 return;
1226 }
1227 desc = sessionEffects.valueAt(index);
1228 if (--desc->mRefCount == 0) {
1229 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1230 sessionEffects.removeItemsAt(index);
1231 if (sessionEffects.isEmpty()) {
1232 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1233 sessionId);
1234 mSuspendedSessions.removeItem(sessionId);
1235 }
1236 }
1237 }
1238 if (!sessionEffects.isEmpty()) {
1239 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1240 }
1241}
1242
1243void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1244 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001245 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001246{
1247 Mutex::Autolock _l(mLock);
1248 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1249}
1250
1251void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1252 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001253 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001254{
1255 if (mType != RECORD) {
1256 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1257 // another session. This gives the priority to well behaved effect control panels
1258 // and applications not using global effects.
1259 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1260 // global effects
1261 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1262 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1263 }
1264 }
1265
1266 sp<EffectChain> chain = getEffectChain_l(sessionId);
1267 if (chain != 0) {
1268 chain->checkSuspendOnEffectEnabled(effect, enabled);
1269 }
1270}
1271
1272// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1273sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1274 const sp<AudioFlinger::Client>& client,
1275 const sp<IEffectClient>& effectClient,
1276 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001277 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001278 effect_descriptor_t *desc,
1279 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001280 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001281{
1282 sp<EffectModule> effect;
1283 sp<EffectHandle> handle;
1284 status_t lStatus;
1285 sp<EffectChain> chain;
1286 bool chainCreated = false;
1287 bool effectCreated = false;
1288 bool effectRegistered = false;
1289
1290 lStatus = initCheck();
1291 if (lStatus != NO_ERROR) {
1292 ALOGW("createEffect_l() Audio driver not initialized.");
1293 goto Exit;
1294 }
1295
Andy Hung98ef9782014-03-04 14:46:50 -08001296 // Reject any effect on Direct output threads for now, since the format of
1297 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1298 if (mType == DIRECT) {
1299 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001300 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001301 lStatus = BAD_VALUE;
1302 goto Exit;
1303 }
1304
Andy Hung389cfdb2014-08-07 17:49:53 -07001305 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001306 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001307 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1308 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1309 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001310 lStatus = BAD_VALUE;
1311 goto Exit;
1312 }
1313
Eric Laurent5baf2af2013-09-12 17:37:00 -07001314 // Allow global effects only on offloaded and mixer threads
1315 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1316 switch (mType) {
1317 case MIXER:
1318 case OFFLOAD:
1319 break;
1320 case DIRECT:
1321 case DUPLICATING:
1322 case RECORD:
1323 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001324 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1325 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001326 lStatus = BAD_VALUE;
1327 goto Exit;
1328 }
Eric Laurent81784c32012-11-19 14:55:58 -08001329 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001330
Eric Laurent81784c32012-11-19 14:55:58 -08001331 // Only Pre processor effects are allowed on input threads and only on input threads
1332 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1333 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1334 desc->name, desc->flags, mType);
1335 lStatus = BAD_VALUE;
1336 goto Exit;
1337 }
1338
1339 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1340
1341 { // scope for mLock
1342 Mutex::Autolock _l(mLock);
1343
1344 // check for existing effect chain with the requested audio session
1345 chain = getEffectChain_l(sessionId);
1346 if (chain == 0) {
1347 // create a new chain for this session
1348 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1349 chain = new EffectChain(this, sessionId);
1350 addEffectChain_l(chain);
1351 chain->setStrategy(getStrategyForSession_l(sessionId));
1352 chainCreated = true;
1353 } else {
1354 effect = chain->getEffectFromDesc_l(desc);
1355 }
1356
1357 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1358
1359 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001360 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001361 // Check CPU and memory usage
1362 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1363 if (lStatus != NO_ERROR) {
1364 goto Exit;
1365 }
1366 effectRegistered = true;
1367 // create a new effect module if none present in the chain
1368 effect = new EffectModule(this, chain, desc, id, sessionId);
1369 lStatus = effect->status();
1370 if (lStatus != NO_ERROR) {
1371 goto Exit;
1372 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001373 effect->setOffloaded(mType == OFFLOAD, mId);
1374
Eric Laurent81784c32012-11-19 14:55:58 -08001375 lStatus = chain->addEffect_l(effect);
1376 if (lStatus != NO_ERROR) {
1377 goto Exit;
1378 }
1379 effectCreated = true;
1380
1381 effect->setDevice(mOutDevice);
1382 effect->setDevice(mInDevice);
1383 effect->setMode(mAudioFlinger->getMode());
1384 effect->setAudioSource(mAudioSource);
1385 }
1386 // create effect handle and connect it to effect module
1387 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001388 lStatus = handle->initCheck();
1389 if (lStatus == OK) {
1390 lStatus = effect->addHandle(handle.get());
1391 }
Eric Laurent81784c32012-11-19 14:55:58 -08001392 if (enabled != NULL) {
1393 *enabled = (int)effect->isEnabled();
1394 }
1395 }
1396
1397Exit:
1398 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1399 Mutex::Autolock _l(mLock);
1400 if (effectCreated) {
1401 chain->removeEffect_l(effect);
1402 }
1403 if (effectRegistered) {
1404 AudioSystem::unregisterEffect(effect->id());
1405 }
1406 if (chainCreated) {
1407 removeEffectChain_l(chain);
1408 }
1409 handle.clear();
1410 }
1411
Glenn Kasten9156ef32013-08-06 15:39:08 -07001412 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001413 return handle;
1414}
1415
Glenn Kastend848eb42016-03-08 13:42:11 -08001416sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1417 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001418{
1419 Mutex::Autolock _l(mLock);
1420 return getEffect_l(sessionId, effectId);
1421}
1422
Glenn Kastend848eb42016-03-08 13:42:11 -08001423sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1424 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001425{
1426 sp<EffectChain> chain = getEffectChain_l(sessionId);
1427 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1428}
1429
1430// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1431// PlaybackThread::mLock held
1432status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1433{
1434 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001435 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001436 sp<EffectChain> chain = getEffectChain_l(sessionId);
1437 bool chainCreated = false;
1438
Eric Laurent5baf2af2013-09-12 17:37:00 -07001439 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1440 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1441 this, effect->desc().name, effect->desc().flags);
1442
Eric Laurent81784c32012-11-19 14:55:58 -08001443 if (chain == 0) {
1444 // create a new chain for this session
1445 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1446 chain = new EffectChain(this, sessionId);
1447 addEffectChain_l(chain);
1448 chain->setStrategy(getStrategyForSession_l(sessionId));
1449 chainCreated = true;
1450 }
1451 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1452
1453 if (chain->getEffectFromId_l(effect->id()) != 0) {
1454 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1455 this, effect->desc().name, chain.get());
1456 return BAD_VALUE;
1457 }
1458
Eric Laurent5baf2af2013-09-12 17:37:00 -07001459 effect->setOffloaded(mType == OFFLOAD, mId);
1460
Eric Laurent81784c32012-11-19 14:55:58 -08001461 status_t status = chain->addEffect_l(effect);
1462 if (status != NO_ERROR) {
1463 if (chainCreated) {
1464 removeEffectChain_l(chain);
1465 }
1466 return status;
1467 }
1468
1469 effect->setDevice(mOutDevice);
1470 effect->setDevice(mInDevice);
1471 effect->setMode(mAudioFlinger->getMode());
1472 effect->setAudioSource(mAudioSource);
1473 return NO_ERROR;
1474}
1475
1476void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1477
1478 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1479 effect_descriptor_t desc = effect->desc();
1480 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1481 detachAuxEffect_l(effect->id());
1482 }
1483
1484 sp<EffectChain> chain = effect->chain().promote();
1485 if (chain != 0) {
1486 // remove effect chain if removing last effect
1487 if (chain->removeEffect_l(effect) == 0) {
1488 removeEffectChain_l(chain);
1489 }
1490 } else {
1491 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1492 }
1493}
1494
1495void AudioFlinger::ThreadBase::lockEffectChains_l(
1496 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1497{
1498 effectChains = mEffectChains;
1499 for (size_t i = 0; i < mEffectChains.size(); i++) {
1500 mEffectChains[i]->lock();
1501 }
1502}
1503
1504void AudioFlinger::ThreadBase::unlockEffectChains(
1505 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1506{
1507 for (size_t i = 0; i < effectChains.size(); i++) {
1508 effectChains[i]->unlock();
1509 }
1510}
1511
Glenn Kastend848eb42016-03-08 13:42:11 -08001512sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001513{
1514 Mutex::Autolock _l(mLock);
1515 return getEffectChain_l(sessionId);
1516}
1517
Glenn Kastend848eb42016-03-08 13:42:11 -08001518sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1519 const
Eric Laurent81784c32012-11-19 14:55:58 -08001520{
1521 size_t size = mEffectChains.size();
1522 for (size_t i = 0; i < size; i++) {
1523 if (mEffectChains[i]->sessionId() == sessionId) {
1524 return mEffectChains[i];
1525 }
1526 }
1527 return 0;
1528}
1529
1530void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1531{
1532 Mutex::Autolock _l(mLock);
1533 size_t size = mEffectChains.size();
1534 for (size_t i = 0; i < size; i++) {
1535 mEffectChains[i]->setMode_l(mode);
1536 }
1537}
1538
Eric Laurent83b88082014-06-20 18:31:16 -07001539void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1540{
1541 config->type = AUDIO_PORT_TYPE_MIX;
1542 config->ext.mix.handle = mId;
1543 config->sample_rate = mSampleRate;
1544 config->format = mFormat;
1545 config->channel_mask = mChannelMask;
1546 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1547 AUDIO_PORT_CONFIG_FORMAT;
1548}
1549
Eric Laurent72e3f392015-05-20 14:43:50 -07001550void AudioFlinger::ThreadBase::systemReady()
1551{
1552 Mutex::Autolock _l(mLock);
1553 if (mSystemReady) {
1554 return;
1555 }
1556 mSystemReady = true;
1557
1558 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1559 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1560 }
1561 mPendingConfigEvents.clear();
1562}
1563
Eric Laurent83b88082014-06-20 18:31:16 -07001564
Eric Laurent81784c32012-11-19 14:55:58 -08001565// ----------------------------------------------------------------------------
1566// Playback
1567// ----------------------------------------------------------------------------
1568
1569AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1570 AudioStreamOut* output,
1571 audio_io_handle_t id,
1572 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001573 type_t type,
Eric Laurent51716182016-02-29 18:00:56 -08001574 bool systemReady,
1575 uint32_t bitRate)
Eric Laurent72e3f392015-05-20 14:43:50 -07001576 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001577 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001578 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001579 mMixerBuffer(NULL),
1580 mMixerBufferSize(0),
1581 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1582 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001583 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001584 mEffectBuffer(NULL),
1585 mEffectBufferSize(0),
1586 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1587 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001588 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001589 mFramesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001590 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001591 // mStreamTypes[] initialized in constructor body
1592 mOutput(output),
1593 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1594 mMixerStatus(MIXER_IDLE),
1595 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001596 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001597 mBytesRemaining(0),
1598 mCurrentWriteLength(0),
1599 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001600 mWriteAckSequence(0),
1601 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001602 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001603 mScreenState(AudioFlinger::mScreenState),
1604 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001605 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001606 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001607{
Glenn Kastend7dca052015-03-05 16:05:54 -08001608 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1609 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001610
1611 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1612 // it would be safer to explicitly pass initial masterVolume/masterMute as
1613 // parameter.
1614 //
1615 // If the HAL we are using has support for master volume or master mute,
1616 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1617 // and the mute set to false).
1618 mMasterVolume = audioFlinger->masterVolume_l();
1619 mMasterMute = audioFlinger->masterMute_l();
1620 if (mOutput && mOutput->audioHwDev) {
1621 if (mOutput->audioHwDev->canSetMasterVolume()) {
1622 mMasterVolume = 1.0;
1623 }
1624
1625 if (mOutput->audioHwDev->canSetMasterMute()) {
1626 mMasterMute = false;
1627 }
1628 }
1629
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001630 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001631
Eric Laurent223fd5c2014-11-11 13:43:36 -08001632 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001633 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001634 stream = (audio_stream_type_t) (stream + 1)) {
1635 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1636 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1637 }
Eric Laurent51716182016-02-29 18:00:56 -08001638
1639 if (audio_has_proportional_frames(mFormat)) {
1640 mBufferDurationUs = (uint32_t)((mNormalFrameCount * 1000000LL) / mSampleRate);
1641 } else {
1642 bitRate = bitRate != 0 ? bitRate : kOffloadDefaultBitRateBps;
1643 mBufferDurationUs = (uint32_t)((mBufferSize * 8 * 1000000LL) / bitRate);
1644 }
Eric Laurent81784c32012-11-19 14:55:58 -08001645}
1646
1647AudioFlinger::PlaybackThread::~PlaybackThread()
1648{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001649 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001650 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001651 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001652 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001653}
1654
1655void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1656{
1657 dumpInternals(fd, args);
1658 dumpTracks(fd, args);
1659 dumpEffectChains(fd, args);
1660}
1661
Glenn Kasten0f11b512014-01-31 16:18:54 -08001662void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001663{
1664 const size_t SIZE = 256;
1665 char buffer[SIZE];
1666 String8 result;
1667
Marco Nelissenb2208842014-02-07 14:00:50 -08001668 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001669 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1670 const stream_type_t *st = &mStreamTypes[i];
1671 if (i > 0) {
1672 result.appendFormat(", ");
1673 }
1674 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1675 if (st->mute) {
1676 result.append("M");
1677 }
1678 }
1679 result.append("\n");
1680 write(fd, result.string(), result.length());
1681 result.clear();
1682
Eric Laurent81784c32012-11-19 14:55:58 -08001683 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1684 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001685 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001686 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001687
1688 size_t numtracks = mTracks.size();
1689 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001690 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001691 size_t numactiveseen = 0;
1692 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001693 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001694 Track::appendDumpHeader(result);
1695 for (size_t i = 0; i < numtracks; ++i) {
1696 sp<Track> track = mTracks[i];
1697 if (track != 0) {
1698 bool active = mActiveTracks.indexOf(track) >= 0;
1699 if (active) {
1700 numactiveseen++;
1701 }
1702 track->dump(buffer, SIZE, active);
1703 result.append(buffer);
1704 }
1705 }
1706 } else {
1707 result.append("\n");
1708 }
1709 if (numactiveseen != numactive) {
1710 // some tracks in the active list were not in the tracks list
1711 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1712 " not in the track list\n");
1713 result.append(buffer);
1714 Track::appendDumpHeader(result);
1715 for (size_t i = 0; i < numactive; ++i) {
1716 sp<Track> track = mActiveTracks[i].promote();
1717 if (track != 0 && mTracks.indexOf(track) < 0) {
1718 track->dump(buffer, SIZE, true);
1719 result.append(buffer);
1720 }
1721 }
1722 }
1723
1724 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001725}
1726
1727void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1728{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001729 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001730
1731 dumpBase(fd, args);
1732
Elliott Hughes87cebad2014-05-22 10:14:43 -07001733 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1734 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1735 dprintf(fd, " Total writes: %d\n", mNumWrites);
1736 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1737 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1738 dprintf(fd, " Suspend count: %d\n", mSuspended);
1739 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1740 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1741 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1742 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001743 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001744 AudioStreamOut *output = mOutput;
1745 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1746 String8 flagsAsString = outputFlagsToString(flags);
1747 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001748}
1749
1750// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001751
1752void AudioFlinger::PlaybackThread::onFirstRef()
1753{
Glenn Kastend7dca052015-03-05 16:05:54 -08001754 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001755}
1756
1757// ThreadBase virtuals
1758void AudioFlinger::PlaybackThread::preExit()
1759{
1760 ALOGV(" preExit()");
1761 // FIXME this is using hard-coded strings but in the future, this functionality will be
1762 // converted to use audio HAL extensions required to support tunneling
1763 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1764}
1765
1766// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1767sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1768 const sp<AudioFlinger::Client>& client,
1769 audio_stream_type_t streamType,
1770 uint32_t sampleRate,
1771 audio_format_t format,
1772 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001773 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001774 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001775 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001776 IAudioFlinger::track_flags_t *flags,
1777 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001778 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001779 status_t *status)
1780{
Glenn Kasten74935e42013-12-19 08:56:45 -08001781 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001782 sp<Track> track;
1783 status_t lStatus;
1784
Eric Laurent81784c32012-11-19 14:55:58 -08001785 // client expresses a preference for FAST, but we get the final say
1786 if (*flags & IAudioFlinger::TRACK_FAST) {
1787 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001788 // either of these use cases:
1789 (
1790 // use case 1: shared buffer with any frame count
1791 (
1792 (sharedBuffer != 0)
1793 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001794 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001795 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001796 // we formerly checked for a callback handler (non-0 tid),
1797 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001798 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001799 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001800 )
1801 ) &&
1802 // PCM data
1803 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001804 // TODO: extract as a data library function that checks that a computationally
1805 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001806 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001807 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1808 (channelMask == AUDIO_CHANNEL_OUT_MONO
1809 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001810 // hardware sample rate
1811 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001812 // normal mixer has an associated fast mixer
1813 hasFastMixer() &&
1814 // there are sufficient fast track slots available
1815 (mFastTrackAvailMask != 0)
1816 // FIXME test that MixerThread for this fast track has a capable output HAL
1817 // FIXME add a permission test also?
1818 ) {
1819 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1820 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001821 // read the fast track multiplier property the first time it is needed
1822 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1823 if (ok != 0) {
1824 ALOGE("%s pthread_once failed: %d", __func__, ok);
1825 }
1826 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001827 }
1828 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1829 frameCount, mFrameCount);
1830 } else {
Glenn Kastend79072e2016-01-06 08:41:20 -08001831 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001832 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1833 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001834 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001835 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001836 audio_is_linear_pcm(format),
1837 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1838 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001839 }
1840 }
1841 // For normal PCM streaming tracks, update minimum frame count.
1842 // For compatibility with AudioTrack calculation, buffer depth is forced
1843 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1844 // This is probably too conservative, but legacy application code may depend on it.
1845 // If you change this calculation, also review the start threshold which is related.
1846 if (!(*flags & IAudioFlinger::TRACK_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001847 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001848 // this must match AudioTrack.cpp calculateMinFrameCount().
1849 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001850 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1851 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1852 if (minBufCount < 2) {
1853 minBufCount = 2;
1854 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001855 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1856 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001857 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001858 minBufCount * sourceFramesNeededWithTimestretch(
1859 sampleRate, mNormalFrameCount,
1860 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001861 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001862 frameCount = minFrameCount;
1863 }
Eric Laurent81784c32012-11-19 14:55:58 -08001864 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001865 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001866
Glenn Kastenc3df8382014-03-13 15:05:25 -07001867 switch (mType) {
1868
1869 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001870 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001871 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001872 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1873 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001874 sampleRate, format, channelMask, mOutput, mFormat);
1875 lStatus = BAD_VALUE;
1876 goto Exit;
1877 }
1878 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001879 break;
1880
1881 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001882 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001883 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1884 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001885 sampleRate, format, channelMask, mOutput, mFormat);
1886 lStatus = BAD_VALUE;
1887 goto Exit;
1888 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001889 break;
1890
1891 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001892 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001893 ALOGE("createTrack_l() Bad parameter: format %#x \""
1894 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001895 format, mOutput, mFormat);
1896 lStatus = BAD_VALUE;
1897 goto Exit;
1898 }
Andy Hungcd044842014-08-07 11:04:34 -07001899 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001900 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1901 lStatus = BAD_VALUE;
1902 goto Exit;
1903 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001904 break;
1905
Eric Laurent81784c32012-11-19 14:55:58 -08001906 }
1907
1908 lStatus = initCheck();
1909 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001910 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001911 goto Exit;
1912 }
1913
1914 { // scope for mLock
1915 Mutex::Autolock _l(mLock);
1916
1917 // all tracks in same audio session must share the same routing strategy otherwise
1918 // conflicts will happen when tracks are moved from one output to another by audio policy
1919 // manager
1920 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1921 for (size_t i = 0; i < mTracks.size(); ++i) {
1922 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001923 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001924 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1925 if (sessionId == t->sessionId() && strategy != actual) {
1926 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1927 strategy, actual);
1928 lStatus = BAD_VALUE;
1929 goto Exit;
1930 }
1931 }
1932 }
1933
Glenn Kastend79072e2016-01-06 08:41:20 -08001934 track = new Track(this, client, streamType, sampleRate, format,
1935 channelMask, frameCount, NULL, sharedBuffer,
1936 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07001937
Glenn Kasten03003332013-08-06 15:40:54 -07001938 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1939 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001940 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001941 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001942 goto Exit;
1943 }
1944 mTracks.add(track);
1945
1946 sp<EffectChain> chain = getEffectChain_l(sessionId);
1947 if (chain != 0) {
1948 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1949 track->setMainBuffer(chain->inBuffer());
1950 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1951 chain->incTrackCnt();
1952 }
1953
1954 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1955 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1956 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1957 // so ask activity manager to do this on our behalf
1958 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1959 }
1960 }
1961
1962 lStatus = NO_ERROR;
1963
1964Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001965 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001966 return track;
1967}
1968
1969uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1970{
1971 return latency;
1972}
1973
1974uint32_t AudioFlinger::PlaybackThread::latency() const
1975{
1976 Mutex::Autolock _l(mLock);
1977 return latency_l();
1978}
1979uint32_t AudioFlinger::PlaybackThread::latency_l() const
1980{
1981 if (initCheck() == NO_ERROR) {
1982 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1983 } else {
1984 return 0;
1985 }
1986}
1987
1988void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1989{
1990 Mutex::Autolock _l(mLock);
1991 // Don't apply master volume in SW if our HAL can do it for us.
1992 if (mOutput && mOutput->audioHwDev &&
1993 mOutput->audioHwDev->canSetMasterVolume()) {
1994 mMasterVolume = 1.0;
1995 } else {
1996 mMasterVolume = value;
1997 }
1998}
1999
2000void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2001{
2002 Mutex::Autolock _l(mLock);
2003 // Don't apply master mute in SW if our HAL can do it for us.
2004 if (mOutput && mOutput->audioHwDev &&
2005 mOutput->audioHwDev->canSetMasterMute()) {
2006 mMasterMute = false;
2007 } else {
2008 mMasterMute = muted;
2009 }
2010}
2011
2012void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2013{
2014 Mutex::Autolock _l(mLock);
2015 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002016 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002017}
2018
2019void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2020{
2021 Mutex::Autolock _l(mLock);
2022 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002023 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002024}
2025
2026float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2027{
2028 Mutex::Autolock _l(mLock);
2029 return mStreamTypes[stream].volume;
2030}
2031
2032// addTrack_l() must be called with ThreadBase::mLock held
2033status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2034{
2035 status_t status = ALREADY_EXISTS;
2036
Eric Laurent81784c32012-11-19 14:55:58 -08002037 if (mActiveTracks.indexOf(track) < 0) {
2038 // the track is newly added, make sure it fills up all its
2039 // buffers before playing. This is to ensure the client will
2040 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002041 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002042 TrackBase::track_state state = track->mState;
2043 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002044 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002045 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002046 mLock.lock();
2047 // abort track was stopped/paused while we released the lock
2048 if (state != track->mState) {
2049 if (status == NO_ERROR) {
2050 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002051 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002052 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002053 mLock.lock();
2054 }
2055 return INVALID_OPERATION;
2056 }
2057 // abort if start is rejected by audio policy manager
2058 if (status != NO_ERROR) {
2059 return PERMISSION_DENIED;
2060 }
2061#ifdef ADD_BATTERY_DATA
2062 // to track the speaker usage
2063 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2064#endif
2065 }
2066
Eric Laurent51716182016-02-29 18:00:56 -08002067 // set retry count for buffer fill
2068 if (track->isOffloaded()) {
2069 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2070 } else {
2071 track->mRetryCount = kMaxTrackStartupRetries;
2072 }
2073
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002074 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08002075 track->mResetDone = false;
2076 track->mPresentationCompleteFrames = 0;
2077 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002078 mWakeLockUids.add(track->uid());
2079 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002080 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002081 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2082 if (chain != 0) {
2083 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2084 track->sessionId());
2085 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002086 }
2087
2088 status = NO_ERROR;
2089 }
2090
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002091 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002092 return status;
2093}
2094
Eric Laurentbfb1b832013-01-07 09:53:42 -08002095bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002096{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002097 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002098 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002099 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2100 track->mState = TrackBase::STOPPED;
2101 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002102 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002103 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002104 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002105 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002106
2107 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002108}
2109
2110void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2111{
2112 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2113 mTracks.remove(track);
2114 deleteTrackName_l(track->name());
2115 // redundant as track is about to be destroyed, for dumpsys only
2116 track->mName = -1;
2117 if (track->isFastTrack()) {
2118 int index = track->mFastIndex;
2119 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
2120 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2121 mFastTrackAvailMask |= 1 << index;
2122 // redundant as track is about to be destroyed, for dumpsys only
2123 track->mFastIndex = -1;
2124 }
2125 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2126 if (chain != 0) {
2127 chain->decTrackCnt();
2128 }
2129}
2130
Eric Laurentede6c3b2013-09-19 14:37:46 -07002131void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002132{
2133 // Thread could be blocked waiting for async
2134 // so signal it to handle state changes immediately
2135 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2136 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2137 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002138 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002139}
2140
Eric Laurent81784c32012-11-19 14:55:58 -08002141String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2142{
Eric Laurent81784c32012-11-19 14:55:58 -08002143 Mutex::Autolock _l(mLock);
2144 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002145 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002146 }
2147
Glenn Kastend8ea6992013-07-16 14:17:15 -07002148 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2149 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002150 free(s);
2151 return out_s8;
2152}
2153
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002154void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002155 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2156 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002157
Eric Laurent73e26b62015-04-27 16:55:58 -07002158 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002159
2160 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002161 case AUDIO_OUTPUT_OPENED:
2162 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002163 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002164 desc->mChannelMask = mChannelMask;
2165 desc->mSamplingRate = mSampleRate;
2166 desc->mFormat = mFormat;
2167 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002168 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002169 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002170 break;
2171
Eric Laurent73e26b62015-04-27 16:55:58 -07002172 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002173 default:
2174 break;
2175 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002176 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002177}
2178
Eric Laurentbfb1b832013-01-07 09:53:42 -08002179void AudioFlinger::PlaybackThread::writeCallback()
2180{
2181 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002182 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002183}
2184
2185void AudioFlinger::PlaybackThread::drainCallback()
2186{
2187 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002188 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002189}
2190
Eric Laurent3b4529e2013-09-05 18:09:19 -07002191void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002192{
2193 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002194 // reject out of sequence requests
2195 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2196 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002197 mWaitWorkCV.signal();
2198 }
2199}
2200
Eric Laurent3b4529e2013-09-05 18:09:19 -07002201void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002202{
2203 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002204 // reject out of sequence requests
2205 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2206 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002207 mWaitWorkCV.signal();
2208 }
2209}
2210
2211// static
2212int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002213 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002214 void *cookie)
2215{
2216 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2217 ALOGV("asyncCallback() event %d", event);
2218 switch (event) {
2219 case STREAM_CBK_EVENT_WRITE_READY:
2220 me->writeCallback();
2221 break;
2222 case STREAM_CBK_EVENT_DRAIN_READY:
2223 me->drainCallback();
2224 break;
2225 default:
2226 ALOGW("asyncCallback() unknown event %d", event);
2227 break;
2228 }
2229 return 0;
2230}
2231
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002232void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002233{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002234 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002235 mSampleRate = mOutput->getSampleRate();
2236 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002237 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002238 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002239 }
Andy Hung9a592762014-07-21 21:56:01 -07002240 if ((mType == MIXER || mType == DUPLICATING)
2241 && !isValidPcmSinkChannelMask(mChannelMask)) {
2242 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2243 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002244 }
Andy Hunge5412692014-05-16 11:25:07 -07002245 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002246
2247 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002248 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002249 // Get format from the shim, which will be different than the HAL format
2250 // if playing compressed audio over HDMI passthrough.
2251 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002252 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002253 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002254 }
Andy Hung6146c082014-03-18 11:56:15 -07002255 if ((mType == MIXER || mType == DUPLICATING)
2256 && !isValidPcmSinkFormat(mFormat)) {
2257 LOG_FATAL("HAL format %#x not supported for mixed output",
2258 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002259 }
Phil Burk062e67a2015-02-11 13:40:50 -08002260 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002261 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2262 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002263 if (mFrameCount & 15) {
2264 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2265 mFrameCount);
2266 }
2267
Eric Laurentbfb1b832013-01-07 09:53:42 -08002268 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2269 (mOutput->stream->set_callback != NULL)) {
2270 if (mOutput->stream->set_callback(mOutput->stream,
2271 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2272 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002273 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002274 }
2275 }
2276
Eric Laurentd1f69b02014-12-15 14:33:13 -08002277 mHwSupportsPause = false;
2278 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2279 if (mOutput->stream->pause != NULL) {
2280 if (mOutput->stream->resume != NULL) {
2281 mHwSupportsPause = true;
2282 } else {
2283 ALOGW("direct output implements pause but not resume");
2284 }
2285 } else if (mOutput->stream->resume != NULL) {
2286 ALOGW("direct output implements resume but not pause");
2287 }
2288 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002289 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2290 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2291 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002292
Andy Hungfbfc3952015-01-15 13:33:51 -08002293 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2294 // For best precision, we use float instead of the associated output
2295 // device format (typically PCM 16 bit).
2296
2297 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2298 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2299 mBufferSize = mFrameSize * mFrameCount;
2300
2301 // TODO: We currently use the associated output device channel mask and sample rate.
2302 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2303 // (if a valid mask) to avoid premature downmix.
2304 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2305 // instead of the output device sample rate to avoid loss of high frequency information.
2306 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2307 }
2308
Andy Hung09a50072014-02-27 14:30:47 -08002309 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002310 double multiplier = 1.0;
2311 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2312 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002313 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2314 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002315 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2316 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2317 maxNormalFrameCount = maxNormalFrameCount & ~15;
2318 if (maxNormalFrameCount < minNormalFrameCount) {
2319 maxNormalFrameCount = minNormalFrameCount;
2320 }
2321 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2322 if (multiplier <= 1.0) {
2323 multiplier = 1.0;
2324 } else if (multiplier <= 2.0) {
2325 if (2 * mFrameCount <= maxNormalFrameCount) {
2326 multiplier = 2.0;
2327 } else {
2328 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2329 }
2330 } else {
2331 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002332 // 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 -08002333 // track, but we sometimes have to do this to satisfy the maximum frame count
2334 // constraint)
2335 // FIXME this rounding up should not be done if no HAL SRC
2336 uint32_t truncMult = (uint32_t) multiplier;
2337 if ((truncMult & 1)) {
2338 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2339 ++truncMult;
2340 }
2341 }
2342 multiplier = (double) truncMult;
2343 }
2344 }
2345 mNormalFrameCount = multiplier * mFrameCount;
2346 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002347 if (mType == MIXER || mType == DUPLICATING) {
2348 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2349 }
Andy Hung09a50072014-02-27 14:30:47 -08002350 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002351 mNormalFrameCount);
2352
Andy Hung08fb1742015-05-31 23:22:10 -07002353 // Check if we want to throttle the processing to no more than 2x normal rate
2354 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002355 mThreadThrottleTimeMs = 0;
2356 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002357 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2358
Andy Hung010a1a12014-03-13 13:57:33 -07002359 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2360 // Originally this was int16_t[] array, need to remove legacy implications.
2361 free(mSinkBuffer);
2362 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002363 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2364 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2365 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002366 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002367
Andy Hung69aed5f2014-02-25 17:24:40 -08002368 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2369 // drives the output.
2370 free(mMixerBuffer);
2371 mMixerBuffer = NULL;
2372 if (mMixerBufferEnabled) {
2373 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2374 mMixerBufferSize = mNormalFrameCount * mChannelCount
2375 * audio_bytes_per_sample(mMixerBufferFormat);
2376 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2377 }
Andy Hung98ef9782014-03-04 14:46:50 -08002378 free(mEffectBuffer);
2379 mEffectBuffer = NULL;
2380 if (mEffectBufferEnabled) {
2381 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2382 mEffectBufferSize = mNormalFrameCount * mChannelCount
2383 * audio_bytes_per_sample(mEffectBufferFormat);
2384 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2385 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002386
Eric Laurent81784c32012-11-19 14:55:58 -08002387 // force reconfiguration of effect chains and engines to take new buffer size and audio
2388 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002389 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002390 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2391 // matter.
2392 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2393 Vector< sp<EffectChain> > effectChains = mEffectChains;
2394 for (size_t i = 0; i < effectChains.size(); i ++) {
2395 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2396 }
2397}
2398
2399
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002400status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002401{
2402 if (halFrames == NULL || dspFrames == NULL) {
2403 return BAD_VALUE;
2404 }
2405 Mutex::Autolock _l(mLock);
2406 if (initCheck() != NO_ERROR) {
2407 return INVALID_OPERATION;
2408 }
Andy Hung818e7a32016-02-16 18:08:07 -08002409 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002410 *halFrames = framesWritten;
2411
2412 if (isSuspended()) {
2413 // return an estimation of rendered frames when the output is suspended
2414 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002415 *dspFrames = (uint32_t)
2416 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002417 return NO_ERROR;
2418 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002419 status_t status;
2420 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002421 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002422 *dspFrames = (size_t)frames;
2423 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002424 }
2425}
2426
Glenn Kastend848eb42016-03-08 13:42:11 -08002427uint32_t AudioFlinger::PlaybackThread::hasAudioSession(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002428{
2429 Mutex::Autolock _l(mLock);
2430 uint32_t result = 0;
2431 if (getEffectChain_l(sessionId) != 0) {
2432 result = EFFECT_SESSION;
2433 }
2434
2435 for (size_t i = 0; i < mTracks.size(); ++i) {
2436 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002437 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002438 result |= TRACK_SESSION;
2439 break;
2440 }
2441 }
2442
2443 return result;
2444}
2445
Glenn Kastend848eb42016-03-08 13:42:11 -08002446uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002447{
2448 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2449 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2450 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2451 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2452 }
2453 for (size_t i = 0; i < mTracks.size(); i++) {
2454 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002455 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002456 return AudioSystem::getStrategyForStream(track->streamType());
2457 }
2458 }
2459 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2460}
2461
2462
Phil Burk062e67a2015-02-11 13:40:50 -08002463AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002464{
2465 Mutex::Autolock _l(mLock);
2466 return mOutput;
2467}
2468
Phil Burk062e67a2015-02-11 13:40:50 -08002469AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002470{
2471 Mutex::Autolock _l(mLock);
2472 AudioStreamOut *output = mOutput;
2473 mOutput = NULL;
2474 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2475 // must push a NULL and wait for ack
2476 mOutputSink.clear();
2477 mPipeSink.clear();
2478 mNormalSink.clear();
2479 return output;
2480}
2481
2482// this method must always be called either with ThreadBase mLock held or inside the thread loop
2483audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2484{
2485 if (mOutput == NULL) {
2486 return NULL;
2487 }
2488 return &mOutput->stream->common;
2489}
2490
2491uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2492{
2493 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2494}
2495
2496status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2497{
2498 if (!isValidSyncEvent(event)) {
2499 return BAD_VALUE;
2500 }
2501
2502 Mutex::Autolock _l(mLock);
2503
2504 for (size_t i = 0; i < mTracks.size(); ++i) {
2505 sp<Track> track = mTracks[i];
2506 if (event->triggerSession() == track->sessionId()) {
2507 (void) track->setSyncEvent(event);
2508 return NO_ERROR;
2509 }
2510 }
2511
2512 return NAME_NOT_FOUND;
2513}
2514
2515bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2516{
2517 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2518}
2519
2520void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2521 const Vector< sp<Track> >& tracksToRemove)
2522{
2523 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002524 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002525 for (size_t i = 0 ; i < count ; i++) {
2526 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002527 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002528 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002529 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002530#ifdef ADD_BATTERY_DATA
2531 // to track the speaker usage
2532 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2533#endif
2534 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002535 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002536 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002537 }
Eric Laurent81784c32012-11-19 14:55:58 -08002538 }
2539 }
2540 }
Eric Laurent81784c32012-11-19 14:55:58 -08002541}
2542
2543void AudioFlinger::PlaybackThread::checkSilentMode_l()
2544{
2545 if (!mMasterMute) {
2546 char value[PROPERTY_VALUE_MAX];
2547 if (property_get("ro.audio.silent", value, "0") > 0) {
2548 char *endptr;
2549 unsigned long ul = strtoul(value, &endptr, 0);
2550 if (*endptr == '\0' && ul != 0) {
2551 ALOGD("Silence is golden");
2552 // The setprop command will not allow a property to be changed after
2553 // the first time it is set, so we don't have to worry about un-muting.
2554 setMasterMute_l(true);
2555 }
2556 }
2557 }
2558}
2559
2560// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002561ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002562{
2563 // FIXME rewrite to reduce number of system calls
2564 mLastWriteTime = systemTime();
2565 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002566 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002567 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002568
2569 // If an NBAIO sink is present, use it to write the normal mixer's submix
2570 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002571
Andy Hung010a1a12014-03-13 13:57:33 -07002572 const size_t count = mBytesRemaining / mFrameSize;
2573
Simon Wilson2d590962012-11-29 15:18:50 -08002574 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002575 // update the setpoint when AudioFlinger::mScreenState changes
2576 uint32_t screenState = AudioFlinger::mScreenState;
2577 if (screenState != mScreenState) {
2578 mScreenState = screenState;
2579 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2580 if (pipe != NULL) {
2581 pipe->setAvgFrames((mScreenState & 1) ?
2582 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2583 }
2584 }
Andy Hung010a1a12014-03-13 13:57:33 -07002585 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002586 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002587 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002588 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002589 } else {
2590 bytesWritten = framesWritten;
2591 }
2592 // otherwise use the HAL / AudioStreamOut directly
2593 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002594 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002595
Eric Laurentbfb1b832013-01-07 09:53:42 -08002596 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002597 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2598 mWriteAckSequence += 2;
2599 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002600 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002601 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002602 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002603 // FIXME We should have an implementation of timestamps for direct output threads.
2604 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002605 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002606
Eric Laurentbfb1b832013-01-07 09:53:42 -08002607 if (mUseAsyncWrite &&
2608 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2609 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002610 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002611 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002612 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002613 }
Eric Laurent81784c32012-11-19 14:55:58 -08002614 }
2615
Eric Laurent81784c32012-11-19 14:55:58 -08002616 mNumWrites++;
2617 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002618 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002619 return bytesWritten;
2620}
2621
2622void AudioFlinger::PlaybackThread::threadLoop_drain()
2623{
2624 if (mOutput->stream->drain) {
2625 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2626 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002627 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2628 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002629 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002630 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002631 }
2632 mOutput->stream->drain(mOutput->stream,
2633 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2634 : AUDIO_DRAIN_ALL);
2635 }
2636}
2637
2638void AudioFlinger::PlaybackThread::threadLoop_exit()
2639{
Eric Laurent275e8e92014-11-30 15:14:47 -08002640 {
2641 Mutex::Autolock _l(mLock);
2642 for (size_t i = 0; i < mTracks.size(); i++) {
2643 sp<Track> track = mTracks[i];
2644 track->invalidate();
2645 }
2646 }
Eric Laurent81784c32012-11-19 14:55:58 -08002647}
2648
2649/*
2650The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002651 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002652 - mActiveSleepTimeUs from activeSleepTimeUs()
2653 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002654 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2655 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002656 - maxPeriod from frame count and sample rate (MIXER only)
2657
2658The parameters that affect these derived values are:
2659 - frame count
2660 - frame size
2661 - sample rate
2662 - device type: A2DP or not
2663 - device latency
2664 - format: PCM or not
2665 - active sleep time
2666 - idle sleep time
2667*/
2668
2669void AudioFlinger::PlaybackThread::cacheParameters_l()
2670{
Andy Hung25c2dac2014-02-27 14:56:00 -08002671 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002672 mActiveSleepTimeUs = activeSleepTimeUs();
2673 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002674
2675 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2676 // truncating audio when going to standby.
2677 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2678 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2679 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2680 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2681 }
2682 }
Eric Laurent81784c32012-11-19 14:55:58 -08002683}
2684
2685void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2686{
Glenn Kasten7c027242012-12-26 14:43:16 -08002687 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002688 this, streamType, mTracks.size());
2689 Mutex::Autolock _l(mLock);
2690
2691 size_t size = mTracks.size();
2692 for (size_t i = 0; i < size; i++) {
2693 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002694 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002695 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002696 }
2697 }
2698}
2699
2700status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2701{
Glenn Kastend848eb42016-03-08 13:42:11 -08002702 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002703 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2704 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002705 bool ownsBuffer = false;
2706
2707 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002708 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002709 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002710 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002711 if (mType != DIRECT) {
2712 size_t numSamples = mNormalFrameCount * mChannelCount;
2713 buffer = new int16_t[numSamples];
2714 memset(buffer, 0, numSamples * sizeof(int16_t));
2715 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2716 ownsBuffer = true;
2717 }
2718
2719 // Attach all tracks with same session ID to this chain.
2720 for (size_t i = 0; i < mTracks.size(); ++i) {
2721 sp<Track> track = mTracks[i];
2722 if (session == track->sessionId()) {
2723 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2724 buffer);
2725 track->setMainBuffer(buffer);
2726 chain->incTrackCnt();
2727 }
2728 }
2729
2730 // indicate all active tracks in the chain
2731 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2732 sp<Track> track = mActiveTracks[i].promote();
2733 if (track == 0) {
2734 continue;
2735 }
2736 if (session == track->sessionId()) {
2737 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2738 chain->incActiveTrackCnt();
2739 }
2740 }
2741 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002742 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002743 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002744 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2745 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002746 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002747 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002748 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2749 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002750 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002751 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002752 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002753 // Effect chain for other sessions are inserted at beginning of effect
2754 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002755 // sessions is not important.
2756 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2757 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2758 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002759 size_t size = mEffectChains.size();
2760 size_t i = 0;
2761 for (i = 0; i < size; i++) {
2762 if (mEffectChains[i]->sessionId() < session) {
2763 break;
2764 }
2765 }
2766 mEffectChains.insertAt(chain, i);
2767 checkSuspendOnAddEffectChain_l(chain);
2768
2769 return NO_ERROR;
2770}
2771
2772size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2773{
Glenn Kastend848eb42016-03-08 13:42:11 -08002774 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002775
2776 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2777
2778 for (size_t i = 0; i < mEffectChains.size(); i++) {
2779 if (chain == mEffectChains[i]) {
2780 mEffectChains.removeAt(i);
2781 // detach all active tracks from the chain
2782 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2783 sp<Track> track = mActiveTracks[i].promote();
2784 if (track == 0) {
2785 continue;
2786 }
2787 if (session == track->sessionId()) {
2788 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2789 chain.get(), session);
2790 chain->decActiveTrackCnt();
2791 }
2792 }
2793
2794 // detach all tracks with same session ID from this chain
2795 for (size_t i = 0; i < mTracks.size(); ++i) {
2796 sp<Track> track = mTracks[i];
2797 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002798 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002799 chain->decTrackCnt();
2800 }
2801 }
2802 break;
2803 }
2804 }
2805 return mEffectChains.size();
2806}
2807
2808status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2809 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2810{
2811 Mutex::Autolock _l(mLock);
2812 return attachAuxEffect_l(track, EffectId);
2813}
2814
2815status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2816 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2817{
2818 status_t status = NO_ERROR;
2819
2820 if (EffectId == 0) {
2821 track->setAuxBuffer(0, NULL);
2822 } else {
2823 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2824 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2825 if (effect != 0) {
2826 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2827 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2828 } else {
2829 status = INVALID_OPERATION;
2830 }
2831 } else {
2832 status = BAD_VALUE;
2833 }
2834 }
2835 return status;
2836}
2837
2838void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2839{
2840 for (size_t i = 0; i < mTracks.size(); ++i) {
2841 sp<Track> track = mTracks[i];
2842 if (track->auxEffectId() == effectId) {
2843 attachAuxEffect_l(track, 0);
2844 }
2845 }
2846}
2847
2848bool AudioFlinger::PlaybackThread::threadLoop()
2849{
2850 Vector< sp<Track> > tracksToRemove;
2851
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002852 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002853
2854 // MIXER
2855 nsecs_t lastWarning = 0;
2856
2857 // DUPLICATING
2858 // FIXME could this be made local to while loop?
2859 writeFrames = 0;
2860
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002861 int lastGeneration = 0;
2862
Eric Laurent81784c32012-11-19 14:55:58 -08002863 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002864 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002865
2866 if (mType == MIXER) {
2867 sleepTimeShift = 0;
2868 }
2869
2870 CpuStats cpuStats;
2871 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2872
2873 acquireWakeLock();
2874
Glenn Kasten9e58b552013-01-18 15:09:48 -08002875 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2876 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2877 // and then that string will be logged at the next convenient opportunity.
2878 const char *logString = NULL;
2879
Eric Laurent664539d2013-09-23 18:24:31 -07002880 checkSilentMode_l();
2881
Eric Laurent81784c32012-11-19 14:55:58 -08002882 while (!exitPending())
2883 {
2884 cpuStats.sample(myName);
2885
2886 Vector< sp<EffectChain> > effectChains;
2887
Eric Laurent81784c32012-11-19 14:55:58 -08002888 { // scope for mLock
2889
2890 Mutex::Autolock _l(mLock);
2891
Eric Laurent021cf962014-05-13 10:18:14 -07002892 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002893
Glenn Kasten9e58b552013-01-18 15:09:48 -08002894 if (logString != NULL) {
2895 mNBLogWriter->logTimestamp();
2896 mNBLogWriter->log(logString);
2897 logString = NULL;
2898 }
2899
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002900 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002901 // and associate with the sink frames written out. We need
2902 // this to convert the sink timestamp to the track timestamp.
2903 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002904 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002905 // We always fetch the timestamp here because often the downstream
2906 // sink will block whie writing.
2907 ExtendedTimestamp timestamp; // use private copy to fetch
2908 (void) mNormalSink->getTimestamp(timestamp);
2909 // copy over kernel info
2910 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
2911 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2912 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2913 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08002914 }
2915 // mFramesWritten for non-offloaded tracks are contiguous
2916 // even after standby() is called. This is useful for the track frame
2917 // to sink frame mapping.
2918 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
2919 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
2920 const size_t size = mActiveTracks.size();
2921 for (size_t i = 0; i < size; ++i) {
2922 sp<Track> t = mActiveTracks[i].promote();
2923 if (t != 0 && !t->isFastTrack()) {
2924 t->updateTrackFrameInfo(
2925 t->mAudioTrackServerProxy->framesReleased(),
2926 mFramesWritten,
2927 mTimestamp);
Andy Hunge10393e2015-06-12 13:59:33 -07002928 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002929 }
2930
Eric Laurent81784c32012-11-19 14:55:58 -08002931 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002932 if (mSignalPending) {
2933 // A signal was raised while we were unlocked
2934 mSignalPending = false;
2935 } else if (waitingAsyncCallback_l()) {
2936 if (exitPending()) {
2937 break;
2938 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002939 bool released = false;
2940 // The following works around a bug in the offload driver. Ideally we would release
2941 // the wake lock every time, but that causes the last offload buffer(s) to be
2942 // dropped while the device is on battery, so we need to hold a wake lock during
2943 // the drain phase.
2944 if (mBytesRemaining && !(mDrainSequence & 1)) {
2945 releaseWakeLock_l();
2946 released = true;
2947 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002948 mWakeLockUids.clear();
2949 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002950 ALOGV("wait async completion");
2951 mWaitWorkCV.wait(mLock);
2952 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002953 if (released) {
2954 acquireWakeLock_l();
2955 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002956 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2957 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002958
2959 continue;
2960 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002961 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002962 isSuspended()) {
2963 // put audio hardware into standby after short delay
2964 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002965
2966 threadLoop_standby();
2967
2968 mStandby = true;
2969 }
2970
2971 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2972 // we're about to wait, flush the binder command buffer
2973 IPCThreadState::self()->flushCommands();
2974
2975 clearOutputTracks();
2976
2977 if (exitPending()) {
2978 break;
2979 }
2980
2981 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002982 mWakeLockUids.clear();
2983 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002984 // wait until we have something to do...
2985 ALOGV("%s going to sleep", myName.string());
2986 mWaitWorkCV.wait(mLock);
2987 ALOGV("%s waking up", myName.string());
2988 acquireWakeLock_l();
2989
2990 mMixerStatus = MIXER_IDLE;
2991 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2992 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002993 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002994 checkSilentMode_l();
2995
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002996 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2997 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002998 if (mType == MIXER) {
2999 sleepTimeShift = 0;
3000 }
3001
3002 continue;
3003 }
3004 }
Eric Laurent81784c32012-11-19 14:55:58 -08003005 // mMixerStatusIgnoringFastTracks is also updated internally
3006 mMixerStatus = prepareTracks_l(&tracksToRemove);
3007
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003008 // compare with previously applied list
3009 if (lastGeneration != mActiveTracksGeneration) {
3010 // update wakelock
3011 updateWakeLockUids_l(mWakeLockUids);
3012 lastGeneration = mActiveTracksGeneration;
3013 }
3014
Eric Laurent81784c32012-11-19 14:55:58 -08003015 // prevent any changes in effect chain list and in each effect chain
3016 // during mixing and effect process as the audio buffers could be deleted
3017 // or modified if an effect is created or deleted
3018 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003019 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003020
Eric Laurentbfb1b832013-01-07 09:53:42 -08003021 if (mBytesRemaining == 0) {
3022 mCurrentWriteLength = 0;
3023 if (mMixerStatus == MIXER_TRACKS_READY) {
3024 // threadLoop_mix() sets mCurrentWriteLength
3025 threadLoop_mix();
3026 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3027 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003028 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003029 // must be written to HAL
3030 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003031 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003032 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003033 }
3034 }
Andy Hung98ef9782014-03-04 14:46:50 -08003035 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003036 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003037 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3038 // or mSinkBuffer (if there are no effects).
3039 //
3040 // This is done pre-effects computation; if effects change to
3041 // support higher precision, this needs to move.
3042 //
3043 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003044 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003045 if (mMixerBufferValid) {
3046 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3047 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3048
Andy Hung2ddee192015-12-18 17:34:44 -08003049 // mono blend occurs for mixer threads only (not direct or offloaded)
3050 // and is handled here if we're going directly to the sink.
3051 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003052 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3053 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003054 }
3055
Andy Hung98ef9782014-03-04 14:46:50 -08003056 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3057 mNormalFrameCount * mChannelCount);
3058 }
3059
Eric Laurentbfb1b832013-01-07 09:53:42 -08003060 mBytesRemaining = mCurrentWriteLength;
3061 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003062 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003063 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08003064 mBytesWritten += mSinkBufferSize;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003065 mFramesWritten += mSinkBufferSize / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003066 mBytesRemaining = 0;
3067 }
Eric Laurent81784c32012-11-19 14:55:58 -08003068
Eric Laurentbfb1b832013-01-07 09:53:42 -08003069 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003070 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003071 for (size_t i = 0; i < effectChains.size(); i ++) {
3072 effectChains[i]->process_l();
3073 }
Eric Laurent81784c32012-11-19 14:55:58 -08003074 }
3075 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003076 // Process effect chains for offloaded thread even if no audio
3077 // was read from audio track: process only updates effect state
3078 // and thus does have to be synchronized with audio writes but may have
3079 // to be called while waiting for async write callback
3080 if (mType == OFFLOAD) {
3081 for (size_t i = 0; i < effectChains.size(); i ++) {
3082 effectChains[i]->process_l();
3083 }
3084 }
Eric Laurent81784c32012-11-19 14:55:58 -08003085
Andy Hung98ef9782014-03-04 14:46:50 -08003086 // Only if the Effects buffer is enabled and there is data in the
3087 // Effects buffer (buffer valid), we need to
3088 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003089 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003090 if (mEffectBufferValid) {
3091 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003092
3093 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003094 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3095 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003096 }
3097
Andy Hung98ef9782014-03-04 14:46:50 -08003098 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3099 mNormalFrameCount * mChannelCount);
3100 }
3101
Eric Laurent81784c32012-11-19 14:55:58 -08003102 // enable changes in effect chain
3103 unlockEffectChains(effectChains);
3104
Eric Laurentbfb1b832013-01-07 09:53:42 -08003105 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003106 // mSleepTimeUs == 0 means we must write to audio hardware
3107 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003108 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003109 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07003110 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003111 if (ret < 0) {
3112 mBytesRemaining = 0;
3113 } else {
3114 mBytesWritten += ret;
3115 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003116 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003117 }
3118 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3119 (mMixerStatus == MIXER_DRAIN_ALL)) {
3120 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003121 }
Andy Hung08fb1742015-05-31 23:22:10 -07003122 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003123 // write blocked detection
3124 nsecs_t now = systemTime();
3125 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07003126 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003127 mNumDelayedWrites++;
3128 if ((now - lastWarning) > kWarningThrottleNs) {
3129 ATRACE_NAME("underrun");
3130 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
3131 ns2ms(delta), mNumDelayedWrites, this);
3132 lastWarning = now;
3133 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003134 }
Andy Hung08fb1742015-05-31 23:22:10 -07003135
3136 if (mThreadThrottle
3137 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3138 && ret > 0) { // we wrote something
3139 // Limit MixerThread data processing to no more than twice the
3140 // expected processing rate.
3141 //
3142 // This helps prevent underruns with NuPlayer and other applications
3143 // which may set up buffers that are close to the minimum size, or use
3144 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3145 //
3146 // The throttle smooths out sudden large data drains from the device,
3147 // e.g. when it comes out of standby, which often causes problems with
3148 // (1) mixer threads without a fast mixer (which has its own warm-up)
3149 // (2) minimum buffer sized tracks (even if the track is full,
3150 // the app won't fill fast enough to handle the sudden draw).
3151
3152 const int32_t deltaMs = delta / 1000000;
3153 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3154 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3155 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003156 // notify of throttle start on verbose log
3157 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3158 "mixer(%p) throttle begin:"
3159 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003160 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003161 mThreadThrottleTimeMs += throttleMs;
3162 } else {
3163 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3164 if (diff > 0) {
3165 // notify of throttle end on debug log
3166 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
3167 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3168 }
Andy Hung08fb1742015-05-31 23:22:10 -07003169 }
3170 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003171 }
Eric Laurent81784c32012-11-19 14:55:58 -08003172
Eric Laurentbfb1b832013-01-07 09:53:42 -08003173 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003174 ATRACE_BEGIN("sleep");
Eric Laurent51716182016-02-29 18:00:56 -08003175 if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
3176 Mutex::Autolock _l(mLock);
3177 if (!mSignalPending && !exitPending()) {
3178 // Do not sleep more than one buffer duration since last write and not
3179 // less than kDirectMinSleepTimeUs
3180 // Wake up if a command is received
3181 nsecs_t now = systemTime();
3182 uint32_t deltaUs = (uint32_t)((now - mLastWriteTime) / 1000);
3183 uint32_t timeoutUs = mSleepTimeUs;
3184 if (timeoutUs + deltaUs > mBufferDurationUs) {
3185 if (mBufferDurationUs > deltaUs) {
3186 timeoutUs = mBufferDurationUs - deltaUs;
3187 if (timeoutUs < kDirectMinSleepTimeUs) {
3188 timeoutUs = kDirectMinSleepTimeUs;
3189 }
3190 } else {
3191 timeoutUs = kDirectMinSleepTimeUs;
3192 }
3193 }
3194 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)timeoutUs));
3195 }
3196 } else {
3197 usleep(mSleepTimeUs);
3198 }
Glenn Kastene7754022014-10-31 12:11:26 -07003199 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003200 }
Eric Laurent81784c32012-11-19 14:55:58 -08003201 }
3202
3203 // Finally let go of removed track(s), without the lock held
3204 // since we can't guarantee the destructors won't acquire that
3205 // same lock. This will also mutate and push a new fast mixer state.
3206 threadLoop_removeTracks(tracksToRemove);
3207 tracksToRemove.clear();
3208
3209 // FIXME I don't understand the need for this here;
3210 // it was in the original code but maybe the
3211 // assignment in saveOutputTracks() makes this unnecessary?
3212 clearOutputTracks();
3213
3214 // Effect chains will be actually deleted here if they were removed from
3215 // mEffectChains list during mixing or effects processing
3216 effectChains.clear();
3217
3218 // FIXME Note that the above .clear() is no longer necessary since effectChains
3219 // is now local to this block, but will keep it for now (at least until merge done).
3220 }
3221
Eric Laurentbfb1b832013-01-07 09:53:42 -08003222 threadLoop_exit();
3223
Eric Laurentcf817a22014-08-04 20:36:31 -07003224 if (!mStandby) {
3225 threadLoop_standby();
3226 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003227 }
3228
3229 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003230 mWakeLockUids.clear();
3231 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003232
3233 ALOGV("Thread %p type %d exiting", this, mType);
3234 return false;
3235}
3236
Eric Laurentbfb1b832013-01-07 09:53:42 -08003237// removeTracks_l() must be called with ThreadBase::mLock held
3238void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3239{
3240 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003241 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003242 for (size_t i=0 ; i<count ; i++) {
3243 const sp<Track>& track = tracksToRemove.itemAt(i);
3244 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003245 mWakeLockUids.remove(track->uid());
3246 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003247 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3248 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3249 if (chain != 0) {
3250 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3251 track->sessionId());
3252 chain->decActiveTrackCnt();
3253 }
3254 if (track->isTerminated()) {
3255 removeTrack_l(track);
3256 }
3257 }
3258 }
3259
3260}
Eric Laurent81784c32012-11-19 14:55:58 -08003261
Eric Laurentaccc1472013-09-20 09:36:34 -07003262status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3263{
3264 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003265 ExtendedTimestamp ets;
3266 status_t status = mNormalSink->getTimestamp(ets);
3267 if (status == NO_ERROR) {
3268 status = ets.getBestTimestamp(&timestamp);
3269 }
3270 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003271 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003272 if ((mType == OFFLOAD || mType == DIRECT)
3273 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003274 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003275 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003276 if (ret == 0) {
3277 timestamp.mPosition = (uint32_t)position64;
3278 return NO_ERROR;
3279 }
3280 }
3281 return INVALID_OPERATION;
3282}
Eric Laurent1c333e22014-05-20 10:48:17 -07003283
Eric Laurent054d9d32015-04-24 08:48:48 -07003284status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3285 audio_patch_handle_t *handle)
3286{
3287 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3288 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3289 if (mFastMixer != 0) {
3290 FastMixerStateQueue *sq = mFastMixer->sq();
3291 FastMixerState *state = sq->begin();
3292 if (!(state->mCommand & FastMixerState::IDLE)) {
3293 previousCommand = state->mCommand;
3294 state->mCommand = FastMixerState::HOT_IDLE;
3295 sq->end();
3296 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3297 } else {
3298 sq->end(false /*didModify*/);
3299 }
3300 }
3301 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3302
3303 if (!(previousCommand & FastMixerState::IDLE)) {
3304 ALOG_ASSERT(mFastMixer != 0);
3305 FastMixerStateQueue *sq = mFastMixer->sq();
3306 FastMixerState *state = sq->begin();
3307 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3308 state->mCommand = previousCommand;
3309 sq->end();
3310 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3311 }
3312
3313 return status;
3314}
3315
Eric Laurent1c333e22014-05-20 10:48:17 -07003316status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3317 audio_patch_handle_t *handle)
3318{
3319 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003320
3321 // store new device and send to effects
3322 audio_devices_t type = AUDIO_DEVICE_NONE;
3323 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3324 type |= patch->sinks[i].ext.device.type;
3325 }
3326
3327#ifdef ADD_BATTERY_DATA
3328 // when changing the audio output device, call addBatteryData to notify
3329 // the change
3330 if (mOutDevice != type) {
3331 uint32_t params = 0;
3332 // check whether speaker is on
3333 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3334 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003335 }
3336
Eric Laurent054d9d32015-04-24 08:48:48 -07003337 audio_devices_t deviceWithoutSpeaker
3338 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3339 // check if any other device (except speaker) is on
3340 if (type & deviceWithoutSpeaker) {
3341 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3342 }
3343
3344 if (params != 0) {
3345 addBatteryData(params);
3346 }
3347 }
3348#endif
3349
3350 for (size_t i = 0; i < mEffectChains.size(); i++) {
3351 mEffectChains[i]->setDevice_l(type);
3352 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003353
3354 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3355 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3356 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003357 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003358 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003359
3360 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003361 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3362 status = hwDevice->create_audio_patch(hwDevice,
3363 patch->num_sources,
3364 patch->sources,
3365 patch->num_sinks,
3366 patch->sinks,
3367 handle);
3368 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003369 char *address;
3370 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3371 //FIXME: we only support address on first sink with HAL version < 3.0
3372 address = audio_device_address_to_parameter(
3373 patch->sinks[0].ext.device.type,
3374 patch->sinks[0].ext.device.address);
3375 } else {
3376 address = (char *)calloc(1, 1);
3377 }
3378 AudioParameter param = AudioParameter(String8(address));
3379 free(address);
3380 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3381 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3382 param.toString().string());
3383 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003384 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003385 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003386 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003387 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3388 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003389 return status;
3390}
3391
Eric Laurent054d9d32015-04-24 08:48:48 -07003392status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3393{
3394 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3395 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3396 if (mFastMixer != 0) {
3397 FastMixerStateQueue *sq = mFastMixer->sq();
3398 FastMixerState *state = sq->begin();
3399 if (!(state->mCommand & FastMixerState::IDLE)) {
3400 previousCommand = state->mCommand;
3401 state->mCommand = FastMixerState::HOT_IDLE;
3402 sq->end();
3403 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3404 } else {
3405 sq->end(false /*didModify*/);
3406 }
3407 }
3408
3409 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3410
3411 if (!(previousCommand & FastMixerState::IDLE)) {
3412 ALOG_ASSERT(mFastMixer != 0);
3413 FastMixerStateQueue *sq = mFastMixer->sq();
3414 FastMixerState *state = sq->begin();
3415 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3416 state->mCommand = previousCommand;
3417 sq->end();
3418 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3419 }
3420
3421 return status;
3422}
3423
Eric Laurent1c333e22014-05-20 10:48:17 -07003424status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3425{
3426 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003427
3428 mOutDevice = AUDIO_DEVICE_NONE;
3429
Eric Laurent1c333e22014-05-20 10:48:17 -07003430 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3431 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3432 status = hwDevice->release_audio_patch(hwDevice, handle);
3433 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003434 AudioParameter param;
3435 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3436 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3437 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003438 }
3439 return status;
3440}
3441
Eric Laurent83b88082014-06-20 18:31:16 -07003442void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3443{
3444 Mutex::Autolock _l(mLock);
3445 mTracks.add(track);
3446}
3447
3448void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3449{
3450 Mutex::Autolock _l(mLock);
3451 destroyTrack_l(track);
3452}
3453
3454void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3455{
3456 ThreadBase::getAudioPortConfig(config);
3457 config->role = AUDIO_PORT_ROLE_SOURCE;
3458 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3459 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3460}
3461
Eric Laurent81784c32012-11-19 14:55:58 -08003462// ----------------------------------------------------------------------------
3463
3464AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003465 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3466 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003467 // mAudioMixer below
3468 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003469 mFastMixerFutex(0),
3470 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003471 // mOutputSink below
3472 // mPipeSink below
3473 // mNormalSink below
3474{
3475 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003476 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003477 "mFrameCount=%d, mNormalFrameCount=%d",
3478 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3479 mNormalFrameCount);
3480 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3481
Andy Hungfbfc3952015-01-15 13:33:51 -08003482 if (type == DUPLICATING) {
3483 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3484 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3485 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3486 return;
3487 }
Eric Laurent81784c32012-11-19 14:55:58 -08003488 // create an NBAIO sink for the HAL output stream, and negotiate
3489 mOutputSink = new AudioStreamOutSink(output->stream);
3490 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003491 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003492 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3493 ALOG_ASSERT(index == 0);
3494
3495 // initialize fast mixer depending on configuration
3496 bool initFastMixer;
3497 switch (kUseFastMixer) {
3498 case FastMixer_Never:
3499 initFastMixer = false;
3500 break;
3501 case FastMixer_Always:
3502 initFastMixer = true;
3503 break;
3504 case FastMixer_Static:
3505 case FastMixer_Dynamic:
3506 initFastMixer = mFrameCount < mNormalFrameCount;
3507 break;
3508 }
3509 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003510 audio_format_t fastMixerFormat;
3511 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3512 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3513 } else {
3514 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3515 }
3516 if (mFormat != fastMixerFormat) {
3517 // change our Sink format to accept our intermediate precision
3518 mFormat = fastMixerFormat;
3519 free(mSinkBuffer);
3520 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3521 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3522 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3523 }
Eric Laurent81784c32012-11-19 14:55:58 -08003524
3525 // create a MonoPipe to connect our submix to FastMixer
3526 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003527 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003528 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003529 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003530 format.mFormat = fastMixerFormat;
3531 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3532
Eric Laurent81784c32012-11-19 14:55:58 -08003533 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3534 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3535 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3536 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3537 const NBAIO_Format offers[1] = {format};
3538 size_t numCounterOffers = 0;
3539 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3540 ALOG_ASSERT(index == 0);
3541 monoPipe->setAvgFrames((mScreenState & 1) ?
3542 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3543 mPipeSink = monoPipe;
3544
Glenn Kasten46909e72013-02-26 09:20:22 -08003545#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003546 if (mTeeSinkOutputEnabled) {
3547 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003548 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3549 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003550 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003551 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003552 ALOG_ASSERT(index == 0);
3553 mTeeSink = teeSink;
3554 PipeReader *teeSource = new PipeReader(*teeSink);
3555 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003556 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003557 ALOG_ASSERT(index == 0);
3558 mTeeSource = teeSource;
3559 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003560#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003561
3562 // create fast mixer and configure it initially with just one fast track for our submix
3563 mFastMixer = new FastMixer();
3564 FastMixerStateQueue *sq = mFastMixer->sq();
3565#ifdef STATE_QUEUE_DUMP
3566 sq->setObserverDump(&mStateQueueObserverDump);
3567 sq->setMutatorDump(&mStateQueueMutatorDump);
3568#endif
3569 FastMixerState *state = sq->begin();
3570 FastTrack *fastTrack = &state->mFastTracks[0];
3571 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3572 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3573 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003574 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3575 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003576 fastTrack->mGeneration++;
3577 state->mFastTracksGen++;
3578 state->mTrackMask = 1;
3579 // fast mixer will use the HAL output sink
3580 state->mOutputSink = mOutputSink.get();
3581 state->mOutputSinkGen++;
3582 state->mFrameCount = mFrameCount;
3583 state->mCommand = FastMixerState::COLD_IDLE;
3584 // already done in constructor initialization list
3585 //mFastMixerFutex = 0;
3586 state->mColdFutexAddr = &mFastMixerFutex;
3587 state->mColdGen++;
3588 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003589#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003590 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003591#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003592 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3593 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003594 sq->end();
3595 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3596
3597 // start the fast mixer
3598 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3599 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003600 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003601
3602#ifdef AUDIO_WATCHDOG
3603 // create and start the watchdog
3604 mAudioWatchdog = new AudioWatchdog();
3605 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3606 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3607 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003608 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003609#endif
3610
Eric Laurent81784c32012-11-19 14:55:58 -08003611 }
3612
3613 switch (kUseFastMixer) {
3614 case FastMixer_Never:
3615 case FastMixer_Dynamic:
3616 mNormalSink = mOutputSink;
3617 break;
3618 case FastMixer_Always:
3619 mNormalSink = mPipeSink;
3620 break;
3621 case FastMixer_Static:
3622 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3623 break;
3624 }
3625}
3626
3627AudioFlinger::MixerThread::~MixerThread()
3628{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003629 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003630 FastMixerStateQueue *sq = mFastMixer->sq();
3631 FastMixerState *state = sq->begin();
3632 if (state->mCommand == FastMixerState::COLD_IDLE) {
3633 int32_t old = android_atomic_inc(&mFastMixerFutex);
3634 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003635 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003636 }
3637 }
3638 state->mCommand = FastMixerState::EXIT;
3639 sq->end();
3640 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3641 mFastMixer->join();
3642 // Though the fast mixer thread has exited, it's state queue is still valid.
3643 // We'll use that extract the final state which contains one remaining fast track
3644 // corresponding to our sub-mix.
3645 state = sq->begin();
3646 ALOG_ASSERT(state->mTrackMask == 1);
3647 FastTrack *fastTrack = &state->mFastTracks[0];
3648 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3649 delete fastTrack->mBufferProvider;
3650 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003651 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003652#ifdef AUDIO_WATCHDOG
3653 if (mAudioWatchdog != 0) {
3654 mAudioWatchdog->requestExit();
3655 mAudioWatchdog->requestExitAndWait();
3656 mAudioWatchdog.clear();
3657 }
3658#endif
3659 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003660 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003661 delete mAudioMixer;
3662}
3663
3664
3665uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3666{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003667 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003668 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3669 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3670 }
3671 return latency;
3672}
3673
3674
3675void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3676{
3677 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3678}
3679
Eric Laurentbfb1b832013-01-07 09:53:42 -08003680ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003681{
3682 // FIXME we should only do one push per cycle; confirm this is true
3683 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003684 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003685 FastMixerStateQueue *sq = mFastMixer->sq();
3686 FastMixerState *state = sq->begin();
3687 if (state->mCommand != FastMixerState::MIX_WRITE &&
3688 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3689 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003690
3691 // FIXME workaround for first HAL write being CPU bound on some devices
3692 ATRACE_BEGIN("write");
3693 mOutput->write((char *)mSinkBuffer, 0);
3694 ATRACE_END();
3695
Eric Laurent81784c32012-11-19 14:55:58 -08003696 int32_t old = android_atomic_inc(&mFastMixerFutex);
3697 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003698 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003699 }
3700#ifdef AUDIO_WATCHDOG
3701 if (mAudioWatchdog != 0) {
3702 mAudioWatchdog->resume();
3703 }
3704#endif
3705 }
3706 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003707#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003708 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003709 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003710#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003711 sq->end();
3712 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3713 if (kUseFastMixer == FastMixer_Dynamic) {
3714 mNormalSink = mPipeSink;
3715 }
3716 } else {
3717 sq->end(false /*didModify*/);
3718 }
3719 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003720 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003721}
3722
3723void AudioFlinger::MixerThread::threadLoop_standby()
3724{
3725 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003726 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003727 FastMixerStateQueue *sq = mFastMixer->sq();
3728 FastMixerState *state = sq->begin();
3729 if (!(state->mCommand & FastMixerState::IDLE)) {
3730 state->mCommand = FastMixerState::COLD_IDLE;
3731 state->mColdFutexAddr = &mFastMixerFutex;
3732 state->mColdGen++;
3733 mFastMixerFutex = 0;
3734 sq->end();
3735 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3736 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3737 if (kUseFastMixer == FastMixer_Dynamic) {
3738 mNormalSink = mOutputSink;
3739 }
3740#ifdef AUDIO_WATCHDOG
3741 if (mAudioWatchdog != 0) {
3742 mAudioWatchdog->pause();
3743 }
3744#endif
3745 } else {
3746 sq->end(false /*didModify*/);
3747 }
3748 }
3749 PlaybackThread::threadLoop_standby();
3750}
3751
Eric Laurentbfb1b832013-01-07 09:53:42 -08003752bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3753{
3754 return false;
3755}
3756
3757bool AudioFlinger::PlaybackThread::shouldStandby_l()
3758{
3759 return !mStandby;
3760}
3761
3762bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3763{
3764 Mutex::Autolock _l(mLock);
3765 return waitingAsyncCallback_l();
3766}
3767
Eric Laurent81784c32012-11-19 14:55:58 -08003768// shared by MIXER and DIRECT, overridden by DUPLICATING
3769void AudioFlinger::PlaybackThread::threadLoop_standby()
3770{
3771 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003772 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003773 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003774 // discard any pending drain or write ack by incrementing sequence
3775 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3776 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003777 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003778 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3779 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003780 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003781 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003782}
3783
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003784void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3785{
3786 ALOGV("signal playback thread");
3787 broadcast_l();
3788}
3789
Eric Laurent81784c32012-11-19 14:55:58 -08003790void AudioFlinger::MixerThread::threadLoop_mix()
3791{
Eric Laurent81784c32012-11-19 14:55:58 -08003792 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003793 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003794 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003795 // increase sleep time progressively when application underrun condition clears.
3796 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3797 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3798 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003799 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003800 sleepTimeShift--;
3801 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003802 mSleepTimeUs = 0;
3803 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003804 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003805
Eric Laurent81784c32012-11-19 14:55:58 -08003806}
3807
3808void AudioFlinger::MixerThread::threadLoop_sleepTime()
3809{
3810 // If no tracks are ready, sleep once for the duration of an output
3811 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003812 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003813 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003814 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3815 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3816 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003817 }
3818 // reduce sleep time in case of consecutive application underruns to avoid
3819 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3820 // duration we would end up writing less data than needed by the audio HAL if
3821 // the condition persists.
3822 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3823 sleepTimeShift++;
3824 }
3825 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003826 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003827 }
3828 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003829 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3830 // before effects processing or output.
3831 if (mMixerBufferValid) {
3832 memset(mMixerBuffer, 0, mMixerBufferSize);
3833 } else {
3834 memset(mSinkBuffer, 0, mSinkBufferSize);
3835 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003836 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003837 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3838 "anticipated start");
3839 }
3840 // TODO add standby time extension fct of effect tail
3841}
3842
3843// prepareTracks_l() must be called with ThreadBase::mLock held
3844AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3845 Vector< sp<Track> > *tracksToRemove)
3846{
3847
3848 mixer_state mixerStatus = MIXER_IDLE;
3849 // find out which tracks need to be processed
3850 size_t count = mActiveTracks.size();
3851 size_t mixedTracks = 0;
3852 size_t tracksWithEffect = 0;
3853 // counts only _active_ fast tracks
3854 size_t fastTracks = 0;
3855 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3856
3857 float masterVolume = mMasterVolume;
3858 bool masterMute = mMasterMute;
3859
3860 if (masterMute) {
3861 masterVolume = 0;
3862 }
3863 // Delegate master volume control to effect in output mix effect chain if needed
3864 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3865 if (chain != 0) {
3866 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3867 chain->setVolume_l(&v, &v);
3868 masterVolume = (float)((v + (1 << 23)) >> 24);
3869 chain.clear();
3870 }
3871
3872 // prepare a new state to push
3873 FastMixerStateQueue *sq = NULL;
3874 FastMixerState *state = NULL;
3875 bool didModify = false;
3876 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003877 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003878 sq = mFastMixer->sq();
3879 state = sq->begin();
3880 }
3881
Andy Hung69aed5f2014-02-25 17:24:40 -08003882 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003883 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003884
Eric Laurent81784c32012-11-19 14:55:58 -08003885 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003886 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003887 if (t == 0) {
3888 continue;
3889 }
3890
3891 // this const just means the local variable doesn't change
3892 Track* const track = t.get();
3893
3894 // process fast tracks
3895 if (track->isFastTrack()) {
3896
3897 // It's theoretically possible (though unlikely) for a fast track to be created
3898 // and then removed within the same normal mix cycle. This is not a problem, as
3899 // the track never becomes active so it's fast mixer slot is never touched.
3900 // The converse, of removing an (active) track and then creating a new track
3901 // at the identical fast mixer slot within the same normal mix cycle,
3902 // is impossible because the slot isn't marked available until the end of each cycle.
3903 int j = track->mFastIndex;
3904 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3905 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3906 FastTrack *fastTrack = &state->mFastTracks[j];
3907
3908 // Determine whether the track is currently in underrun condition,
3909 // and whether it had a recent underrun.
3910 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3911 FastTrackUnderruns underruns = ftDump->mUnderruns;
3912 uint32_t recentFull = (underruns.mBitFields.mFull -
3913 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3914 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3915 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3916 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3917 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3918 uint32_t recentUnderruns = recentPartial + recentEmpty;
3919 track->mObservedUnderruns = underruns;
3920 // don't count underruns that occur while stopping or pausing
3921 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003922 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3923 recentUnderruns > 0) {
3924 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3925 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003926 } else {
3927 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003928 }
3929
3930 // This is similar to the state machine for normal tracks,
3931 // with a few modifications for fast tracks.
3932 bool isActive = true;
3933 switch (track->mState) {
3934 case TrackBase::STOPPING_1:
3935 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003936 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003937 track->mState = TrackBase::STOPPING_2;
3938 }
3939 break;
3940 case TrackBase::PAUSING:
3941 // ramp down is not yet implemented
3942 track->setPaused();
3943 break;
3944 case TrackBase::RESUMING:
3945 // ramp up is not yet implemented
3946 track->mState = TrackBase::ACTIVE;
3947 break;
3948 case TrackBase::ACTIVE:
3949 if (recentFull > 0 || recentPartial > 0) {
3950 // track has provided at least some frames recently: reset retry count
3951 track->mRetryCount = kMaxTrackRetries;
3952 }
3953 if (recentUnderruns == 0) {
3954 // no recent underruns: stay active
3955 break;
3956 }
3957 // there has recently been an underrun of some kind
3958 if (track->sharedBuffer() == 0) {
3959 // were any of the recent underruns "empty" (no frames available)?
3960 if (recentEmpty == 0) {
3961 // no, then ignore the partial underruns as they are allowed indefinitely
3962 break;
3963 }
3964 // there has recently been an "empty" underrun: decrement the retry counter
3965 if (--(track->mRetryCount) > 0) {
3966 break;
3967 }
3968 // indicate to client process that the track was disabled because of underrun;
3969 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08003970 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08003971 // remove from active list, but state remains ACTIVE [confusing but true]
3972 isActive = false;
3973 break;
3974 }
3975 // fall through
3976 case TrackBase::STOPPING_2:
3977 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003978 case TrackBase::STOPPED:
3979 case TrackBase::FLUSHED: // flush() while active
3980 // Check for presentation complete if track is inactive
3981 // We have consumed all the buffers of this track.
3982 // This would be incomplete if we auto-paused on underrun
3983 {
3984 size_t audioHALFrames =
3985 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003986 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003987 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3988 // track stays in active list until presentation is complete
3989 break;
3990 }
3991 }
3992 if (track->isStopping_2()) {
3993 track->mState = TrackBase::STOPPED;
3994 }
3995 if (track->isStopped()) {
3996 // Can't reset directly, as fast mixer is still polling this track
3997 // track->reset();
3998 // So instead mark this track as needing to be reset after push with ack
3999 resetMask |= 1 << i;
4000 }
4001 isActive = false;
4002 break;
4003 case TrackBase::IDLE:
4004 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004005 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004006 }
4007
4008 if (isActive) {
4009 // was it previously inactive?
4010 if (!(state->mTrackMask & (1 << j))) {
4011 ExtendedAudioBufferProvider *eabp = track;
4012 VolumeProvider *vp = track;
4013 fastTrack->mBufferProvider = eabp;
4014 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004015 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004016 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004017 fastTrack->mGeneration++;
4018 state->mTrackMask |= 1 << j;
4019 didModify = true;
4020 // no acknowledgement required for newly active tracks
4021 }
4022 // cache the combined master volume and stream type volume for fast mixer; this
4023 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004024 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004025 ++fastTracks;
4026 } else {
4027 // was it previously active?
4028 if (state->mTrackMask & (1 << j)) {
4029 fastTrack->mBufferProvider = NULL;
4030 fastTrack->mGeneration++;
4031 state->mTrackMask &= ~(1 << j);
4032 didModify = true;
4033 // If any fast tracks were removed, we must wait for acknowledgement
4034 // because we're about to decrement the last sp<> on those tracks.
4035 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4036 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004037 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4038 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4039 j, track->mState, state->mTrackMask, recentUnderruns,
4040 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004041 }
4042 tracksToRemove->add(track);
4043 // Avoids a misleading display in dumpsys
4044 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4045 }
4046 continue;
4047 }
4048
4049 { // local variable scope to avoid goto warning
4050
4051 audio_track_cblk_t* cblk = track->cblk();
4052
4053 // The first time a track is added we wait
4054 // for all its buffers to be filled before processing it
4055 int name = track->name();
4056 // make sure that we have enough frames to mix one full buffer.
4057 // enforce this condition only once to enable draining the buffer in case the client
4058 // app does not call stop() and relies on underrun to stop:
4059 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4060 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004061 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004062 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004063 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004064
4065 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004066 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004067 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4068 // add frames already consumed but not yet released by the resampler
4069 // because mAudioTrackServerProxy->framesReady() will include these frames
4070 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4071
Eric Laurent81784c32012-11-19 14:55:58 -08004072 uint32_t minFrames = 1;
4073 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4074 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004075 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004076 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004077
4078 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004079 if (ATRACE_ENABLED()) {
4080 // I wish we had formatted trace names
4081 char traceName[16];
4082 strcpy(traceName, "nRdy");
4083 int name = track->name();
4084 if (AudioMixer::TRACK0 <= name &&
4085 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4086 name -= AudioMixer::TRACK0;
4087 traceName[4] = (name / 10) + '0';
4088 traceName[5] = (name % 10) + '0';
4089 } else {
4090 traceName[4] = '?';
4091 traceName[5] = '?';
4092 }
4093 traceName[6] = '\0';
4094 ATRACE_INT(traceName, framesReady);
4095 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004096 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004097 !track->isPaused() && !track->isTerminated())
4098 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004099 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004100
4101 mixedTracks++;
4102
Andy Hung69aed5f2014-02-25 17:24:40 -08004103 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4104 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004105 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004106 if (track->mainBuffer() != mSinkBuffer &&
4107 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004108 if (mEffectBufferEnabled) {
4109 mEffectBufferValid = true; // Later can set directly.
4110 }
Eric Laurent81784c32012-11-19 14:55:58 -08004111 chain = getEffectChain_l(track->sessionId());
4112 // Delegate volume control to effect in track effect chain if needed
4113 if (chain != 0) {
4114 tracksWithEffect++;
4115 } else {
4116 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4117 "session %d",
4118 name, track->sessionId());
4119 }
4120 }
4121
4122
4123 int param = AudioMixer::VOLUME;
4124 if (track->mFillingUpStatus == Track::FS_FILLED) {
4125 // no ramp for the first volume setting
4126 track->mFillingUpStatus = Track::FS_ACTIVE;
4127 if (track->mState == TrackBase::RESUMING) {
4128 track->mState = TrackBase::ACTIVE;
4129 param = AudioMixer::RAMP_VOLUME;
4130 }
4131 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004132 // FIXME should not make a decision based on mServer
4133 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004134 // If the track is stopped before the first frame was mixed,
4135 // do not apply ramp
4136 param = AudioMixer::RAMP_VOLUME;
4137 }
4138
4139 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004140 uint32_t vl, vr; // in U8.24 integer format
4141 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004142 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004143 vl = vr = 0;
4144 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004145 if (track->isPausing()) {
4146 track->setPaused();
4147 }
4148 } else {
4149
4150 // read original volumes with volume control
4151 float typeVolume = mStreamTypes[track->streamType()].volume;
4152 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004153 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004154 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004155 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4156 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004157 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004158 if (vlf > GAIN_FLOAT_UNITY) {
4159 ALOGV("Track left volume out of range: %.3g", vlf);
4160 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004161 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004162 if (vrf > GAIN_FLOAT_UNITY) {
4163 ALOGV("Track right volume out of range: %.3g", vrf);
4164 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004165 }
4166 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004167 vlf *= v;
4168 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004169 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004170 // then derive vl and vr as U8.24 versions for the effect chain
4171 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4172 vl = (uint32_t) (scaleto8_24 * vlf);
4173 vr = (uint32_t) (scaleto8_24 * vrf);
4174 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004175 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004176 // send level comes from shared memory and so may be corrupt
4177 if (sendLevel > MAX_GAIN_INT) {
4178 ALOGV("Track send level out of range: %04X", sendLevel);
4179 sendLevel = MAX_GAIN_INT;
4180 }
Andy Hung6be49402014-05-30 10:42:03 -07004181 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4182 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004183 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004184
Eric Laurent81784c32012-11-19 14:55:58 -08004185 // Delegate volume control to effect in track effect chain if needed
4186 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4187 // Do not ramp volume if volume is controlled by effect
4188 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004189 // Update remaining floating point volume levels
4190 vlf = (float)vl / (1 << 24);
4191 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004192 track->mHasVolumeController = true;
4193 } else {
4194 // force no volume ramp when volume controller was just disabled or removed
4195 // from effect chain to avoid volume spike
4196 if (track->mHasVolumeController) {
4197 param = AudioMixer::VOLUME;
4198 }
4199 track->mHasVolumeController = false;
4200 }
4201
Eric Laurent81784c32012-11-19 14:55:58 -08004202 // XXX: these things DON'T need to be done each time
4203 mAudioMixer->setBufferProvider(name, track);
4204 mAudioMixer->enable(name);
4205
Andy Hung6be49402014-05-30 10:42:03 -07004206 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4207 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4208 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004209 mAudioMixer->setParameter(
4210 name,
4211 AudioMixer::TRACK,
4212 AudioMixer::FORMAT, (void *)track->format());
4213 mAudioMixer->setParameter(
4214 name,
4215 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004216 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004217 mAudioMixer->setParameter(
4218 name,
4219 AudioMixer::TRACK,
4220 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004221 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004222 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004223 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004224 if (reqSampleRate == 0) {
4225 reqSampleRate = mSampleRate;
4226 } else if (reqSampleRate > maxSampleRate) {
4227 reqSampleRate = maxSampleRate;
4228 }
Eric Laurent81784c32012-11-19 14:55:58 -08004229 mAudioMixer->setParameter(
4230 name,
4231 AudioMixer::RESAMPLE,
4232 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004233 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004234
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004235 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004236 mAudioMixer->setParameter(
4237 name,
4238 AudioMixer::TIMESTRETCH,
4239 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004240 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004241
Andy Hung69aed5f2014-02-25 17:24:40 -08004242 /*
4243 * Select the appropriate output buffer for the track.
4244 *
Andy Hung98ef9782014-03-04 14:46:50 -08004245 * Tracks with effects go into their own effects chain buffer
4246 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004247 *
4248 * Other tracks can use mMixerBuffer for higher precision
4249 * channel accumulation. If this buffer is enabled
4250 * (mMixerBufferEnabled true), then selected tracks will accumulate
4251 * into it.
4252 *
4253 */
4254 if (mMixerBufferEnabled
4255 && (track->mainBuffer() == mSinkBuffer
4256 || track->mainBuffer() == mMixerBuffer)) {
4257 mAudioMixer->setParameter(
4258 name,
4259 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004260 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004261 mAudioMixer->setParameter(
4262 name,
4263 AudioMixer::TRACK,
4264 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4265 // TODO: override track->mainBuffer()?
4266 mMixerBufferValid = true;
4267 } else {
4268 mAudioMixer->setParameter(
4269 name,
4270 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004271 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004272 mAudioMixer->setParameter(
4273 name,
4274 AudioMixer::TRACK,
4275 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4276 }
Eric Laurent81784c32012-11-19 14:55:58 -08004277 mAudioMixer->setParameter(
4278 name,
4279 AudioMixer::TRACK,
4280 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4281
4282 // reset retry count
4283 track->mRetryCount = kMaxTrackRetries;
4284
4285 // If one track is ready, set the mixer ready if:
4286 // - the mixer was not ready during previous round OR
4287 // - no other track is not ready
4288 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4289 mixerStatus != MIXER_TRACKS_ENABLED) {
4290 mixerStatus = MIXER_TRACKS_READY;
4291 }
4292 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004293 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004294 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4295 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004296 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004297 } else {
4298 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004299 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004300
Eric Laurent81784c32012-11-19 14:55:58 -08004301 // clear effect chain input buffer if an active track underruns to avoid sending
4302 // previous audio buffer again to effects
4303 chain = getEffectChain_l(track->sessionId());
4304 if (chain != 0) {
4305 chain->clearInputBuffer();
4306 }
4307
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004308 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004309 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4310 track->isStopped() || track->isPaused()) {
4311 // We have consumed all the buffers of this track.
4312 // Remove it from the list of active tracks.
4313 // TODO: use actual buffer filling status instead of latency when available from
4314 // audio HAL
4315 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004316 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004317 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4318 if (track->isStopped()) {
4319 track->reset();
4320 }
4321 tracksToRemove->add(track);
4322 }
4323 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004324 // No buffers for this track. Give it a few chances to
4325 // fill a buffer, then remove it from active list.
4326 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004327 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004328 tracksToRemove->add(track);
4329 // indicate to client process that the track was disabled because of underrun;
4330 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004331 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004332 // If one track is not ready, mark the mixer also not ready if:
4333 // - the mixer was ready during previous round OR
4334 // - no other track is ready
4335 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4336 mixerStatus != MIXER_TRACKS_READY) {
4337 mixerStatus = MIXER_TRACKS_ENABLED;
4338 }
4339 }
4340 mAudioMixer->disable(name);
4341 }
4342
4343 } // local variable scope to avoid goto warning
4344track_is_ready: ;
4345
4346 }
4347
4348 // Push the new FastMixer state if necessary
4349 bool pauseAudioWatchdog = false;
4350 if (didModify) {
4351 state->mFastTracksGen++;
4352 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4353 if (kUseFastMixer == FastMixer_Dynamic &&
4354 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4355 state->mCommand = FastMixerState::COLD_IDLE;
4356 state->mColdFutexAddr = &mFastMixerFutex;
4357 state->mColdGen++;
4358 mFastMixerFutex = 0;
4359 if (kUseFastMixer == FastMixer_Dynamic) {
4360 mNormalSink = mOutputSink;
4361 }
4362 // If we go into cold idle, need to wait for acknowledgement
4363 // so that fast mixer stops doing I/O.
4364 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4365 pauseAudioWatchdog = true;
4366 }
Eric Laurent81784c32012-11-19 14:55:58 -08004367 }
4368 if (sq != NULL) {
4369 sq->end(didModify);
4370 sq->push(block);
4371 }
4372#ifdef AUDIO_WATCHDOG
4373 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4374 mAudioWatchdog->pause();
4375 }
4376#endif
4377
4378 // Now perform the deferred reset on fast tracks that have stopped
4379 while (resetMask != 0) {
4380 size_t i = __builtin_ctz(resetMask);
4381 ALOG_ASSERT(i < count);
4382 resetMask &= ~(1 << i);
4383 sp<Track> t = mActiveTracks[i].promote();
4384 if (t == 0) {
4385 continue;
4386 }
4387 Track* track = t.get();
4388 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4389 track->reset();
4390 }
4391
4392 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004393 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004394
Eric Laurent97d547d2014-09-02 14:45:53 -07004395 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4396 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004397 }
4398
4399 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004400 // as long as there are effects we should clear the effects buffer, to avoid
4401 // passing a non-clean buffer to the effect chain
4402 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004403 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004404 // sink or mix buffer must be cleared if all tracks are connected to an
4405 // effect chain as in this case the mixer will not write to the sink or mix buffer
4406 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004407 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4408 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004409 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004410 if (mMixerBufferValid) {
4411 memset(mMixerBuffer, 0, mMixerBufferSize);
4412 // TODO: In testing, mSinkBuffer below need not be cleared because
4413 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4414 // after mixing.
4415 //
4416 // To enforce this guarantee:
4417 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4418 // (mixedTracks == 0 && fastTracks > 0))
4419 // must imply MIXER_TRACKS_READY.
4420 // Later, we may clear buffers regardless, and skip much of this logic.
4421 }
Andy Hung98ef9782014-03-04 14:46:50 -08004422 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004423 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004424 }
4425
4426 // if any fast tracks, then status is ready
4427 mMixerStatusIgnoringFastTracks = mixerStatus;
4428 if (fastTracks > 0) {
4429 mixerStatus = MIXER_TRACKS_READY;
4430 }
4431 return mixerStatus;
4432}
4433
4434// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004435int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Glenn Kastend848eb42016-03-08 13:42:11 -08004436 audio_format_t format, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004437{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004438 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004439}
4440
4441// deleteTrackName_l() must be called with ThreadBase::mLock held
4442void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4443{
4444 ALOGV("remove track (%d) and delete from mixer", name);
4445 mAudioMixer->deleteTrackName(name);
4446}
4447
Eric Laurent10351942014-05-08 18:49:52 -07004448// checkForNewParameter_l() must be called with ThreadBase::mLock held
4449bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4450 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004451{
Eric Laurent81784c32012-11-19 14:55:58 -08004452 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004453 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004454
Eric Laurent10351942014-05-08 18:49:52 -07004455 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004456
Eric Laurent10351942014-05-08 18:49:52 -07004457 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4458 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004459 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004460 FastMixerStateQueue *sq = mFastMixer->sq();
4461 FastMixerState *state = sq->begin();
4462 if (!(state->mCommand & FastMixerState::IDLE)) {
4463 previousCommand = state->mCommand;
4464 state->mCommand = FastMixerState::HOT_IDLE;
4465 sq->end();
4466 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4467 } else {
4468 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004469 }
Eric Laurent10351942014-05-08 18:49:52 -07004470 }
Eric Laurent81784c32012-11-19 14:55:58 -08004471
Eric Laurent10351942014-05-08 18:49:52 -07004472 AudioParameter param = AudioParameter(keyValuePair);
4473 int value;
4474 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4475 reconfig = true;
4476 }
4477 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004478 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004479 status = BAD_VALUE;
4480 } else {
4481 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004482 reconfig = true;
4483 }
Eric Laurent10351942014-05-08 18:49:52 -07004484 }
4485 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004486 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004487 status = BAD_VALUE;
4488 } else {
4489 // no need to save value, since it's constant
4490 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004491 }
Eric Laurent10351942014-05-08 18:49:52 -07004492 }
4493 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4494 // do not accept frame count changes if tracks are open as the track buffer
4495 // size depends on frame count and correct behavior would not be guaranteed
4496 // if frame count is changed after track creation
4497 if (!mTracks.isEmpty()) {
4498 status = INVALID_OPERATION;
4499 } else {
4500 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004501 }
Eric Laurent10351942014-05-08 18:49:52 -07004502 }
4503 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004504#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004505 // when changing the audio output device, call addBatteryData to notify
4506 // the change
4507 if (mOutDevice != value) {
4508 uint32_t params = 0;
4509 // check whether speaker is on
4510 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4511 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004512 }
Eric Laurent10351942014-05-08 18:49:52 -07004513
4514 audio_devices_t deviceWithoutSpeaker
4515 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4516 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004517 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004518 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4519 }
4520
4521 if (params != 0) {
4522 addBatteryData(params);
4523 }
4524 }
Eric Laurent81784c32012-11-19 14:55:58 -08004525#endif
4526
Eric Laurent10351942014-05-08 18:49:52 -07004527 // forward device change to effects that have requested to be
4528 // aware of attached audio device.
4529 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004530 a2dpDeviceChanged =
4531 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004532 mOutDevice = value;
4533 for (size_t i = 0; i < mEffectChains.size(); i++) {
4534 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004535 }
4536 }
Eric Laurent10351942014-05-08 18:49:52 -07004537 }
Eric Laurent81784c32012-11-19 14:55:58 -08004538
Eric Laurent10351942014-05-08 18:49:52 -07004539 if (status == NO_ERROR) {
4540 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4541 keyValuePair.string());
4542 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004543 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004544 mStandby = true;
4545 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004546 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004547 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004548 }
Eric Laurent10351942014-05-08 18:49:52 -07004549 if (status == NO_ERROR && reconfig) {
4550 readOutputParameters_l();
4551 delete mAudioMixer;
4552 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4553 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004554 int name = getTrackName_l(mTracks[i]->mChannelMask,
4555 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004556 if (name < 0) {
4557 break;
4558 }
4559 mTracks[i]->mName = name;
4560 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004561 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004562 }
Eric Laurent81784c32012-11-19 14:55:58 -08004563 }
4564
4565 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004566 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004567 FastMixerStateQueue *sq = mFastMixer->sq();
4568 FastMixerState *state = sq->begin();
4569 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4570 state->mCommand = previousCommand;
4571 sq->end();
4572 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4573 }
4574
Eric Laurent42537be2016-01-08 17:16:42 -08004575 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004576}
4577
4578
4579void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4580{
4581 const size_t SIZE = 256;
4582 char buffer[SIZE];
4583 String8 result;
4584
4585 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004586 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004587 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004588 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004589
4590 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004591 // while we are dumping it. It may be inconsistent, but it won't mutate!
4592 // This is a large object so we place it on the heap.
4593 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4594 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4595 copy->dump(fd);
4596 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004597
4598#ifdef STATE_QUEUE_DUMP
4599 // Similar for state queue
4600 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4601 observerCopy.dump(fd);
4602 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4603 mutatorCopy.dump(fd);
4604#endif
4605
Glenn Kasten46909e72013-02-26 09:20:22 -08004606#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004607 // Write the tee output to a .wav file
4608 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004609#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004610
4611#ifdef AUDIO_WATCHDOG
4612 if (mAudioWatchdog != 0) {
4613 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4614 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4615 wdCopy.dump(fd);
4616 }
4617#endif
4618}
4619
4620uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4621{
4622 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4623}
4624
4625uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4626{
4627 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4628}
4629
4630void AudioFlinger::MixerThread::cacheParameters_l()
4631{
4632 PlaybackThread::cacheParameters_l();
4633
4634 // FIXME: Relaxed timing because of a certain device that can't meet latency
4635 // Should be reduced to 2x after the vendor fixes the driver issue
4636 // increase threshold again due to low power audio mode. The way this warning
4637 // threshold is calculated and its usefulness should be reconsidered anyway.
4638 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4639}
4640
4641// ----------------------------------------------------------------------------
4642
4643AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent51716182016-02-29 18:00:56 -08004644 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady,
4645 uint32_t bitRate)
4646 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady, bitRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004647 // mLeftVolFloat, mRightVolFloat
4648{
4649}
4650
Eric Laurentbfb1b832013-01-07 09:53:42 -08004651AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4652 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent51716182016-02-29 18:00:56 -08004653 ThreadBase::type_t type, bool systemReady, uint32_t bitRate)
4654 : PlaybackThread(audioFlinger, output, id, device, type, systemReady, bitRate)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004655 // mLeftVolFloat, mRightVolFloat
4656{
4657}
4658
Eric Laurent81784c32012-11-19 14:55:58 -08004659AudioFlinger::DirectOutputThread::~DirectOutputThread()
4660{
4661}
4662
Eric Laurentbfb1b832013-01-07 09:53:42 -08004663void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4664{
4665 audio_track_cblk_t* cblk = track->cblk();
4666 float left, right;
4667
4668 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4669 left = right = 0;
4670 } else {
4671 float typeVolume = mStreamTypes[track->streamType()].volume;
4672 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004673 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004674 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4675 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4676 if (left > GAIN_FLOAT_UNITY) {
4677 left = GAIN_FLOAT_UNITY;
4678 }
4679 left *= v;
4680 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4681 if (right > GAIN_FLOAT_UNITY) {
4682 right = GAIN_FLOAT_UNITY;
4683 }
4684 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004685 }
4686
4687 if (lastTrack) {
4688 if (left != mLeftVolFloat || right != mRightVolFloat) {
4689 mLeftVolFloat = left;
4690 mRightVolFloat = right;
4691
4692 // Convert volumes from float to 8.24
4693 uint32_t vl = (uint32_t)(left * (1 << 24));
4694 uint32_t vr = (uint32_t)(right * (1 << 24));
4695
4696 // Delegate volume control to effect in track effect chain if needed
4697 // only one effect chain can be present on DirectOutputThread, so if
4698 // there is one, the track is connected to it
4699 if (!mEffectChains.isEmpty()) {
4700 mEffectChains[0]->setVolume_l(&vl, &vr);
4701 left = (float)vl / (1 << 24);
4702 right = (float)vr / (1 << 24);
4703 }
4704 if (mOutput->stream->set_volume) {
4705 mOutput->stream->set_volume(mOutput->stream, left, right);
4706 }
4707 }
4708 }
4709}
4710
Phil Burk43b4dcc2015-06-09 16:53:44 -07004711void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4712{
4713 sp<Track> previousTrack = mPreviousTrack.promote();
4714 sp<Track> latestTrack = mLatestActiveTrack.promote();
4715
Eric Laurent0f0631e2015-07-06 18:01:25 -07004716 if (previousTrack != 0 && latestTrack != 0) {
4717 if (mType == DIRECT) {
4718 if (previousTrack.get() != latestTrack.get()) {
4719 mFlushPending = true;
4720 }
4721 } else /* mType == OFFLOAD */ {
4722 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4723 mFlushPending = true;
4724 }
4725 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004726 }
4727 PlaybackThread::onAddNewTrack_l();
4728}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004729
Eric Laurent81784c32012-11-19 14:55:58 -08004730AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4731 Vector< sp<Track> > *tracksToRemove
4732)
4733{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004734 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004735 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004736 bool doHwPause = false;
4737 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004738
4739 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004740 for (size_t i = 0; i < count; i++) {
4741 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004742 // The track died recently
4743 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004744 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004745 }
4746
Phil Burk43b4dcc2015-06-09 16:53:44 -07004747 if (t->isInvalid()) {
4748 ALOGW("An invalidated track shouldn't be in active list");
4749 tracksToRemove->add(t);
4750 continue;
4751 }
4752
Eric Laurent81784c32012-11-19 14:55:58 -08004753 Track* const track = t.get();
4754 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004755 // Only consider last track started for volume and mixer state control.
4756 // In theory an older track could underrun and restart after the new one starts
4757 // but as we only care about the transition phase between two tracks on a
4758 // direct output, it is not a problem to ignore the underrun case.
4759 sp<Track> l = mLatestActiveTrack.promote();
4760 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004761
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004762 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004763 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004764 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004765 doHwPause = true;
4766 mHwPaused = true;
4767 }
4768 tracksToRemove->add(track);
4769 } else if (track->isFlushPending()) {
4770 track->flushAck();
4771 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004772 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004773 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004774 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004775 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004776 if (last && mHwPaused) {
4777 doHwResume = true;
4778 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004779 }
4780 }
4781
Eric Laurent81784c32012-11-19 14:55:58 -08004782 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004783 // for all its buffers to be filled before processing it.
4784 // Allow draining the buffer in case the client
4785 // app does not call stop() and relies on underrun to stop:
4786 // hence the test on (track->mRetryCount > 1).
4787 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004788 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004789 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004790 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004791 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004792 minFrames = mNormalFrameCount;
4793 } else {
4794 minFrames = 1;
4795 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004796
Eric Laurentab5cdba2014-06-09 17:22:27 -07004797 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4798 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004799 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004800 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004801
4802 if (track->mFillingUpStatus == Track::FS_FILLED) {
4803 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004804 // make sure processVolume_l() will apply new volume even if 0
4805 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004806 if (!mHwSupportsPause) {
4807 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004808 }
4809 }
4810
4811 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004812 processVolume_l(track, last);
4813 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004814 sp<Track> previousTrack = mPreviousTrack.promote();
4815 if (previousTrack != 0) {
4816 if (track != previousTrack.get()) {
4817 // Flush any data still being written from last track
4818 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004819 // Invalidate previous track to force a seek when resuming.
4820 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004821 }
4822 }
4823 mPreviousTrack = track;
4824
Eric Laurentd595b7c2013-04-03 17:27:56 -07004825 // reset retry count
4826 track->mRetryCount = kMaxTrackRetriesDirect;
4827 mActiveTrack = t;
4828 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004829 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004830 doHwResume = true;
4831 mHwPaused = false;
4832 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004833 }
Eric Laurent81784c32012-11-19 14:55:58 -08004834 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004835 // clear effect chain input buffer if the last active track started underruns
4836 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004837 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004838 mEffectChains[0]->clearInputBuffer();
4839 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004840 if (track->isStopping_1()) {
4841 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004842 if (last && mHwPaused) {
4843 doHwResume = true;
4844 mHwPaused = false;
4845 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004846 }
4847 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4848 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004849 // We have consumed all the buffers of this track.
4850 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004851 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004852 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004853 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4854 } else {
4855 audioHALFrames = 0;
4856 }
4857
Andy Hung818e7a32016-02-16 18:08:07 -08004858 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004859 if (mStandby || !last ||
4860 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004861 if (track->isStopping_2()) {
4862 track->mState = TrackBase::STOPPED;
4863 }
Eric Laurent81784c32012-11-19 14:55:58 -08004864 if (track->isStopped()) {
4865 track->reset();
4866 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004867 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004868 }
4869 } else {
4870 // No buffers for this track. Give it a few chances to
4871 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004872 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004873 if (--(track->mRetryCount) <= 0) {
4874 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004875 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004876 // indicate to client process that the track was disabled because of underrun;
4877 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004878 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004879 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004880 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4881 "minFrames = %u, mFormat = %#x",
4882 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004883 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004884 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004885 doHwPause = true;
4886 mHwPaused = true;
4887 }
Eric Laurent81784c32012-11-19 14:55:58 -08004888 }
4889 }
4890 }
4891 }
4892
Eric Laurentd1f69b02014-12-15 14:33:13 -08004893 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004894 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004895 for (size_t i = 0; i < mTracks.size(); i++) {
4896 if (mTracks[i]->isFlushPending()) {
4897 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004898 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004899 }
4900 }
4901 }
4902
4903 // make sure the pause/flush/resume sequence is executed in the right order.
4904 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4905 // before flush and then resume HW. This can happen in case of pause/flush/resume
4906 // if resume is received before pause is executed.
4907 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004908 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004909 mOutput->stream->pause(mOutput->stream);
4910 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004911 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004912 flushHw_l();
4913 }
4914 if (mHwSupportsPause && !mStandby && doHwResume) {
4915 mOutput->stream->resume(mOutput->stream);
4916 }
Eric Laurent81784c32012-11-19 14:55:58 -08004917 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004918 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004919
4920 return mixerStatus;
4921}
4922
4923void AudioFlinger::DirectOutputThread::threadLoop_mix()
4924{
Eric Laurent81784c32012-11-19 14:55:58 -08004925 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004926 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004927 // output audio to hardware
4928 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004929 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004930 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004931 status_t status = mActiveTrack->getNextBuffer(&buffer);
4932 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08004933 // no need to pad with 0 for compressed audio
4934 if (audio_has_proportional_frames(mFormat)) {
4935 memset(curBuf, 0, frameCount * mFrameSize);
4936 }
Eric Laurent81784c32012-11-19 14:55:58 -08004937 break;
4938 }
4939 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4940 frameCount -= buffer.frameCount;
4941 curBuf += buffer.frameCount * mFrameSize;
4942 mActiveTrack->releaseBuffer(&buffer);
4943 }
Andy Hung2098f272014-02-27 14:00:06 -08004944 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004945 mSleepTimeUs = 0;
4946 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004947 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004948}
4949
4950void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4951{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004952 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004953 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004954 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004955 return;
4956 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004957 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004958 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent51716182016-02-29 18:00:56 -08004959 // For compressed offload, use faster sleep time when underruning until more than an
4960 // entire buffer was written to the audio HAL
4961 if (!audio_has_proportional_frames(mFormat) &&
4962 (mType == OFFLOAD) && (mBytesWritten < mBufferSize)) {
4963 mSleepTimeUs = kDirectMinSleepTimeUs;
4964 } else {
4965 mSleepTimeUs = mActiveSleepTimeUs;
4966 }
Eric Laurent81784c32012-11-19 14:55:58 -08004967 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004968 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004969 }
Phil Burkfdb3c072016-02-09 10:47:02 -08004970 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004971 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004972 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004973 }
4974}
4975
Eric Laurentd1f69b02014-12-15 14:33:13 -08004976void AudioFlinger::DirectOutputThread::threadLoop_exit()
4977{
4978 {
4979 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004980 for (size_t i = 0; i < mTracks.size(); i++) {
4981 if (mTracks[i]->isFlushPending()) {
4982 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004983 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004984 }
4985 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004986 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004987 flushHw_l();
4988 }
4989 }
4990 PlaybackThread::threadLoop_exit();
4991}
4992
4993// must be called with thread mutex locked
4994bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4995{
4996 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004997 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004998
4999 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5000 // after a timeout and we will enter standby then.
5001 if (mTracks.size() > 0) {
5002 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005003 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5004 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005005 }
5006
Eric Laurent5cff4032015-05-26 13:49:58 -07005007 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005008}
5009
Eric Laurent81784c32012-11-19 14:55:58 -08005010// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005011int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -08005012 audio_format_t format __unused, audio_session_t sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005013{
5014 return 0;
5015}
5016
5017// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005018void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005019{
5020}
5021
Eric Laurent10351942014-05-08 18:49:52 -07005022// checkForNewParameter_l() must be called with ThreadBase::mLock held
5023bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5024 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005025{
5026 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005027 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005028
Eric Laurent10351942014-05-08 18:49:52 -07005029 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005030
Eric Laurent10351942014-05-08 18:49:52 -07005031 AudioParameter param = AudioParameter(keyValuePair);
5032 int value;
5033 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5034 // forward device change to effects that have requested to be
5035 // aware of attached audio device.
5036 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005037 a2dpDeviceChanged =
5038 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005039 mOutDevice = value;
5040 for (size_t i = 0; i < mEffectChains.size(); i++) {
5041 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005042 }
5043 }
Eric Laurent81784c32012-11-19 14:55:58 -08005044 }
Eric Laurent10351942014-05-08 18:49:52 -07005045 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5046 // do not accept frame count changes if tracks are open as the track buffer
5047 // size depends on frame count and correct behavior would not be garantied
5048 // if frame count is changed after track creation
5049 if (!mTracks.isEmpty()) {
5050 status = INVALID_OPERATION;
5051 } else {
5052 reconfig = true;
5053 }
5054 }
5055 if (status == NO_ERROR) {
5056 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5057 keyValuePair.string());
5058 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005059 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005060 mStandby = true;
5061 mBytesWritten = 0;
5062 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5063 keyValuePair.string());
5064 }
5065 if (status == NO_ERROR && reconfig) {
5066 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005067 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005068 }
5069 }
5070
Eric Laurent42537be2016-01-08 17:16:42 -08005071 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005072}
5073
5074uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5075{
5076 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005077 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005078 time = PlaybackThread::activeSleepTimeUs();
5079 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005080 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005081 }
5082 return time;
5083}
5084
5085uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5086{
5087 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005088 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005089 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5090 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005091 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005092 }
5093 return time;
5094}
5095
5096uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5097{
5098 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005099 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005100 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5101 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005102 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005103 }
5104 return time;
5105}
5106
5107void AudioFlinger::DirectOutputThread::cacheParameters_l()
5108{
5109 PlaybackThread::cacheParameters_l();
5110
5111 // use shorter standby delay as on normal output to release
5112 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005113 // no delay on outputs with HW A/V sync
5114 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005115 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005116 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005117 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005118 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005119 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005120 }
Eric Laurent81784c32012-11-19 14:55:58 -08005121}
5122
Eric Laurente659ef42014-09-29 13:06:46 -07005123void AudioFlinger::DirectOutputThread::flushHw_l()
5124{
Phil Burk062e67a2015-02-11 13:40:50 -08005125 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005126 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005127 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005128}
5129
Eric Laurent81784c32012-11-19 14:55:58 -08005130// ----------------------------------------------------------------------------
5131
Eric Laurentbfb1b832013-01-07 09:53:42 -08005132AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005133 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005134 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005135 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005136 mWriteAckSequence(0),
5137 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005138{
5139}
5140
5141AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5142{
5143}
5144
5145void AudioFlinger::AsyncCallbackThread::onFirstRef()
5146{
5147 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5148}
5149
5150bool AudioFlinger::AsyncCallbackThread::threadLoop()
5151{
5152 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005153 uint32_t writeAckSequence;
5154 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005155
5156 {
5157 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005158 while (!((mWriteAckSequence & 1) ||
5159 (mDrainSequence & 1) ||
5160 exitPending())) {
5161 mWaitWorkCV.wait(mLock);
5162 }
5163
Eric Laurentbfb1b832013-01-07 09:53:42 -08005164 if (exitPending()) {
5165 break;
5166 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005167 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5168 mWriteAckSequence, mDrainSequence);
5169 writeAckSequence = mWriteAckSequence;
5170 mWriteAckSequence &= ~1;
5171 drainSequence = mDrainSequence;
5172 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005173 }
5174 {
Eric Laurent4de95592013-09-26 15:28:21 -07005175 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5176 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005177 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005178 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005179 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005180 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005181 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005182 }
5183 }
5184 }
5185 }
5186 return false;
5187}
5188
5189void AudioFlinger::AsyncCallbackThread::exit()
5190{
5191 ALOGV("AsyncCallbackThread::exit");
5192 Mutex::Autolock _l(mLock);
5193 requestExit();
5194 mWaitWorkCV.broadcast();
5195}
5196
Eric Laurent3b4529e2013-09-05 18:09:19 -07005197void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005198{
5199 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005200 // bit 0 is cleared
5201 mWriteAckSequence = sequence << 1;
5202}
5203
5204void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5205{
5206 Mutex::Autolock _l(mLock);
5207 // ignore unexpected callbacks
5208 if (mWriteAckSequence & 2) {
5209 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005210 mWaitWorkCV.signal();
5211 }
5212}
5213
Eric Laurent3b4529e2013-09-05 18:09:19 -07005214void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005215{
5216 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005217 // bit 0 is cleared
5218 mDrainSequence = sequence << 1;
5219}
5220
5221void AudioFlinger::AsyncCallbackThread::resetDraining()
5222{
5223 Mutex::Autolock _l(mLock);
5224 // ignore unexpected callbacks
5225 if (mDrainSequence & 2) {
5226 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005227 mWaitWorkCV.signal();
5228 }
5229}
5230
5231
5232// ----------------------------------------------------------------------------
5233AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent51716182016-02-29 18:00:56 -08005234 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady,
5235 uint32_t bitRate)
5236 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady, bitRate),
Eric Laurentd7e59222013-11-15 12:02:28 -08005237 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005238{
Eric Laurentfd477972013-10-25 18:10:40 -07005239 //FIXME: mStandby should be set to true by ThreadBase constructor
5240 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005241}
5242
Eric Laurentbfb1b832013-01-07 09:53:42 -08005243void AudioFlinger::OffloadThread::threadLoop_exit()
5244{
5245 if (mFlushPending || mHwPaused) {
5246 // If a flush is pending or track was paused, just discard buffered data
5247 flushHw_l();
5248 } else {
5249 mMixerStatus = MIXER_DRAIN_ALL;
5250 threadLoop_drain();
5251 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005252 if (mUseAsyncWrite) {
5253 ALOG_ASSERT(mCallbackThread != 0);
5254 mCallbackThread->exit();
5255 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005256 PlaybackThread::threadLoop_exit();
5257}
5258
5259AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5260 Vector< sp<Track> > *tracksToRemove
5261)
5262{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005263 size_t count = mActiveTracks.size();
5264
5265 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005266 bool doHwPause = false;
5267 bool doHwResume = false;
5268
Eric Laurentede6c3b2013-09-19 14:37:46 -07005269 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5270
Eric Laurentbfb1b832013-01-07 09:53:42 -08005271 // find out which tracks need to be processed
5272 for (size_t i = 0; i < count; i++) {
5273 sp<Track> t = mActiveTracks[i].promote();
5274 // The track died recently
5275 if (t == 0) {
5276 continue;
5277 }
5278 Track* const track = t.get();
5279 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07005280 // Only consider last track started for volume and mixer state control.
5281 // In theory an older track could underrun and restart after the new one starts
5282 // but as we only care about the transition phase between two tracks on a
5283 // direct output, it is not a problem to ignore the underrun case.
5284 sp<Track> l = mLatestActiveTrack.promote();
5285 bool last = l.get() == track;
5286
Haynes Mathew George7844f672014-01-15 12:32:55 -08005287 if (track->isInvalid()) {
5288 ALOGW("An invalidated track shouldn't be in active list");
5289 tracksToRemove->add(track);
5290 continue;
5291 }
5292
5293 if (track->mState == TrackBase::IDLE) {
5294 ALOGW("An idle track shouldn't be in active list");
5295 continue;
5296 }
5297
Eric Laurentbfb1b832013-01-07 09:53:42 -08005298 if (track->isPausing()) {
5299 track->setPaused();
5300 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005301 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005302 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005303 mHwPaused = true;
5304 }
5305 // If we were part way through writing the mixbuffer to
5306 // the HAL we must save this until we resume
5307 // BUG - this will be wrong if a different track is made active,
5308 // in that case we want to discard the pending data in the
5309 // mixbuffer and tell the client to present it again when the
5310 // track is resumed
5311 mPausedWriteLength = mCurrentWriteLength;
5312 mPausedBytesRemaining = mBytesRemaining;
5313 mBytesRemaining = 0; // stop writing
5314 }
5315 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005316 } else if (track->isFlushPending()) {
Eric Laurent51716182016-02-29 18:00:56 -08005317 track->mRetryCount = kMaxTrackRetriesOffload;
Haynes Mathew George7844f672014-01-15 12:32:55 -08005318 track->flushAck();
5319 if (last) {
5320 mFlushPending = true;
5321 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005322 } else if (track->isResumePending()){
5323 track->resumeAck();
5324 if (last) {
5325 if (mPausedBytesRemaining) {
5326 // Need to continue write that was interrupted
5327 mCurrentWriteLength = mPausedWriteLength;
5328 mBytesRemaining = mPausedBytesRemaining;
5329 mPausedBytesRemaining = 0;
5330 }
5331 if (mHwPaused) {
5332 doHwResume = true;
5333 mHwPaused = false;
5334 // threadLoop_mix() will handle the case that we need to
5335 // resume an interrupted write
5336 }
5337 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005338 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005339
5340 // Do not handle new data in this iteration even if track->framesReady()
5341 mixerStatus = MIXER_TRACKS_ENABLED;
5342 }
5343 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005344 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005345 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005346 if (track->mFillingUpStatus == Track::FS_FILLED) {
5347 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005348 // make sure processVolume_l() will apply new volume even if 0
5349 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005350 }
5351
5352 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005353 sp<Track> previousTrack = mPreviousTrack.promote();
5354 if (previousTrack != 0) {
5355 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005356 // Flush any data still being written from last track
5357 mBytesRemaining = 0;
5358 if (mPausedBytesRemaining) {
5359 // Last track was paused so we also need to flush saved
5360 // mixbuffer state and invalidate track so that it will
5361 // re-submit that unwritten data when it is next resumed
5362 mPausedBytesRemaining = 0;
5363 // Invalidate is a bit drastic - would be more efficient
5364 // to have a flag to tell client that some of the
5365 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005366 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005367 }
5368 // flush data already sent to the DSP if changing audio session as audio
5369 // comes from a different source. Also invalidate previous track to force a
5370 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005371 if (previousTrack->sessionId() != track->sessionId()) {
5372 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005373 }
5374 }
5375 }
5376 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005377 // reset retry count
5378 track->mRetryCount = kMaxTrackRetriesOffload;
5379 mActiveTrack = t;
5380 mixerStatus = MIXER_TRACKS_READY;
5381 }
5382 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005383 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005384 if (track->isStopping_1()) {
5385 // Hardware buffer can hold a large amount of audio so we must
5386 // wait for all current track's data to drain before we say
5387 // that the track is stopped.
5388 if (mBytesRemaining == 0) {
5389 // Only start draining when all data in mixbuffer
5390 // has been written
5391 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5392 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005393 // do not drain if no data was ever sent to HAL (mStandby == true)
5394 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005395 // do not modify drain sequence if we are already draining. This happens
5396 // when resuming from pause after drain.
5397 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005398 mSleepTimeUs = 0;
5399 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005400 mixerStatus = MIXER_DRAIN_TRACK;
5401 mDrainSequence += 2;
5402 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005403 if (mHwPaused) {
5404 // It is possible to move from PAUSED to STOPPING_1 without
5405 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005406 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005407 mHwPaused = false;
5408 }
5409 }
5410 }
5411 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005412 // Drain has completed or we are in standby, signal presentation complete
5413 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005414 track->mState = TrackBase::STOPPED;
5415 size_t audioHALFrames =
5416 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005417 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005418 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005419 track->presentationComplete(framesWritten, audioHALFrames);
5420 track->reset();
5421 tracksToRemove->add(track);
5422 }
5423 } else {
5424 // No buffers for this track. Give it a few chances to
5425 // fill a buffer, then remove it from active list.
5426 if (--(track->mRetryCount) <= 0) {
5427 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5428 track->name());
5429 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005430 // indicate to client process that the track was disabled because of underrun;
5431 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005432 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005433 } else if (last){
5434 mixerStatus = MIXER_TRACKS_ENABLED;
5435 }
5436 }
5437 }
5438 // compute volume for this track
5439 processVolume_l(track, last);
5440 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005441
Eric Laurentea0fade2013-10-04 16:23:48 -07005442 // make sure the pause/flush/resume sequence is executed in the right order.
5443 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5444 // before flush and then resume HW. This can happen in case of pause/flush/resume
5445 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005446 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005447 mOutput->stream->pause(mOutput->stream);
5448 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005449 if (mFlushPending) {
5450 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005451 }
Eric Laurentfd477972013-10-25 18:10:40 -07005452 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005453 mOutput->stream->resume(mOutput->stream);
5454 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005455
Eric Laurentbfb1b832013-01-07 09:53:42 -08005456 // remove all the tracks that need to be...
5457 removeTracks_l(*tracksToRemove);
5458
5459 return mixerStatus;
5460}
5461
Eric Laurentbfb1b832013-01-07 09:53:42 -08005462// must be called with thread mutex locked
5463bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5464{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005465 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5466 mWriteAckSequence, mDrainSequence);
5467 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005468 return true;
5469 }
5470 return false;
5471}
5472
Eric Laurentbfb1b832013-01-07 09:53:42 -08005473bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5474{
5475 Mutex::Autolock _l(mLock);
5476 return waitingAsyncCallback_l();
5477}
5478
5479void AudioFlinger::OffloadThread::flushHw_l()
5480{
Eric Laurente659ef42014-09-29 13:06:46 -07005481 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005482 // Flush anything still waiting in the mixbuffer
5483 mCurrentWriteLength = 0;
5484 mBytesRemaining = 0;
5485 mPausedWriteLength = 0;
5486 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005487
Eric Laurentbfb1b832013-01-07 09:53:42 -08005488 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005489 // discard any pending drain or write ack by incrementing sequence
5490 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5491 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005492 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005493 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5494 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005495 }
5496}
5497
Eric Laurent51716182016-02-29 18:00:56 -08005498uint32_t AudioFlinger::OffloadThread::activeSleepTimeUs() const
5499{
5500 uint32_t time;
5501 if (audio_has_proportional_frames(mFormat)) {
5502 time = PlaybackThread::activeSleepTimeUs();
5503 } else {
5504 // sleep time is half the duration of an audio HAL buffer.
5505 // Note: This can be problematic in case of underrun with variable bit rate and
5506 // current rate is much less than initial rate.
5507 time = (uint32_t)max(kDirectMinSleepTimeUs, mBufferDurationUs / 2);
5508 }
5509 return time;
5510}
5511
Eric Laurentbfb1b832013-01-07 09:53:42 -08005512// ----------------------------------------------------------------------------
5513
Eric Laurent81784c32012-11-19 14:55:58 -08005514AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005515 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005516 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005517 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005518 mWaitTimeMs(UINT_MAX)
5519{
5520 addOutputTrack(mainThread);
5521}
5522
5523AudioFlinger::DuplicatingThread::~DuplicatingThread()
5524{
5525 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5526 mOutputTracks[i]->destroy();
5527 }
5528}
5529
5530void AudioFlinger::DuplicatingThread::threadLoop_mix()
5531{
5532 // mix buffers...
5533 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005534 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005535 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005536 if (mMixerBufferValid) {
5537 memset(mMixerBuffer, 0, mMixerBufferSize);
5538 } else {
5539 memset(mSinkBuffer, 0, mSinkBufferSize);
5540 }
Eric Laurent81784c32012-11-19 14:55:58 -08005541 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005542 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005543 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005544 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005545 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005546}
5547
5548void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5549{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005550 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005551 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005552 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005553 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005554 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005555 }
5556 } else if (mBytesWritten != 0) {
5557 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5558 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005559 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005560 } else {
5561 // flush remaining overflow buffers in output tracks
5562 writeFrames = 0;
5563 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005564 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005565 }
5566}
5567
Eric Laurentbfb1b832013-01-07 09:53:42 -08005568ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005569{
5570 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005571 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005572 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005573 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005574 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005575}
5576
5577void AudioFlinger::DuplicatingThread::threadLoop_standby()
5578{
5579 // DuplicatingThread implements standby by stopping all tracks
5580 for (size_t i = 0; i < outputTracks.size(); i++) {
5581 outputTracks[i]->stop();
5582 }
5583}
5584
5585void AudioFlinger::DuplicatingThread::saveOutputTracks()
5586{
5587 outputTracks = mOutputTracks;
5588}
5589
5590void AudioFlinger::DuplicatingThread::clearOutputTracks()
5591{
5592 outputTracks.clear();
5593}
5594
5595void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5596{
5597 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005598 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5599 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5600 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5601 const size_t frameCount =
5602 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5603 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5604 // from different OutputTracks and their associated MixerThreads (e.g. one may
5605 // nearly empty and the other may be dropping data).
5606
5607 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005608 this,
5609 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005610 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005611 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005612 frameCount,
5613 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005614 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005615 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005616 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005617 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005618 updateWaitTime_l();
5619 }
5620}
5621
5622void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5623{
5624 Mutex::Autolock _l(mLock);
5625 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5626 if (mOutputTracks[i]->thread() == thread) {
5627 mOutputTracks[i]->destroy();
5628 mOutputTracks.removeAt(i);
5629 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005630 if (thread->getOutput() == mOutput) {
5631 mOutput = NULL;
5632 }
Eric Laurent81784c32012-11-19 14:55:58 -08005633 return;
5634 }
5635 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005636 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005637}
5638
5639// caller must hold mLock
5640void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5641{
5642 mWaitTimeMs = UINT_MAX;
5643 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5644 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5645 if (strong != 0) {
5646 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5647 if (waitTimeMs < mWaitTimeMs) {
5648 mWaitTimeMs = waitTimeMs;
5649 }
5650 }
5651 }
5652}
5653
5654
5655bool AudioFlinger::DuplicatingThread::outputsReady(
5656 const SortedVector< sp<OutputTrack> > &outputTracks)
5657{
5658 for (size_t i = 0; i < outputTracks.size(); i++) {
5659 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5660 if (thread == 0) {
5661 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5662 outputTracks[i].get());
5663 return false;
5664 }
5665 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5666 // see note at standby() declaration
5667 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5668 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5669 thread.get());
5670 return false;
5671 }
5672 }
5673 return true;
5674}
5675
5676uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5677{
5678 return (mWaitTimeMs * 1000) / 2;
5679}
5680
5681void AudioFlinger::DuplicatingThread::cacheParameters_l()
5682{
5683 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5684 updateWaitTime_l();
5685
5686 MixerThread::cacheParameters_l();
5687}
5688
5689// ----------------------------------------------------------------------------
5690// Record
5691// ----------------------------------------------------------------------------
5692
5693AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5694 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005695 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005696 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005697 audio_devices_t inDevice,
5698 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005699#ifdef TEE_SINK
5700 , const sp<NBAIO_Sink>& teeSink
5701#endif
5702 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005703 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005704 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005705 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005706 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005707#ifdef TEE_SINK
5708 , mTeeSink(teeSink)
5709#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005710 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5711 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005712 // mFastCapture below
5713 , mFastCaptureFutex(0)
5714 // mInputSource
5715 // mPipeSink
5716 // mPipeSource
5717 , mPipeFramesP2(0)
5718 // mPipeMemory
5719 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005720 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005721{
Glenn Kastend7dca052015-03-05 16:05:54 -08005722 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5723 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005724
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005725 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005726
5727 // create an NBAIO source for the HAL input stream, and negotiate
5728 mInputSource = new AudioStreamInSource(input->stream);
5729 size_t numCounterOffers = 0;
5730 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5731 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5732 ALOG_ASSERT(index == 0);
5733
5734 // initialize fast capture depending on configuration
5735 bool initFastCapture;
5736 switch (kUseFastCapture) {
5737 case FastCapture_Never:
5738 initFastCapture = false;
5739 break;
5740 case FastCapture_Always:
5741 initFastCapture = true;
5742 break;
5743 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005744 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005745 break;
5746 // case FastCapture_Dynamic:
5747 }
5748
5749 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005750 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005751 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005752 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005753 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5754 void *pipeBuffer;
5755 const sp<MemoryDealer> roHeap(readOnlyHeap());
5756 sp<IMemory> pipeMemory;
5757 if ((roHeap == 0) ||
5758 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5759 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5760 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5761 goto failed;
5762 }
5763 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5764 memset(pipeBuffer, 0, pipeSize);
5765 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5766 const NBAIO_Format offers[1] = {format};
5767 size_t numCounterOffers = 0;
5768 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5769 ALOG_ASSERT(index == 0);
5770 mPipeSink = pipe;
5771 PipeReader *pipeReader = new PipeReader(*pipe);
5772 numCounterOffers = 0;
5773 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5774 ALOG_ASSERT(index == 0);
5775 mPipeSource = pipeReader;
5776 mPipeFramesP2 = pipeFramesP2;
5777 mPipeMemory = pipeMemory;
5778
5779 // create fast capture
5780 mFastCapture = new FastCapture();
5781 FastCaptureStateQueue *sq = mFastCapture->sq();
5782#ifdef STATE_QUEUE_DUMP
5783 // FIXME
5784#endif
5785 FastCaptureState *state = sq->begin();
5786 state->mCblk = NULL;
5787 state->mInputSource = mInputSource.get();
5788 state->mInputSourceGen++;
5789 state->mPipeSink = pipe;
5790 state->mPipeSinkGen++;
5791 state->mFrameCount = mFrameCount;
5792 state->mCommand = FastCaptureState::COLD_IDLE;
5793 // already done in constructor initialization list
5794 //mFastCaptureFutex = 0;
5795 state->mColdFutexAddr = &mFastCaptureFutex;
5796 state->mColdGen++;
5797 state->mDumpState = &mFastCaptureDumpState;
5798#ifdef TEE_SINK
5799 // FIXME
5800#endif
5801 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5802 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5803 sq->end();
5804 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5805
5806 // start the fast capture
5807 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5808 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005809 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005810#ifdef AUDIO_WATCHDOG
5811 // FIXME
5812#endif
5813
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005814 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005815 }
5816failed: ;
5817
5818 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005819}
5820
Eric Laurent81784c32012-11-19 14:55:58 -08005821AudioFlinger::RecordThread::~RecordThread()
5822{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005823 if (mFastCapture != 0) {
5824 FastCaptureStateQueue *sq = mFastCapture->sq();
5825 FastCaptureState *state = sq->begin();
5826 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5827 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5828 if (old == -1) {
5829 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5830 }
5831 }
5832 state->mCommand = FastCaptureState::EXIT;
5833 sq->end();
5834 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5835 mFastCapture->join();
5836 mFastCapture.clear();
5837 }
5838 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005839 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005840 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005841}
5842
5843void AudioFlinger::RecordThread::onFirstRef()
5844{
Glenn Kastend7dca052015-03-05 16:05:54 -08005845 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005846}
5847
Eric Laurent81784c32012-11-19 14:55:58 -08005848bool AudioFlinger::RecordThread::threadLoop()
5849{
Eric Laurent81784c32012-11-19 14:55:58 -08005850 nsecs_t lastWarning = 0;
5851
5852 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005853
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005854reacquire_wakelock:
5855 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005856 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005857 {
5858 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005859 size_t size = mActiveTracks.size();
5860 activeTracksGen = mActiveTracksGen;
5861 if (size > 0) {
5862 // FIXME an arbitrary choice
5863 activeTrack = mActiveTracks[0];
5864 acquireWakeLock_l(activeTrack->uid());
5865 if (size > 1) {
5866 SortedVector<int> tmp;
5867 for (size_t i = 0; i < size; i++) {
5868 tmp.add(mActiveTracks[i]->uid());
5869 }
5870 updateWakeLockUids_l(tmp);
5871 }
5872 } else {
5873 acquireWakeLock_l(-1);
5874 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005875 }
5876
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005877 // used to request a deferred sleep, to be executed later while mutex is unlocked
5878 uint32_t sleepUs = 0;
5879
5880 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005881 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005882 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005883
Glenn Kasten5edadd42013-08-14 16:30:49 -07005884 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005885 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005886 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005887 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005888 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005889 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005890 }
5891
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005892 // activeTracks accumulates a copy of a subset of mActiveTracks
5893 Vector< sp<RecordTrack> > activeTracks;
5894
Glenn Kasten735f45f2014-08-18 15:51:59 -07005895 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005896 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005897
Glenn Kasten735f45f2014-08-18 15:51:59 -07005898 // reference to a fast track which is about to be removed
5899 sp<RecordTrack> fastTrackToRemove;
5900
Eric Laurent81784c32012-11-19 14:55:58 -08005901 { // scope for mLock
5902 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005903
Eric Laurent021cf962014-05-13 10:18:14 -07005904 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005905
Eric Laurent000a4192014-01-29 15:17:32 -08005906 // check exitPending here because checkForNewParameters_l() and
5907 // checkForNewParameters_l() can temporarily release mLock
5908 if (exitPending()) {
5909 break;
5910 }
5911
Glenn Kasten2b806402013-11-20 16:37:38 -08005912 // if no active track(s), then standby and release wakelock
5913 size_t size = mActiveTracks.size();
5914 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005915 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005916 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005917 releaseWakeLock_l();
5918 ALOGV("RecordThread: loop stopping");
5919 // go to sleep
5920 mWaitWorkCV.wait(mLock);
5921 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005922 goto reacquire_wakelock;
5923 }
5924
Glenn Kasten2b806402013-11-20 16:37:38 -08005925 if (mActiveTracksGen != activeTracksGen) {
5926 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005927 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005928 for (size_t i = 0; i < size; i++) {
5929 tmp.add(mActiveTracks[i]->uid());
5930 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005931 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005932 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005933
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005934 bool doBroadcast = false;
5935 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005936
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005937 activeTrack = mActiveTracks[i];
5938 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005939 if (activeTrack->isFastTrack()) {
5940 ALOG_ASSERT(fastTrackToRemove == 0);
5941 fastTrackToRemove = activeTrack;
5942 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005943 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005944 mActiveTracks.remove(activeTrack);
5945 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005946 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005947 continue;
5948 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005949
5950 TrackBase::track_state activeTrackState = activeTrack->mState;
5951 switch (activeTrackState) {
5952
5953 case TrackBase::PAUSING:
5954 mActiveTracks.remove(activeTrack);
5955 mActiveTracksGen++;
5956 doBroadcast = true;
5957 size--;
5958 continue;
5959
5960 case TrackBase::STARTING_1:
5961 sleepUs = 10000;
5962 i++;
5963 continue;
5964
5965 case TrackBase::STARTING_2:
5966 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005967 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005968 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005969 break;
5970
5971 case TrackBase::ACTIVE:
5972 break;
5973
5974 case TrackBase::IDLE:
5975 i++;
5976 continue;
5977
5978 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005979 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005980 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005981
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005982 activeTracks.add(activeTrack);
5983 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005984
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005985 if (activeTrack->isFastTrack()) {
5986 ALOG_ASSERT(!mFastTrackAvail);
5987 ALOG_ASSERT(fastTrack == 0);
5988 fastTrack = activeTrack;
5989 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005990 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005991 if (doBroadcast) {
5992 mStartStopCond.broadcast();
5993 }
5994
5995 // sleep if there are no active tracks to process
5996 if (activeTracks.size() == 0) {
5997 if (sleepUs == 0) {
5998 sleepUs = kRecordThreadSleepUs;
5999 }
6000 continue;
6001 }
6002 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006003
Eric Laurent81784c32012-11-19 14:55:58 -08006004 lockEffectChains_l(effectChains);
6005 }
6006
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006007 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006008
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006009 size_t size = effectChains.size();
6010 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006011 // thread mutex is not locked, but effect chain is locked
6012 effectChains[i]->process_l();
6013 }
6014
Glenn Kasten735f45f2014-08-18 15:51:59 -07006015 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006016 if (mFastCapture != 0) {
6017 FastCaptureStateQueue *sq = mFastCapture->sq();
6018 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006019 bool didModify = false;
6020 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006021 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6022 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6023 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6024 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6025 if (old == -1) {
6026 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6027 }
6028 }
6029 state->mCommand = FastCaptureState::READ_WRITE;
6030#if 0 // FIXME
6031 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006032 FastThreadDumpState::kSamplingNforLowRamDevice :
6033 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006034#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006035 didModify = true;
6036 }
6037 audio_track_cblk_t *cblkOld = state->mCblk;
6038 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6039 if (cblkNew != cblkOld) {
6040 state->mCblk = cblkNew;
6041 // block until acked if removing a fast track
6042 if (cblkOld != NULL) {
6043 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6044 }
6045 didModify = true;
6046 }
6047 sq->end(didModify);
6048 if (didModify) {
6049 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006050#if 0
6051 if (kUseFastCapture == FastCapture_Dynamic) {
6052 mNormalSource = mPipeSource;
6053 }
6054#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006055 }
6056 }
6057
Glenn Kasten735f45f2014-08-18 15:51:59 -07006058 // now run the fast track destructor with thread mutex unlocked
6059 fastTrackToRemove.clear();
6060
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006061 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6062 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6063 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6064 // If destination is non-contiguous, first read past the nominal end of buffer, then
6065 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006066
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006067 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006068 ssize_t framesRead;
6069
6070 // If an NBAIO source is present, use it to read the normal capture's data
6071 if (mPipeSource != 0) {
6072 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07006073 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006074 framesToRead);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006075 if (framesRead == 0) {
6076 // since pipe is non-blocking, simulate blocking input
6077 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
6078 }
6079 // otherwise use the HAL / AudioStreamIn directly
6080 } else {
6081 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07006082 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006083 if (bytesRead < 0) {
6084 framesRead = bytesRead;
6085 } else {
6086 framesRead = bytesRead / mFrameSize;
6087 }
6088 }
6089
Andy Hung3f0c9022016-01-15 17:49:46 -08006090 // Update server timestamp with server stats
6091 // systemTime() is optional if the hardware supports timestamps.
6092 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6093 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6094
6095 // Update server timestamp with kernel stats
6096 if (mInput->stream->get_capture_position != nullptr) {
6097 int64_t position, time;
6098 int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time);
6099 if (ret == NO_ERROR) {
6100 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6101 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6102 // Note: In general record buffers should tend to be empty in
6103 // a properly running pipeline.
6104 //
6105 // Also, it is not advantageous to call get_presentation_position during the read
6106 // as the read obtains a lock, preventing the timestamp call from executing.
6107 }
6108 }
6109 // Use this to track timestamp information
6110 // ALOGD("%s", mTimestamp.toString().c_str());
6111
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006112 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
6113 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006114 // Force input into standby so that it tries to recover at next read attempt
6115 inputStandBy();
6116 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006117 }
6118 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006119 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006120 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006121 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006122
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006123 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006124 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006125 }
6126 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006127 {
6128 size_t part1 = mRsmpInFramesP2 - rear;
6129 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006130 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006131 (framesRead - part1) * mFrameSize);
6132 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006133 }
6134 rear = mRsmpInRear += framesRead;
6135
6136 size = activeTracks.size();
6137 // loop over each active track
6138 for (size_t i = 0; i < size; i++) {
6139 activeTrack = activeTracks[i];
6140
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006141 // skip fast tracks, as those are handled directly by FastCapture
6142 if (activeTrack->isFastTrack()) {
6143 continue;
6144 }
6145
Andy Hung73c02e42015-03-29 01:13:58 -07006146 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006147 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6148
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006149 enum {
6150 OVERRUN_UNKNOWN,
6151 OVERRUN_TRUE,
6152 OVERRUN_FALSE
6153 } overrun = OVERRUN_UNKNOWN;
6154
6155 // loop over getNextBuffer to handle circular sink
6156 for (;;) {
6157
6158 activeTrack->mSink.frameCount = ~0;
6159 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6160 size_t framesOut = activeTrack->mSink.frameCount;
6161 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6162
Andy Hung73c02e42015-03-29 01:13:58 -07006163 // check available frames and handle overrun conditions
6164 // if the record track isn't draining fast enough.
6165 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006166 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006167 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6168 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006169 overrun = OVERRUN_TRUE;
6170 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006171 if (framesOut == 0 || framesIn == 0) {
6172 break;
6173 }
6174
Andy Hung6770c6f2015-04-07 13:43:36 -07006175 // Don't allow framesOut to be larger than what is possible with resampling
6176 // from framesIn.
6177 // This isn't strictly necessary but helps limit buffer resizing in
6178 // RecordBufferConverter. TODO: remove when no longer needed.
6179 framesOut = min(framesOut,
6180 destinationFramesPossible(
6181 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006182 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6183 framesOut = activeTrack->mRecordBufferConverter->convert(
6184 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006185
6186 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6187 overrun = OVERRUN_FALSE;
6188 }
6189
6190 if (activeTrack->mFramesToDrop == 0) {
6191 if (framesOut > 0) {
6192 activeTrack->mSink.frameCount = framesOut;
6193 activeTrack->releaseBuffer(&activeTrack->mSink);
6194 }
6195 } else {
6196 // FIXME could do a partial drop of framesOut
6197 if (activeTrack->mFramesToDrop > 0) {
6198 activeTrack->mFramesToDrop -= framesOut;
6199 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006200 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006201 }
6202 } else {
6203 activeTrack->mFramesToDrop += framesOut;
6204 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6205 activeTrack->mSyncStartEvent->isCancelled()) {
6206 ALOGW("Synced record %s, session %d, trigger session %d",
6207 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6208 activeTrack->sessionId(),
6209 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006210 activeTrack->mSyncStartEvent->triggerSession() :
6211 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006212 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006213 }
6214 }
6215 }
6216
6217 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006218 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006219 }
6220 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006221
6222 switch (overrun) {
6223 case OVERRUN_TRUE:
6224 // client isn't retrieving buffers fast enough
6225 if (!activeTrack->setOverflow()) {
6226 nsecs_t now = systemTime();
6227 // FIXME should lastWarning per track?
6228 if ((now - lastWarning) > kWarningThrottleNs) {
6229 ALOGW("RecordThread: buffer overflow");
6230 lastWarning = now;
6231 }
6232 }
6233 break;
6234 case OVERRUN_FALSE:
6235 activeTrack->clearOverflow();
6236 break;
6237 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006238 break;
6239 }
6240
Andy Hung3f0c9022016-01-15 17:49:46 -08006241 // update frame information and push timestamp out
6242 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006243 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006244 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6245 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006246 }
6247
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006248unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006249 // enable changes in effect chain
6250 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006251 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006252 }
6253
Glenn Kasten93e471f2013-08-19 08:40:07 -07006254 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006255
6256 {
6257 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006258 for (size_t i = 0; i < mTracks.size(); i++) {
6259 sp<RecordTrack> track = mTracks[i];
6260 track->invalidate();
6261 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006262 mActiveTracks.clear();
6263 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006264 mStartStopCond.broadcast();
6265 }
6266
6267 releaseWakeLock();
6268
6269 ALOGV("RecordThread %p exiting", this);
6270 return false;
6271}
6272
Glenn Kasten93e471f2013-08-19 08:40:07 -07006273void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006274{
6275 if (!mStandby) {
6276 inputStandBy();
6277 mStandby = true;
6278 }
6279}
6280
6281void AudioFlinger::RecordThread::inputStandBy()
6282{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006283 // Idle the fast capture if it's currently running
6284 if (mFastCapture != 0) {
6285 FastCaptureStateQueue *sq = mFastCapture->sq();
6286 FastCaptureState *state = sq->begin();
6287 if (!(state->mCommand & FastCaptureState::IDLE)) {
6288 state->mCommand = FastCaptureState::COLD_IDLE;
6289 state->mColdFutexAddr = &mFastCaptureFutex;
6290 state->mColdGen++;
6291 mFastCaptureFutex = 0;
6292 sq->end();
6293 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6294 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6295#if 0
6296 if (kUseFastCapture == FastCapture_Dynamic) {
6297 // FIXME
6298 }
6299#endif
6300#ifdef AUDIO_WATCHDOG
6301 // FIXME
6302#endif
6303 } else {
6304 sq->end(false /*didModify*/);
6305 }
6306 }
Eric Laurent81784c32012-11-19 14:55:58 -08006307 mInput->stream->common.standby(&mInput->stream->common);
6308}
6309
Glenn Kasten05997e22014-03-13 15:08:33 -07006310// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006311sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006312 const sp<AudioFlinger::Client>& client,
6313 uint32_t sampleRate,
6314 audio_format_t format,
6315 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006316 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006317 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006318 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006319 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006320 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006321 pid_t tid,
6322 status_t *status)
6323{
Glenn Kasten74935e42013-12-19 08:56:45 -08006324 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006325 sp<RecordTrack> track;
6326 status_t lStatus;
6327
Glenn Kasten90e58b12013-07-31 16:16:02 -07006328 // client expresses a preference for FAST, but we get the final say
6329 if (*flags & IAudioFlinger::TRACK_FAST) {
6330 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006331 // we formerly checked for a callback handler (non-0 tid),
6332 // but that is no longer required for TRANSFER_OBTAIN mode
6333 //
Glenn Kasten74105912014-07-03 12:28:53 -07006334 // frame count is not specified, or is exactly the pipe depth
6335 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006336 // PCM data
6337 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006338 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006339 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006340 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006341 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006342 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006343 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006344 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006345 hasFastCapture() &&
6346 // there are sufficient fast track slots available
6347 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006348 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07006349 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006350 frameCount, mFrameCount);
6351 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07006352 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6353 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006354 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006355 frameCount, mFrameCount, mPipeFramesP2,
6356 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6357 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006358 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006359 }
6360 }
6361
6362 // compute track buffer size in frames, and suggest the notification frame count
6363 if (*flags & IAudioFlinger::TRACK_FAST) {
6364 // fast track: frame count is exactly the pipe depth
6365 frameCount = mPipeFramesP2;
6366 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6367 *notificationFrames = mFrameCount;
6368 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006369 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6370 // or 20 ms if there is a fast capture
6371 // TODO This could be a roundupRatio inline, and const
6372 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6373 * sampleRate + mSampleRate - 1) / mSampleRate;
6374 // minimum number of notification periods is at least kMinNotifications,
6375 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6376 static const size_t kMinNotifications = 3;
6377 static const uint32_t kMinMs = 30;
6378 // TODO This could be a roundupRatio inline
6379 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6380 // TODO This could be a roundupRatio inline
6381 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6382 maxNotificationFrames;
6383 const size_t minFrameCount = maxNotificationFrames *
6384 max(kMinNotifications, minNotificationsByMs);
6385 frameCount = max(frameCount, minFrameCount);
6386 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6387 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006388 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006389 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006390 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006391
Glenn Kasten15e57982013-09-24 11:52:37 -07006392 lStatus = initCheck();
6393 if (lStatus != NO_ERROR) {
6394 ALOGE("createRecordTrack_l() audio driver not initialized");
6395 goto Exit;
6396 }
Eric Laurent81784c32012-11-19 14:55:58 -08006397
6398 { // scope for mLock
6399 Mutex::Autolock _l(mLock);
6400
6401 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006402 format, channelMask, frameCount, NULL, sessionId, uid,
6403 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006404
Glenn Kasten03003332013-08-06 15:40:54 -07006405 lStatus = track->initCheck();
6406 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006407 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006408 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006409 goto Exit;
6410 }
6411 mTracks.add(track);
6412
6413 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6414 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6415 mAudioFlinger->btNrecIsOff();
6416 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6417 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006418
6419 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6420 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6421 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6422 // so ask activity manager to do this on our behalf
6423 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6424 }
Eric Laurent81784c32012-11-19 14:55:58 -08006425 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006426
Eric Laurent81784c32012-11-19 14:55:58 -08006427 lStatus = NO_ERROR;
6428
6429Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006430 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006431 return track;
6432}
6433
6434status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6435 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006436 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006437{
6438 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6439 sp<ThreadBase> strongMe = this;
6440 status_t status = NO_ERROR;
6441
6442 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006443 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006444 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006445 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006446 triggerSession,
6447 recordTrack->sessionId(),
6448 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006449 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006450 // Sync event can be cancelled by the trigger session if the track is not in a
6451 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006452 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006453 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006454 } else {
6455 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006456 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006457 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006458 }
6459 }
6460
6461 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006462 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006463 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006464 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6465 if (recordTrack->mState == TrackBase::PAUSING) {
6466 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006467 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006468 } else {
6469 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006470 }
6471 return status;
6472 }
6473
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006474 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6475 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6476 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006477 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006478 mActiveTracks.add(recordTrack);
6479 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006480 status_t status = NO_ERROR;
6481 if (recordTrack->isExternalTrack()) {
6482 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006483 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006484 mLock.lock();
6485 // FIXME should verify that recordTrack is still in mActiveTracks
6486 if (status != NO_ERROR) {
6487 mActiveTracks.remove(recordTrack);
6488 mActiveTracksGen++;
6489 recordTrack->clearSyncStartEvent();
6490 ALOGV("RecordThread::start error %d", status);
6491 return status;
6492 }
Eric Laurent81784c32012-11-19 14:55:58 -08006493 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006494 // Catch up with current buffer indices if thread is already running.
6495 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6496 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6497 // see previously buffered data before it called start(), but with greater risk of overrun.
6498
Andy Hung73c02e42015-03-29 01:13:58 -07006499 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006500 // clear any converter state as new data will be discontinuous
6501 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006502 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006503 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006504 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006505 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006506 ALOGV("Record failed to start");
6507 status = BAD_VALUE;
6508 goto startError;
6509 }
Eric Laurent81784c32012-11-19 14:55:58 -08006510 return status;
6511 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006512
Eric Laurent81784c32012-11-19 14:55:58 -08006513startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006514 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006515 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006516 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006517 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006518 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006519 return status;
6520}
6521
Eric Laurent81784c32012-11-19 14:55:58 -08006522void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6523{
6524 sp<SyncEvent> strongEvent = event.promote();
6525
6526 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006527 sp<RefBase> ptr = strongEvent->cookie().promote();
6528 if (ptr != 0) {
6529 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6530 recordTrack->handleSyncStartEvent(strongEvent);
6531 }
Eric Laurent81784c32012-11-19 14:55:58 -08006532 }
6533}
6534
Glenn Kastena8356f62013-07-25 14:37:52 -07006535bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006536 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006537 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006538 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006539 return false;
6540 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006541 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006542 recordTrack->mState = TrackBase::PAUSING;
6543 // do not wait for mStartStopCond if exiting
6544 if (exitPending()) {
6545 return true;
6546 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006547 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006548 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006549 // if we have been restarted, recordTrack is in mActiveTracks here
6550 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006551 ALOGV("Record stopped OK");
6552 return true;
6553 }
6554 return false;
6555}
6556
Glenn Kasten0f11b512014-01-31 16:18:54 -08006557bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006558{
6559 return false;
6560}
6561
Glenn Kasten0f11b512014-01-31 16:18:54 -08006562status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006563{
6564#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6565 if (!isValidSyncEvent(event)) {
6566 return BAD_VALUE;
6567 }
6568
Glenn Kastend848eb42016-03-08 13:42:11 -08006569 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006570 status_t ret = NAME_NOT_FOUND;
6571
6572 Mutex::Autolock _l(mLock);
6573
6574 for (size_t i = 0; i < mTracks.size(); i++) {
6575 sp<RecordTrack> track = mTracks[i];
6576 if (eventSession == track->sessionId()) {
6577 (void) track->setSyncEvent(event);
6578 ret = NO_ERROR;
6579 }
6580 }
6581 return ret;
6582#else
6583 return BAD_VALUE;
6584#endif
6585}
6586
6587// destroyTrack_l() must be called with ThreadBase::mLock held
6588void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6589{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006590 track->terminate();
6591 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006592 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006593 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006594 removeTrack_l(track);
6595 }
6596}
6597
6598void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6599{
6600 mTracks.remove(track);
6601 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006602 if (track->isFastTrack()) {
6603 ALOG_ASSERT(!mFastTrackAvail);
6604 mFastTrackAvail = true;
6605 }
Eric Laurent81784c32012-11-19 14:55:58 -08006606}
6607
6608void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6609{
6610 dumpInternals(fd, args);
6611 dumpTracks(fd, args);
6612 dumpEffectChains(fd, args);
6613}
6614
6615void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6616{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006617 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006618
Glenn Kasten44182c22015-03-05 17:12:23 -08006619 dumpBase(fd, args);
6620
6621 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006622 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006623 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006624 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006625 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006626
Glenn Kasten2f90c512015-12-02 11:40:09 -08006627 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6628 // while we are dumping it. It may be inconsistent, but it won't mutate!
6629 // This is a large object so we place it on the heap.
6630 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6631 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6632 copy->dump(fd);
6633 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006634}
6635
Glenn Kasten0f11b512014-01-31 16:18:54 -08006636void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006637{
6638 const size_t SIZE = 256;
6639 char buffer[SIZE];
6640 String8 result;
6641
Marco Nelissenb2208842014-02-07 14:00:50 -08006642 size_t numtracks = mTracks.size();
6643 size_t numactive = mActiveTracks.size();
6644 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006645 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006646 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006647 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006648 RecordTrack::appendDumpHeader(result);
6649 for (size_t i = 0; i < numtracks ; ++i) {
6650 sp<RecordTrack> track = mTracks[i];
6651 if (track != 0) {
6652 bool active = mActiveTracks.indexOf(track) >= 0;
6653 if (active) {
6654 numactiveseen++;
6655 }
6656 track->dump(buffer, SIZE, active);
6657 result.append(buffer);
6658 }
Eric Laurent81784c32012-11-19 14:55:58 -08006659 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006660 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006661 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006662 }
6663
Marco Nelissenb2208842014-02-07 14:00:50 -08006664 if (numactiveseen != numactive) {
6665 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6666 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006667 result.append(buffer);
6668 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006669 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006670 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006671 if (mTracks.indexOf(track) < 0) {
6672 track->dump(buffer, SIZE, true);
6673 result.append(buffer);
6674 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006675 }
Eric Laurent81784c32012-11-19 14:55:58 -08006676
6677 }
6678 write(fd, result.string(), result.size());
6679}
6680
Andy Hung73c02e42015-03-29 01:13:58 -07006681
6682void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6683{
6684 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6685 RecordThread *recordThread = (RecordThread *) threadBase.get();
6686 mRsmpInFront = recordThread->mRsmpInRear;
6687 mRsmpInUnrel = 0;
6688}
6689
6690void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6691 size_t *framesAvailable, bool *hasOverrun)
6692{
6693 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6694 RecordThread *recordThread = (RecordThread *) threadBase.get();
6695 const int32_t rear = recordThread->mRsmpInRear;
6696 const int32_t front = mRsmpInFront;
6697 const ssize_t filled = rear - front;
6698
6699 size_t framesIn;
6700 bool overrun = false;
6701 if (filled < 0) {
6702 // should not happen, but treat like a massive overrun and re-sync
6703 framesIn = 0;
6704 mRsmpInFront = rear;
6705 overrun = true;
6706 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6707 framesIn = (size_t) filled;
6708 } else {
6709 // client is not keeping up with server, but give it latest data
6710 framesIn = recordThread->mRsmpInFrames;
6711 mRsmpInFront = /* front = */ rear - framesIn;
6712 overrun = true;
6713 }
6714 if (framesAvailable != NULL) {
6715 *framesAvailable = framesIn;
6716 }
6717 if (hasOverrun != NULL) {
6718 *hasOverrun = overrun;
6719 }
6720}
6721
Eric Laurent81784c32012-11-19 14:55:58 -08006722// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006723status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006724 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006725{
Andy Hung73c02e42015-03-29 01:13:58 -07006726 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006727 if (threadBase == 0) {
6728 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006729 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006730 return NOT_ENOUGH_DATA;
6731 }
6732 RecordThread *recordThread = (RecordThread *) threadBase.get();
6733 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006734 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006735 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006736 // FIXME should not be P2 (don't want to increase latency)
6737 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006738 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006739 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006740 front &= recordThread->mRsmpInFramesP2 - 1;
6741 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006742 if (part1 > (size_t) filled) {
6743 part1 = filled;
6744 }
6745 size_t ask = buffer->frameCount;
6746 ALOG_ASSERT(ask > 0);
6747 if (part1 > ask) {
6748 part1 = ask;
6749 }
6750 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006751 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006752 buffer->raw = NULL;
6753 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006754 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006755 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006756 }
6757
Andy Hung57446612015-04-19 23:56:46 -07006758 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006759 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006760 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006761 return NO_ERROR;
6762}
6763
6764// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006765void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6766 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006767{
Glenn Kasten85948432013-08-19 12:09:05 -07006768 size_t stepCount = buffer->frameCount;
6769 if (stepCount == 0) {
6770 return;
6771 }
Andy Hung73c02e42015-03-29 01:13:58 -07006772 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6773 mRsmpInUnrel -= stepCount;
6774 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006775 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006776 buffer->frameCount = 0;
6777}
6778
Andy Hung97a893e2015-03-29 01:03:07 -07006779AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6780 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6781 uint32_t srcSampleRate,
6782 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6783 uint32_t dstSampleRate) :
6784 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6785 // mSrcFormat
6786 // mSrcSampleRate
6787 // mDstChannelMask
6788 // mDstFormat
6789 // mDstSampleRate
6790 // mSrcChannelCount
6791 // mDstChannelCount
6792 // mDstFrameSize
6793 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006794 mResampler(NULL),
6795 mIsLegacyDownmix(false),
6796 mIsLegacyUpmix(false),
6797 mRequiresFloat(false),
6798 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006799{
6800 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6801 dstChannelMask, dstFormat, dstSampleRate);
6802}
6803
6804AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6805 free(mBuf);
6806 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006807 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006808}
6809
6810size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6811 AudioBufferProvider *provider, size_t frames)
6812{
Andy Hungd330ee42015-04-20 13:23:41 -07006813 if (mInputConverterProvider != NULL) {
6814 mInputConverterProvider->setBufferProvider(provider);
6815 provider = mInputConverterProvider;
6816 }
6817
6818 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006819 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6820 mSrcSampleRate, mSrcFormat, mDstFormat);
6821
6822 AudioBufferProvider::Buffer buffer;
6823 for (size_t i = frames; i > 0; ) {
6824 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006825 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006826 if (status != OK || buffer.frameCount == 0) {
6827 frames -= i; // cannot fill request.
6828 break;
6829 }
Andy Hungd330ee42015-04-20 13:23:41 -07006830 // format convert to destination buffer
6831 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006832
6833 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6834 i -= buffer.frameCount;
6835 provider->releaseBuffer(&buffer);
6836 }
6837 } else {
6838 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6839 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6840
Andy Hungd330ee42015-04-20 13:23:41 -07006841 // reallocate buffer if needed
6842 if (mBufFrameSize != 0 && mBufFrames < frames) {
6843 free(mBuf);
6844 mBufFrames = frames;
6845 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6846 }
Andy Hung97a893e2015-03-29 01:03:07 -07006847 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006848 memset(mBuf, 0, frames * mBufFrameSize);
6849 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6850 // format convert to destination buffer
6851 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006852 }
6853 return frames;
6854}
6855
6856status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6857 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6858 uint32_t srcSampleRate,
6859 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6860 uint32_t dstSampleRate)
6861{
6862 // quick evaluation if there is any change.
6863 if (mSrcFormat == srcFormat
6864 && mSrcChannelMask == srcChannelMask
6865 && mSrcSampleRate == srcSampleRate
6866 && mDstFormat == dstFormat
6867 && mDstChannelMask == dstChannelMask
6868 && mDstSampleRate == dstSampleRate) {
6869 return NO_ERROR;
6870 }
6871
Andy Hungdb4c0312015-05-06 08:46:52 -07006872 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6873 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6874 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006875 const bool valid =
6876 audio_is_input_channel(srcChannelMask)
6877 && audio_is_input_channel(dstChannelMask)
6878 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6879 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6880 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6881 ; // no upsampling checks for now
6882 if (!valid) {
6883 return BAD_VALUE;
6884 }
6885
6886 mSrcFormat = srcFormat;
6887 mSrcChannelMask = srcChannelMask;
6888 mSrcSampleRate = srcSampleRate;
6889 mDstFormat = dstFormat;
6890 mDstChannelMask = dstChannelMask;
6891 mDstSampleRate = dstSampleRate;
6892
6893 // compute derived parameters
6894 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6895 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6896 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6897
Andy Hungd330ee42015-04-20 13:23:41 -07006898 // do we need to resample?
6899 delete mResampler;
6900 mResampler = NULL;
6901 if (mSrcSampleRate != mDstSampleRate) {
6902 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6903 mSrcChannelCount, mDstSampleRate);
6904 mResampler->setSampleRate(mSrcSampleRate);
6905 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6906 }
6907
6908 // are we running legacy channel conversion modes?
6909 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6910 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6911 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6912 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6913 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6914 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6915
6916 // do we need to process in float?
6917 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6918
6919 // do we need a staging buffer to convert for destination (we can still optimize this)?
6920 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6921 if (mResampler != NULL) {
6922 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6923 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006924 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006925 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6926 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006927 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6928 } else {
6929 mBufFrameSize = 0;
6930 }
6931 mBufFrames = 0; // force the buffer to be resized.
6932
Andy Hungd330ee42015-04-20 13:23:41 -07006933 // do we need an input converter buffer provider to give us float?
6934 delete mInputConverterProvider;
6935 mInputConverterProvider = NULL;
6936 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6937 mInputConverterProvider = new ReformatBufferProvider(
6938 audio_channel_count_from_in_mask(mSrcChannelMask),
6939 mSrcFormat,
6940 AUDIO_FORMAT_PCM_FLOAT,
6941 256 /* provider buffer frame count */);
6942 }
6943
6944 // do we need a remixer to do channel mask conversion
6945 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6946 (void) memcpy_by_index_array_initialization_from_channel_mask(
6947 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006948 }
6949 return NO_ERROR;
6950}
6951
Andy Hungd330ee42015-04-20 13:23:41 -07006952void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6953 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006954{
Andy Hungd330ee42015-04-20 13:23:41 -07006955 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006956 if (mBufFrameSize != 0 && mBufFrames < frames) {
6957 free(mBuf);
6958 mBufFrames = frames;
6959 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6960 }
Andy Hungd330ee42015-04-20 13:23:41 -07006961 // do we need to do legacy upmix and downmix?
6962 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006963 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006964 if (mIsLegacyUpmix) {
6965 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6966 (const float *)src, frames);
6967 } else /*mIsLegacyDownmix */ {
6968 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6969 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006970 }
Andy Hungd330ee42015-04-20 13:23:41 -07006971 if (mBuf != NULL) {
6972 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6973 frames * mDstChannelCount);
6974 }
6975 return;
6976 }
6977 // do we need to do channel mask conversion?
6978 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006979 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006980 memcpy_by_index_array(dstBuf, mDstChannelCount,
6981 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6982 if (dstBuf == dst) {
6983 return; // format is the same
6984 }
6985 }
6986 // convert to destination buffer
6987 const void *convertBuf = mBuf != NULL ? mBuf : src;
6988 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6989 frames * mDstChannelCount);
6990}
6991
6992void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6993 void *dst, /*not-a-const*/ void *src, size_t frames)
6994{
6995 // src buffer format is ALWAYS float when entering this routine
6996 if (mIsLegacyUpmix) {
6997 ; // mono to stereo already handled by resampler
6998 } else if (mIsLegacyDownmix
6999 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7000 // the resampler outputs stereo for mono input channel (a feature?)
7001 // must convert to mono
7002 downmix_to_mono_float_from_stereo_float((float *)src,
7003 (const float *)src, frames);
7004 } else if (mSrcChannelMask != mDstChannelMask) {
7005 // convert to mono channel again for channel mask conversion (could be skipped
7006 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007007 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007008 downmix_to_mono_float_from_stereo_float((float *)src,
7009 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007010 }
Andy Hungd330ee42015-04-20 13:23:41 -07007011 // convert to destination format (in place, OK as float is larger than other types)
7012 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7013 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7014 frames * mSrcChannelCount);
7015 }
7016 // channel convert and save to dst
7017 memcpy_by_index_array(dst, mDstChannelCount,
7018 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7019 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007020 }
Andy Hungd330ee42015-04-20 13:23:41 -07007021 // convert to destination format and save to dst
7022 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7023 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007024}
7025
Eric Laurent10351942014-05-08 18:49:52 -07007026bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7027 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007028{
7029 bool reconfig = false;
7030
Eric Laurent10351942014-05-08 18:49:52 -07007031 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007032
Eric Laurent10351942014-05-08 18:49:52 -07007033 audio_format_t reqFormat = mFormat;
7034 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007035 // 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 -07007036 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7037
7038 AudioParameter param = AudioParameter(keyValuePair);
7039 int value;
7040 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7041 // channel count change can be requested. Do we mandate the first client defines the
7042 // HAL sampling rate and channel count or do we allow changes on the fly?
7043 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7044 samplingRate = value;
7045 reconfig = true;
7046 }
7047 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007048 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007049 status = BAD_VALUE;
7050 } else {
7051 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007052 reconfig = true;
7053 }
Eric Laurent10351942014-05-08 18:49:52 -07007054 }
7055 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7056 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007057 if (!audio_is_input_channel(mask) ||
7058 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007059 status = BAD_VALUE;
7060 } else {
7061 channelMask = mask;
7062 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007063 }
Eric Laurent10351942014-05-08 18:49:52 -07007064 }
7065 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7066 // do not accept frame count changes if tracks are open as the track buffer
7067 // size depends on frame count and correct behavior would not be guaranteed
7068 // if frame count is changed after track creation
7069 if (mActiveTracks.size() > 0) {
7070 status = INVALID_OPERATION;
7071 } else {
7072 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007073 }
Eric Laurent10351942014-05-08 18:49:52 -07007074 }
7075 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7076 // forward device change to effects that have requested to be
7077 // aware of attached audio device.
7078 for (size_t i = 0; i < mEffectChains.size(); i++) {
7079 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007080 }
Eric Laurent81784c32012-11-19 14:55:58 -08007081
Eric Laurent10351942014-05-08 18:49:52 -07007082 // store input device and output device but do not forward output device to audio HAL.
7083 // Note that status is ignored by the caller for output device
7084 // (see AudioFlinger::setParameters()
7085 if (audio_is_output_devices(value)) {
7086 mOutDevice = value;
7087 status = BAD_VALUE;
7088 } else {
7089 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007090 if (value != AUDIO_DEVICE_NONE) {
7091 mPrevInDevice = value;
7092 }
Eric Laurent10351942014-05-08 18:49:52 -07007093 // disable AEC and NS if the device is a BT SCO headset supporting those
7094 // pre processings
7095 if (mTracks.size() > 0) {
7096 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7097 mAudioFlinger->btNrecIsOff();
7098 for (size_t i = 0; i < mTracks.size(); i++) {
7099 sp<RecordTrack> track = mTracks[i];
7100 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7101 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007102 }
7103 }
7104 }
Eric Laurent10351942014-05-08 18:49:52 -07007105 }
7106 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7107 mAudioSource != (audio_source_t)value) {
7108 // forward device change to effects that have requested to be
7109 // aware of attached audio device.
7110 for (size_t i = 0; i < mEffectChains.size(); i++) {
7111 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007112 }
Eric Laurent10351942014-05-08 18:49:52 -07007113 mAudioSource = (audio_source_t)value;
7114 }
Glenn Kastene198c362013-08-13 09:13:36 -07007115
Eric Laurent10351942014-05-08 18:49:52 -07007116 if (status == NO_ERROR) {
7117 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7118 keyValuePair.string());
7119 if (status == INVALID_OPERATION) {
7120 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007121 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7122 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07007123 }
7124 if (reconfig) {
7125 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07007126 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
7127 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07007128 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07007129 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07007130 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07007131 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007132 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007133 }
Eric Laurent10351942014-05-08 18:49:52 -07007134 if (status == NO_ERROR) {
7135 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007136 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007137 }
7138 }
Eric Laurent81784c32012-11-19 14:55:58 -08007139 }
Eric Laurent10351942014-05-08 18:49:52 -07007140
Eric Laurent81784c32012-11-19 14:55:58 -08007141 return reconfig;
7142}
7143
7144String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7145{
Eric Laurent81784c32012-11-19 14:55:58 -08007146 Mutex::Autolock _l(mLock);
7147 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07007148 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007149 }
7150
Glenn Kastend8ea6992013-07-16 14:17:15 -07007151 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
7152 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08007153 free(s);
7154 return out_s8;
7155}
7156
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007157void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007158 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7159
7160 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007161
7162 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007163 case AUDIO_INPUT_OPENED:
7164 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007165 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007166 desc->mChannelMask = mChannelMask;
7167 desc->mSamplingRate = mSampleRate;
7168 desc->mFormat = mFormat;
7169 desc->mFrameCount = mFrameCount;
7170 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007171 break;
7172
Eric Laurent73e26b62015-04-27 16:55:58 -07007173 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007174 default:
7175 break;
7176 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007177 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007178}
7179
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007180void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007181{
Eric Laurent81784c32012-11-19 14:55:58 -08007182 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
7183 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07007184 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07007185 if (mChannelCount > FCC_8) {
7186 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
7187 }
Andy Hung463be252014-07-10 16:56:07 -07007188 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
7189 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07007190 if (!audio_is_linear_pcm(mFormat)) {
7191 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07007192 }
Eric Laurent665470b2014-07-03 16:37:08 -07007193 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08007194 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7195 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007196 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007197 // 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 -07007198 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007199 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007200 // A larger value should allow more old data to be read after a track calls start(),
7201 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007202 //
7203 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007204 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007205 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007206 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007207 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007208
7209 // TODO optimize audio capture buffer sizes ...
7210 // Here we calculate the size of the sliding buffer used as a source
7211 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7212 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7213 // be better to have it derived from the pipe depth in the long term.
7214 // The current value is higher than necessary. However it should not add to latency.
7215
Glenn Kasten85948432013-08-19 12:09:05 -07007216 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07007217 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7218 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7219 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007220
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007221 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7222 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007223}
7224
Glenn Kasten5f972c02014-01-13 09:59:31 -08007225uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007226{
7227 Mutex::Autolock _l(mLock);
7228 if (initCheck() != NO_ERROR) {
7229 return 0;
7230 }
7231
7232 return mInput->stream->get_input_frames_lost(mInput->stream);
7233}
7234
Glenn Kastend848eb42016-03-08 13:42:11 -08007235uint32_t AudioFlinger::RecordThread::hasAudioSession(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007236{
7237 Mutex::Autolock _l(mLock);
7238 uint32_t result = 0;
7239 if (getEffectChain_l(sessionId) != 0) {
7240 result = EFFECT_SESSION;
7241 }
7242
7243 for (size_t i = 0; i < mTracks.size(); ++i) {
7244 if (sessionId == mTracks[i]->sessionId()) {
7245 result |= TRACK_SESSION;
7246 break;
7247 }
7248 }
7249
7250 return result;
7251}
7252
Glenn Kastend848eb42016-03-08 13:42:11 -08007253KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007254{
Glenn Kastend848eb42016-03-08 13:42:11 -08007255 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007256 Mutex::Autolock _l(mLock);
7257 for (size_t j = 0; j < mTracks.size(); ++j) {
7258 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007259 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007260 if (ids.indexOfKey(sessionId) < 0) {
7261 ids.add(sessionId, true);
7262 }
7263 }
7264 return ids;
7265}
7266
7267AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7268{
7269 Mutex::Autolock _l(mLock);
7270 AudioStreamIn *input = mInput;
7271 mInput = NULL;
7272 return input;
7273}
7274
7275// this method must always be called either with ThreadBase mLock held or inside the thread loop
7276audio_stream_t* AudioFlinger::RecordThread::stream() const
7277{
7278 if (mInput == NULL) {
7279 return NULL;
7280 }
7281 return &mInput->stream->common;
7282}
7283
7284status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7285{
7286 // only one chain per input thread
7287 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007288 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007289 return INVALID_OPERATION;
7290 }
7291 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007292 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007293 chain->setInBuffer(NULL);
7294 chain->setOutBuffer(NULL);
7295
7296 checkSuspendOnAddEffectChain_l(chain);
7297
Eric Laurent1b928682014-10-02 19:41:47 -07007298 // make sure enabled pre processing effects state is communicated to the HAL as we
7299 // just moved them to a new input stream.
7300 chain->syncHalEffectsState();
7301
Eric Laurent81784c32012-11-19 14:55:58 -08007302 mEffectChains.add(chain);
7303
7304 return NO_ERROR;
7305}
7306
7307size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7308{
7309 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7310 ALOGW_IF(mEffectChains.size() != 1,
7311 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7312 chain.get(), mEffectChains.size(), this);
7313 if (mEffectChains.size() == 1) {
7314 mEffectChains.removeAt(0);
7315 }
7316 return 0;
7317}
7318
Eric Laurent1c333e22014-05-20 10:48:17 -07007319status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7320 audio_patch_handle_t *handle)
7321{
7322 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007323
7324 // store new device and send to effects
7325 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007326 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007327 for (size_t i = 0; i < mEffectChains.size(); i++) {
7328 mEffectChains[i]->setDevice_l(mInDevice);
7329 }
7330
7331 // disable AEC and NS if the device is a BT SCO headset supporting those
7332 // pre processings
7333 if (mTracks.size() > 0) {
7334 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7335 mAudioFlinger->btNrecIsOff();
7336 for (size_t i = 0; i < mTracks.size(); i++) {
7337 sp<RecordTrack> track = mTracks[i];
7338 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7339 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7340 }
7341 }
7342
7343 // store new source and send to effects
7344 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7345 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007346 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007347 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007348 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007349 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007350
Eric Laurent054d9d32015-04-24 08:48:48 -07007351 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007352 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7353 status = hwDevice->create_audio_patch(hwDevice,
7354 patch->num_sources,
7355 patch->sources,
7356 patch->num_sinks,
7357 patch->sinks,
7358 handle);
7359 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007360 char *address;
7361 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7362 address = audio_device_address_to_parameter(
7363 patch->sources[0].ext.device.type,
7364 patch->sources[0].ext.device.address);
7365 } else {
7366 address = (char *)calloc(1, 1);
7367 }
7368 AudioParameter param = AudioParameter(String8(address));
7369 free(address);
7370 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7371 (int)patch->sources[0].ext.device.type);
7372 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7373 (int)patch->sinks[0].ext.mix.usecase.source);
7374 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7375 param.toString().string());
7376 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007377 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007378
Eric Laurente8726fe2015-06-26 09:39:24 -07007379 if (mInDevice != mPrevInDevice) {
7380 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7381 mPrevInDevice = mInDevice;
7382 }
Eric Laurent296fb132015-05-01 11:38:42 -07007383
Eric Laurent1c333e22014-05-20 10:48:17 -07007384 return status;
7385}
7386
7387status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7388{
7389 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007390
7391 mInDevice = AUDIO_DEVICE_NONE;
7392
Eric Laurent1c333e22014-05-20 10:48:17 -07007393 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7394 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7395 status = hwDevice->release_audio_patch(hwDevice, handle);
7396 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007397 AudioParameter param;
7398 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7399 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7400 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007401 }
7402 return status;
7403}
7404
Eric Laurent83b88082014-06-20 18:31:16 -07007405void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7406{
7407 Mutex::Autolock _l(mLock);
7408 mTracks.add(record);
7409}
7410
7411void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7412{
7413 Mutex::Autolock _l(mLock);
7414 destroyTrack_l(record);
7415}
7416
7417void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7418{
7419 ThreadBase::getAudioPortConfig(config);
7420 config->role = AUDIO_PORT_ROLE_SINK;
7421 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7422 config->ext.mix.usecase.source = mAudioSource;
7423}
Eric Laurent1c333e22014-05-20 10:48:17 -07007424
Glenn Kasten63238ef2015-03-02 15:50:29 -08007425} // namespace android