blob: 401a19ec07a8aa1fbe801e43d879fac3ab477799 [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>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <memory>
Andy Hungb68f5eb2019-12-03 16:49:17 -080027#include <sstream>
Eric Tan7b651152018-07-13 10:17:19 -070028#include <string>
Glenn Kastenad8510a2015-02-17 16:24:07 -080029#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080030#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080031#include <sys/syscall.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070032#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080033#include <cutils/properties.h>
jiabinc52b1ff2019-10-31 17:20:42 -070034#include <media/AudioContainers.h>
35#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070036#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070037#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080038#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070039#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080041#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070044#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010045#include <audio_utils/Balance.h>
jiabinf6eb4c32020-02-25 14:06:25 -080046#include <audio_utils/Metadata.h>
jiabin245cdd92018-12-07 17:55:15 -080047#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080048#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080049#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080050#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070051#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070052#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070053#include <system/audio_effects/effect_aec.h>
Eric Laurentb3f315a2021-07-13 15:09:05 +020054#include <system/audio_effects/effect_downmix.h>
55#include <system/audio_effects/effect_ns.h>
Eric Laurent1c5e2e32021-08-18 18:50:28 +020056#include <system/audio_effects/effect_spatializer.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070057#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080058
59// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080061#include <media/nbaio/AudioStreamOutSink.h>
62#include <media/nbaio/MonoPipe.h>
63#include <media/nbaio/MonoPipeReader.h>
64#include <media/nbaio/Pipe.h>
65#include <media/nbaio/PipeReader.h>
66#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080067#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070068#include <mediautils/Process.h>
Eric Laurent81784c32012-11-19 14:55:58 -080069
Mikhail Naganov2996f672019-04-18 12:29:59 -070070#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080071#include <powermanager/PowerManager.h>
72
Kevin Rocard7588ff42018-01-08 11:11:30 -080073#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070074#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080075
Eric Laurent81784c32012-11-19 14:55:58 -080076#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080077#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070078#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070079#include <mediautils/SchedulingPolicyService.h>
80#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080081
Eric Laurent81784c32012-11-19 14:55:58 -080082#ifdef ADD_BATTERY_DATA
83#include <media/IMediaPlayerService.h>
84#include <media/IMediaDeathNotifier.h>
85#endif
86
Eric Laurent81784c32012-11-19 14:55:58 -080087#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070088#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080089#include <cpustats/ThreadCpuUsage.h>
90#endif
91
Glenn Kastenc05b8d72016-03-24 09:48:17 -070092#include "AutoPark.h"
93
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080094#include <pthread.h>
95#include "TypedLogger.h"
96
Eric Laurent81784c32012-11-19 14:55:58 -080097// ----------------------------------------------------------------------------
98
99// Note: the following macro is used for extremely verbose logging message. In
100// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
101// 0; but one side effect of this is to turn all LOGV's as well. Some messages
102// are so verbose that we want to suppress them even when we have ALOG_ASSERT
103// turned on. Do not uncomment the #def below unless you really know what you
104// are doing and want to see all of the extremely verbose messages.
105//#define VERY_VERY_VERBOSE_LOGGING
106#ifdef VERY_VERY_VERBOSE_LOGGING
107#define ALOGVV ALOGV
108#else
109#define ALOGVV(a...) do { } while(0)
110#endif
111
Andy Hung6770c6f2015-04-07 13:43:36 -0700112// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700113#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700114
Andy Hung6770c6f2015-04-07 13:43:36 -0700115template <typename T>
116static inline T min(const T& a, const T& b)
117{
118 return a < b ? a : b;
119}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700120
Eric Laurent81784c32012-11-19 14:55:58 -0800121namespace android {
122
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700123using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000124using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700125
Eric Laurent81784c32012-11-19 14:55:58 -0800126// retry counts for buffer fill timeout
127// 50 * ~20msecs = 1 second
128static const int8_t kMaxTrackRetries = 50;
129static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700130
Eric Laurent81784c32012-11-19 14:55:58 -0800131// allow less retry attempts on direct output thread.
132// direct outputs can be a scarce resource in audio hardware and should
133// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700134// Notes:
135// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
136// in case the data write is bursty for the AudioTrack. The application
137// should endeavor to write at least once every kMaxTrackRetriesDirectMs
138// to prevent an underrun situation. If the data is bursty, then
139// the application can also throttle the data sent to be even.
140// 2) For compressed audio data, any data present in the AudioTrack buffer
141// will be sent and reset the retry count. This delivers data as
142// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
143// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
144// of data to be available, then any remaining data is delivered.
145// This is required to ensure the last bit of data is delivered before underrun.
146//
147// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
148// or the size of the HAL period for proportional / linear PCM tracks.
149static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800150
151// don't warn about blocked writes or record buffer overflows more often than this
152static const nsecs_t kWarningThrottleNs = seconds(5);
153
154// RecordThread loop sleep time upon application overrun or audio HAL read error
155static const int kRecordThreadSleepUs = 5000;
156
Eric Laurent10351942014-05-08 18:49:52 -0700157// maximum time to wait in sendConfigEvent_l() for a status to be received
158static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800159
160// minimum sleep time for the mixer thread loop when tracks are active but in underrun
161static const uint32_t kMinThreadSleepTimeUs = 5000;
162// maximum divider applied to the active sleep time in the mixer thread loop
163static const uint32_t kMaxThreadSleepTimeShift = 2;
164
Andy Hung09a50072014-02-27 14:30:47 -0800165// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700166// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800167static const uint32_t kMinNormalSinkBufferSizeMs = 20;
168// maximum normal sink buffer size
169static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800170
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700171// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
172// FIXME This should be based on experimentally observed scheduling jitter
173static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
174
Eric Laurent972a1732013-09-04 09:42:59 -0700175// Offloaded output thread standby delay: allows track transition without going to standby
176static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
177
Eric Laurent51716182016-02-29 18:00:56 -0800178// Direct output thread minimum sleep time in idle or active(underrun) state
179static const nsecs_t kDirectMinSleepTimeUs = 10000;
180
Brian Lindahl65e90012022-07-27 18:01:07 +0200181// Minimum amount of time between checking to see if the timestamp is advancing
182// for underrun detection. If we check too frequently, we may not detect a
183// timestamp update and will falsely detect underrun.
184static const nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1000;
185
Glenn Kasten1b291842016-07-18 14:55:21 -0700186// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
187// balance between power consumption and latency, and allows threads to be scheduled reliably
188// by the CFS scheduler.
189// FIXME Express other hardcoded references to 20ms with references to this constant and move
190// it appropriately.
191#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800192
Eric Laurent81784c32012-11-19 14:55:58 -0800193// Whether to use fast mixer
194static const enum {
195 FastMixer_Never, // never initialize or use: for debugging only
196 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
197 // normal mixer multiplier is 1
198 FastMixer_Static, // initialize if needed, then use all the time if initialized,
199 // multiplier is calculated based on min & max normal mixer buffer size
200 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
201 // multiplier is calculated based on min & max normal mixer buffer size
202 // FIXME for FastMixer_Dynamic:
203 // Supporting this option will require fixing HALs that can't handle large writes.
204 // For example, one HAL implementation returns an error from a large write,
205 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
206 // We could either fix the HAL implementations, or provide a wrapper that breaks
207 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
208} kUseFastMixer = FastMixer_Static;
209
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700210// Whether to use fast capture
211static const enum {
212 FastCapture_Never, // never initialize or use: for debugging only
213 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
214 FastCapture_Static, // initialize if needed, then use all the time if initialized
215} kUseFastCapture = FastCapture_Static;
216
Eric Laurent81784c32012-11-19 14:55:58 -0800217// Priorities for requestPriority
218static const int kPriorityAudioApp = 2;
219static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700220static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800221
Glenn Kastenea38ee72016-04-18 11:08:01 -0700222// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
223// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
224// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700225
226// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800227static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800228
Glenn Kasten03490092014-05-27 12:30:54 -0700229// The minimum and maximum allowed values
230static const int kFastTrackMultiplierMin = 1;
231static const int kFastTrackMultiplierMax = 2;
232
233// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
234static int sFastTrackMultiplier = kFastTrackMultiplier;
235
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700236// See Thread::readOnlyHeap().
237// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
238// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
239// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700240static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700241
Eric Laurent81784c32012-11-19 14:55:58 -0800242// ----------------------------------------------------------------------------
243
Andy Hungb68f5eb2019-12-03 16:49:17 -0800244// TODO: move all toString helpers to audio.h
245// under #ifdef __cplusplus #endif
246static std::string patchSinksToString(const struct audio_patch *patch)
247{
248 std::stringstream ss;
249 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700250 if (i > 0) {
251 ss << "|";
252 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800253 ss << "(" << toString(patch->sinks[i].ext.device.type)
254 << ", " << patch->sinks[i].ext.device.address << ")";
255 }
256 return ss.str();
257}
258
259static std::string patchSourcesToString(const struct audio_patch *patch)
260{
261 std::stringstream ss;
262 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700263 if (i > 0) {
264 ss << "|";
265 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800266 ss << "(" << toString(patch->sources[i].ext.device.type)
267 << ", " << patch->sources[i].ext.device.address << ")";
268 }
269 return ss.str();
270}
271
Glenn Kasten03490092014-05-27 12:30:54 -0700272static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
273
274static void sFastTrackMultiplierInit()
275{
276 char value[PROPERTY_VALUE_MAX];
277 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
278 char *endptr;
279 unsigned long ul = strtoul(value, &endptr, 0);
280 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
281 sFastTrackMultiplier = (int) ul;
282 }
283 }
284}
285
286// ----------------------------------------------------------------------------
287
Eric Laurent81784c32012-11-19 14:55:58 -0800288#ifdef ADD_BATTERY_DATA
289// To collect the amplifier usage
290static void addBatteryData(uint32_t params) {
291 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
292 if (service == NULL) {
293 // it already logged
294 return;
295 }
296
297 service->addBatteryData(params);
298}
299#endif
300
Andy Hung3f0c9022016-01-15 17:49:46 -0800301// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
302struct {
303 // call when you acquire a partial wakelock
304 void acquire(const sp<IBinder> &wakeLockToken) {
305 pthread_mutex_lock(&mLock);
306 if (wakeLockToken.get() == nullptr) {
307 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
308 } else {
309 if (mCount == 0) {
310 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
311 }
312 ++mCount;
313 }
314 pthread_mutex_unlock(&mLock);
315 }
316
317 // call when you release a partial wakelock.
318 void release(const sp<IBinder> &wakeLockToken) {
319 if (wakeLockToken.get() == nullptr) {
320 return;
321 }
322 pthread_mutex_lock(&mLock);
323 if (--mCount < 0) {
324 ALOGE("negative wakelock count");
325 mCount = 0;
326 }
327 pthread_mutex_unlock(&mLock);
328 }
329
330 // retrieves the boottime timebase offset from monotonic.
331 int64_t getBoottimeOffset() {
332 pthread_mutex_lock(&mLock);
333 int64_t boottimeOffset = mBoottimeOffset;
334 pthread_mutex_unlock(&mLock);
335 return boottimeOffset;
336 }
337
338 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
339 // and the selected timebase.
340 // Currently only TIMEBASE_BOOTTIME is allowed.
341 //
342 // This only needs to be called upon acquiring the first partial wakelock
343 // after all other partial wakelocks are released.
344 //
345 // We do an empirical measurement of the offset rather than parsing
346 // /proc/timer_list since the latter is not a formal kernel ABI.
347 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
348 int clockbase;
349 switch (timebase) {
350 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
351 clockbase = SYSTEM_TIME_BOOTTIME;
352 break;
353 default:
354 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
355 break;
356 }
357 // try three times to get the clock offset, choose the one
358 // with the minimum gap in measurements.
359 const int tries = 3;
360 nsecs_t bestGap, measured;
361 for (int i = 0; i < tries; ++i) {
362 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
363 const nsecs_t tbase = systemTime(clockbase);
364 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
365 const nsecs_t gap = tmono2 - tmono;
366 if (i == 0 || gap < bestGap) {
367 bestGap = gap;
368 measured = tbase - ((tmono + tmono2) >> 1);
369 }
370 }
371
372 // to avoid micro-adjusting, we don't change the timebase
373 // unless it is significantly different.
374 //
375 // Assumption: It probably takes more than toleranceNs to
376 // suspend and resume the device.
377 static int64_t toleranceNs = 10000; // 10 us
378 if (llabs(*offset - measured) > toleranceNs) {
379 ALOGV("Adjusting timebase offset old: %lld new: %lld",
380 (long long)*offset, (long long)measured);
381 *offset = measured;
382 }
383 }
384
385 pthread_mutex_t mLock;
386 int32_t mCount;
387 int64_t mBoottimeOffset;
388} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800389
390// ----------------------------------------------------------------------------
391// CPU Stats
392// ----------------------------------------------------------------------------
393
394class CpuStats {
395public:
396 CpuStats();
397 void sample(const String8 &title);
398#ifdef DEBUG_CPU_USAGE
399private:
400 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700401 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800402
Andy Hung16698b82018-08-01 10:48:38 -0700403 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800404
405 int mCpuNum; // thread's current CPU number
406 int mCpukHz; // frequency of thread's current CPU in kHz
407#endif
408};
409
410CpuStats::CpuStats()
411#ifdef DEBUG_CPU_USAGE
412 : mCpuNum(-1), mCpukHz(-1)
413#endif
414{
415}
416
Glenn Kasten0f11b512014-01-31 16:18:54 -0800417void CpuStats::sample(const String8 &title
418#ifndef DEBUG_CPU_USAGE
419 __unused
420#endif
421 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800422#ifdef DEBUG_CPU_USAGE
423 // get current thread's delta CPU time in wall clock ns
424 double wcNs;
425 bool valid = mCpuUsage.sampleAndEnable(wcNs);
426
427 // record sample for wall clock statistics
428 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700429 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800430 }
431
432 // get the current CPU number
433 int cpuNum = sched_getcpu();
434
435 // get the current CPU frequency in kHz
436 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
437
438 // check if either CPU number or frequency changed
439 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
440 mCpuNum = cpuNum;
441 mCpukHz = cpukHz;
442 // ignore sample for purposes of cycles
443 valid = false;
444 }
445
446 // if no change in CPU number or frequency, then record sample for cycle statistics
447 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700448 const double cycles = wcNs * cpukHz * 0.000001;
449 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800450 }
451
Eric Tan5b13ff82018-07-27 11:20:17 -0700452 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800453 // mCpuUsage.elapsed() is expensive, so don't call it every loop
454 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700455 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800456 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700457 const double perLoop = elapsed / (double) n;
458 const double perLoop100 = perLoop * 0.01;
459 const double perLoop1k = perLoop * 0.001;
460 const double mean = mWcStats.getMean();
461 const double stddev = mWcStats.getStdDev();
462 const double minimum = mWcStats.getMin();
463 const double maximum = mWcStats.getMax();
464 const double meanCycles = mHzStats.getMean();
465 const double stddevCycles = mHzStats.getStdDev();
466 const double minCycles = mHzStats.getMin();
467 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800468 mCpuUsage.resetElapsed();
469 mWcStats.reset();
470 mHzStats.reset();
471 ALOGD("CPU usage for %s over past %.1f secs\n"
472 " (%u mixer loops at %.1f mean ms per loop):\n"
473 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
474 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
475 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
476 title.string(),
477 elapsed * .000000001, n, perLoop * .000001,
478 mean * .001,
479 stddev * .001,
480 minimum * .001,
481 maximum * .001,
482 mean / perLoop100,
483 stddev / perLoop100,
484 minimum / perLoop100,
485 maximum / perLoop100,
486 meanCycles / perLoop1k,
487 stddevCycles / perLoop1k,
488 minCycles / perLoop1k,
489 maxCycles / perLoop1k);
490
491 }
492 }
493#endif
494};
495
496// ----------------------------------------------------------------------------
497// ThreadBase
498// ----------------------------------------------------------------------------
499
Glenn Kasten97b7b752014-09-28 13:04:24 -0700500// static
501const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
502{
503 switch (type) {
504 case MIXER:
505 return "MIXER";
506 case DIRECT:
507 return "DIRECT";
508 case DUPLICATING:
509 return "DUPLICATING";
510 case RECORD:
511 return "RECORD";
512 case OFFLOAD:
513 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700514 case MMAP_PLAYBACK:
515 return "MMAP_PLAYBACK";
516 case MMAP_CAPTURE:
517 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200518 case SPATIALIZER:
519 return "SPATIALIZER";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700520 default:
521 return "unknown";
522 }
523}
524
Eric Laurent81784c32012-11-19 14:55:58 -0800525AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700526 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800527 : Thread(false /*canCallJava*/),
528 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700529 mAudioFlinger(audioFlinger),
Andy Hungcf10d742020-04-28 15:38:24 -0700530 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
531 isOut),
532 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700533 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800534 // are set by PlaybackThread::readOutputParameters_l() or
535 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700536 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700537 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700538 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800539 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700540 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800541 mSystemReady(systemReady),
542 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800543{
Andy Hungcf10d742020-04-28 15:38:24 -0700544 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700545 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800546}
547
548AudioFlinger::ThreadBase::~ThreadBase()
549{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700550 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700551 mConfigEvents.clear();
552
Eric Laurent81784c32012-11-19 14:55:58 -0800553 // do not lock the mutex in destructor
554 releaseWakeLock_l();
555 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800556 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800557 binder->unlinkToDeath(mDeathRecipient);
558 }
Andy Hungd0979812019-02-21 15:51:44 -0800559
560 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800561}
562
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700563status_t AudioFlinger::ThreadBase::readyToRun()
564{
565 status_t status = initCheck();
566 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800567 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700568 } else {
569 ALOGE("No working audio driver found.");
570 }
571 return status;
572}
573
Eric Laurent81784c32012-11-19 14:55:58 -0800574void AudioFlinger::ThreadBase::exit()
575{
576 ALOGV("ThreadBase::exit");
577 // do any cleanup required for exit to succeed
578 preExit();
579 {
580 // This lock prevents the following race in thread (uniprocessor for illustration):
581 // if (!exitPending()) {
582 // // context switch from here to exit()
583 // // exit() calls requestExit(), what exitPending() observes
584 // // exit() calls signal(), which is dropped since no waiters
585 // // context switch back from exit() to here
586 // mWaitWorkCV.wait(...);
587 // // now thread is hung
588 // }
589 AutoMutex lock(mLock);
590 requestExit();
591 mWaitWorkCV.broadcast();
592 }
593 // When Thread::requestExitAndWait is made virtual and this method is renamed to
594 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
595 requestExitAndWait();
596}
597
598status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
599{
Eric Laurent81784c32012-11-19 14:55:58 -0800600 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
601 Mutex::Autolock _l(mLock);
602
Eric Laurent10351942014-05-08 18:49:52 -0700603 return sendSetParameterConfigEvent_l(keyValuePairs);
604}
605
606// sendConfigEvent_l() must be called with ThreadBase::mLock held
607// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
608status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
609{
610 status_t status = NO_ERROR;
611
Eric Laurent72e3f392015-05-20 14:43:50 -0700612 if (event->mRequiresSystemReady && !mSystemReady) {
613 event->mWaitStatus = false;
614 mPendingConfigEvents.add(event);
615 return status;
616 }
Eric Laurent10351942014-05-08 18:49:52 -0700617 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700618 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800619 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700620 mLock.unlock();
621 {
622 Mutex::Autolock _l(event->mLock);
623 while (event->mWaitStatus) {
624 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
625 event->mStatus = TIMED_OUT;
626 event->mWaitStatus = false;
627 }
628 }
629 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800630 }
Eric Laurent10351942014-05-08 18:49:52 -0700631 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800632 return status;
633}
634
Mikhail Naganov88536df2021-07-26 17:30:29 -0700635void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700636 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800637{
638 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700639 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800640}
641
642// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov88536df2021-07-26 17:30:29 -0700643void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700644 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800645{
Andy Hungd0979812019-02-21 15:51:44 -0800646 // The audio statistics history is exponentially weighted to forget events
647 // about five or more seconds in the past. In order to have
648 // crisper statistics for mediametrics, we reset the statistics on
649 // an IoConfigEvent, to reflect different properties for a new device.
650 mIoJitterMs.reset();
651 mLatencyMs.reset();
652 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000653 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100654 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800655
Eric Laurent09f1ed22019-04-24 17:45:17 -0700656 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700657 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800658}
659
Mikhail Naganov83f04272017-02-07 10:45:09 -0800660void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700661{
662 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800663 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700664}
665
Eric Laurent81784c32012-11-19 14:55:58 -0800666// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800667void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
668 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800669{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800670 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700671 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800672}
673
Eric Laurent10351942014-05-08 18:49:52 -0700674// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
675status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800676{
Andy Hung2ddee192015-12-18 17:34:44 -0800677 sp<ConfigEvent> configEvent;
678 AudioParameter param(keyValuePair);
679 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700680 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800681 setMasterMono_l(value != 0);
682 if (param.size() == 1) {
683 return NO_ERROR; // should be a solo parameter - we don't pass down
684 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700685 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800686 configEvent = new SetParameterConfigEvent(param.toString());
687 } else {
688 configEvent = new SetParameterConfigEvent(keyValuePair);
689 }
Eric Laurent10351942014-05-08 18:49:52 -0700690 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700691}
692
Eric Laurent1c333e22014-05-20 10:48:17 -0700693status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
694 const struct audio_patch *patch,
695 audio_patch_handle_t *handle)
696{
697 Mutex::Autolock _l(mLock);
698 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
699 status_t status = sendConfigEvent_l(configEvent);
700 if (status == NO_ERROR) {
701 CreateAudioPatchConfigEventData *data =
702 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
703 *handle = data->mHandle;
704 }
705 return status;
706}
707
708status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
709 const audio_patch_handle_t handle)
710{
711 Mutex::Autolock _l(mLock);
712 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
713 return sendConfigEvent_l(configEvent);
714}
715
jiabinc52b1ff2019-10-31 17:20:42 -0700716status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
717 const DeviceDescriptorBaseVector& outDevices)
718{
719 if (type() != RECORD) {
720 // The update out device operation is only for record thread.
721 return INVALID_OPERATION;
722 }
723 Mutex::Autolock _l(mLock);
724 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
725 return sendConfigEvent_l(configEvent);
726}
727
Eric Laurentec376dc2021-04-08 20:41:22 +0200728void AudioFlinger::ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
729{
730 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
731 sp<ConfigEvent> configEvent =
732 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
733 sendConfigEvent_l(configEvent);
734}
Eric Laurent1c333e22014-05-20 10:48:17 -0700735
Eric Laurentb3f315a2021-07-13 15:09:05 +0200736void AudioFlinger::ThreadBase::sendCheckOutputStageEffectsEvent()
737{
738 Mutex::Autolock _l(mLock);
739 sendCheckOutputStageEffectsEvent_l();
740}
741
742void AudioFlinger::ThreadBase::sendCheckOutputStageEffectsEvent_l()
743{
744 sp<ConfigEvent> configEvent =
745 (ConfigEvent *)new CheckOutputStageEffectsEvent();
746 sendConfigEvent_l(configEvent);
747}
748
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700749// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700750void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700751{
Eric Laurent10351942014-05-08 18:49:52 -0700752 bool configChanged = false;
753
Eric Laurent81784c32012-11-19 14:55:58 -0800754 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700755 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700756 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800757 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700758 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700759 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700760 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
761 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800762 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700763 true /*asynchronous*/);
764 if (err != 0) {
765 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700766 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700767 }
768 } break;
769 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700770 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700771 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700772 } break;
773 case CFG_EVENT_SET_PARAMETER: {
774 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
775 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
776 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700777 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
778 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700779 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700780 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700781 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700782 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700783 CreateAudioPatchConfigEventData *data =
784 (CreateAudioPatchConfigEventData *)event->mData.get();
785 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700786 const DeviceTypeSet newDevices = getDeviceTypes();
787 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
788 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
789 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700790 } break;
791 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700792 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700793 ReleaseAudioPatchConfigEventData *data =
794 (ReleaseAudioPatchConfigEventData *)event->mData.get();
795 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700796 const DeviceTypeSet newDevices = getDeviceTypes();
797 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
798 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
799 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
800 } break;
801 case CFG_EVENT_UPDATE_OUT_DEVICE: {
802 UpdateOutDevicesConfigEventData *data =
803 (UpdateOutDevicesConfigEventData *)event->mData.get();
804 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700805 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200806 case CFG_EVENT_RESIZE_BUFFER: {
807 ResizeBufferConfigEventData *data =
808 (ResizeBufferConfigEventData *)event->mData.get();
809 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
810 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200811
812 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
813 setCheckOutputStageEffects();
814 } break;
815
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700816 default:
Eric Laurent10351942014-05-08 18:49:52 -0700817 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700818 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800819 }
Eric Laurent10351942014-05-08 18:49:52 -0700820 {
821 Mutex::Autolock _l(event->mLock);
822 if (event->mWaitStatus) {
823 event->mWaitStatus = false;
824 event->mCond.signal();
825 }
826 }
827 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
828 }
829
830 if (configChanged) {
831 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800832 }
Eric Laurent81784c32012-11-19 14:55:58 -0800833}
834
Marco Nelissenb2208842014-02-07 14:00:50 -0800835String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
836 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700837 const audio_channel_representation_t representation =
838 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700839
840 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800841 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700842 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
843 if (output) {
844 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
845 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
846 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700847 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700848 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
849 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
850 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
851 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
852 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
853 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
854 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
855 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
856 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
857 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
858 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
859 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700860 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
861 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
862 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
863 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
864 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
865 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
866 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700867 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700868 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
869 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700870 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
871 } else {
872 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
873 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
874 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
875 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
876 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
877 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
878 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
879 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
880 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
881 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
882 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
883 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700884 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
885 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
886 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700887 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700888 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
889 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700890 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
891 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
892 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
893 }
894 const int len = s.length();
895 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700896 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700897 s.unlockBuffer(len - 2); // remove trailing ", "
898 }
899 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800900 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700901 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
902 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
903 return s;
904 default:
905 s.appendFormat("unknown mask, representation:%d bits:%#x",
906 representation, audio_channel_mask_get_bits(mask));
907 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800908 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800909}
910
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700911void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800912{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800913 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
914 this, mThreadName, getTid(), type(), threadTypeToString(type()));
915
Eric Laurent81784c32012-11-19 14:55:58 -0800916 bool locked = AudioFlinger::dumpTryLock(mLock);
917 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800918 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800919 }
920
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700921 dumpBase_l(fd, args);
922 dumpInternals_l(fd, args);
923 dumpTracks_l(fd, args);
924 dumpEffectChains_l(fd, args);
925
926 if (locked) {
927 mLock.unlock();
928 }
929
930 dprintf(fd, " Local log:\n");
931 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -0700932
933 // --all does the statistics
934 bool dumpAll = false;
935 for (const auto &arg : args) {
936 if (arg == String16("--all")) {
937 dumpAll = true;
938 }
939 }
940 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -0700941 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -0700942 if (!sched.empty()) {
943 (void)write(fd, sched.c_str(), sched.size());
944 }
945 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700946}
947
948void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
949{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700950 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700951 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700952 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700953 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700954 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700955 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700956 dprintf(fd, " Channel count: %u\n", mChannelCount);
957 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800958 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700959 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700960 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700961 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800962 size_t numConfig = mConfigEvents.size();
963 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700964 const size_t SIZE = 256;
965 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800966 for (size_t i = 0; i < numConfig; i++) {
967 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700968 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800969 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700970 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800971 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700972 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800973 }
Andy Hung293558a2017-03-21 12:19:20 -0700974 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -0700975 dprintf(fd, " Output devices: %s (%s)\n",
976 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
977 dprintf(fd, " Input device: %#x (%s)\n",
978 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800979 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800980
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700981 // Dump timestamp statistics for the Thread types that support it.
982 if (mType == RECORD
983 || mType == MIXER
984 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700985 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -0700986 || mType == OFFLOAD
987 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700988 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700989 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700990 }
991
Andy Hung446f4df2019-02-21 12:26:41 -0800992 if (mLastIoBeginNs > 0) { // MMAP may not set this
993 dprintf(fd, " Last %s occurred (msecs): %lld\n",
994 isOutput() ? "write" : "read",
995 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
996 }
997
998 if (mProcessTimeMs.getN() > 0) {
999 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1000 }
1001
1002 if (mIoJitterMs.getN() > 0) {
1003 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1004 isOutput() ? "write" : "read",
1005 mIoJitterMs.toString().c_str());
1006 }
1007
Andy Hunge6c37112019-02-26 17:38:10 -08001008 if (mLatencyMs.getN() > 0) {
1009 dprintf(fd, " Threadloop %s latency stats: %s\n",
1010 isOutput() ? "write" : "read",
1011 mLatencyMs.toString().c_str());
1012 }
Robert Wu06db0a32021-08-10 19:05:34 +00001013
1014 if (mMonopipePipeDepthStats.getN() > 0) {
1015 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1016 isOutput() ? "write" : "read",
1017 mMonopipePipeDepthStats.toString().c_str());
1018 }
Eric Laurent81784c32012-11-19 14:55:58 -08001019}
1020
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001021void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001022{
1023 const size_t SIZE = 256;
1024 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001025
Marco Nelissenb2208842014-02-07 14:00:50 -08001026 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001027 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001028 write(fd, buffer, strlen(buffer));
1029
Marco Nelissenb2208842014-02-07 14:00:50 -08001030 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -08001031 sp<EffectChain> chain = mEffectChains[i];
1032 if (chain != 0) {
1033 chain->dump(fd, args);
1034 }
1035 }
1036}
1037
Andy Hungdae27702016-10-31 14:01:16 -07001038void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001039{
1040 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07001041 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001042}
1043
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001044String16 AudioFlinger::ThreadBase::getWakeLockTag()
1045{
1046 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001047 case MIXER:
1048 return String16("AudioMix");
1049 case DIRECT:
1050 return String16("AudioDirectOut");
1051 case DUPLICATING:
1052 return String16("AudioDup");
1053 case RECORD:
1054 return String16("AudioIn");
1055 case OFFLOAD:
1056 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001057 case MMAP_PLAYBACK:
1058 return String16("MmapPlayback");
1059 case MMAP_CAPTURE:
1060 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001061 case SPATIALIZER:
1062 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001063 default:
1064 ALOG_ASSERT(false);
1065 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001066 }
1067}
1068
Andy Hungdae27702016-10-31 14:01:16 -07001069void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001070{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001071 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001072 if (mPowerManager != 0) {
1073 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001074 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001075 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1076 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001077 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001078 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001079 {} /* workSource */,
1080 {} /* historyTag */);
1081 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001082 mWakeLockToken = binder;
1083 }
Chris Ye6597d732020-02-28 22:38:25 -08001084 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001085 }
Wei Jia3f273d12015-11-24 09:06:49 -08001086
Andy Hung3f0c9022016-01-15 17:49:46 -08001087 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001088 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1089 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001090}
1091
1092void AudioFlinger::ThreadBase::releaseWakeLock()
1093{
1094 Mutex::Autolock _l(mLock);
1095 releaseWakeLock_l();
1096}
1097
1098void AudioFlinger::ThreadBase::releaseWakeLock_l()
1099{
Andy Hung3f0c9022016-01-15 17:49:46 -08001100 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001101 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001102 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001103 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001104 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001105 }
1106 mWakeLockToken.clear();
1107 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001108}
1109
1110void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001111 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001112 // use checkService() to avoid blocking if power service is not up yet
1113 sp<IBinder> binder =
1114 defaultServiceManager()->checkService(String16("power"));
1115 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001116 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001117 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001118 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001119 binder->linkToDeath(mDeathRecipient);
1120 }
1121 }
1122}
1123
Andy Hungd01b0f12016-11-07 16:10:30 -08001124void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001125 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001126
1127#if !LOG_NDEBUG
1128 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001129 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001130 s << uid << " ";
1131 }
1132 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1133#endif
1134
Andy Hung438e7572015-12-14 15:51:17 -08001135 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1136 if (mSystemReady) {
1137 ALOGE("no wake lock to update, but system ready!");
1138 } else {
1139 ALOGW("no wake lock to update, system not ready yet");
1140 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001141 return;
1142 }
1143 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001144 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001145 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1146 mWakeLockToken, uidsAsInt);
1147 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001148 }
1149}
1150
Eric Laurent81784c32012-11-19 14:55:58 -08001151void AudioFlinger::ThreadBase::clearPowerManager()
1152{
1153 Mutex::Autolock _l(mLock);
1154 releaseWakeLock_l();
1155 mPowerManager.clear();
1156}
1157
jiabinc52b1ff2019-10-31 17:20:42 -07001158void AudioFlinger::ThreadBase::updateOutDevices(
1159 const DeviceDescriptorBaseVector& outDevices __unused)
1160{
1161 ALOGE("%s should only be called in RecordThread", __func__);
1162}
1163
Eric Laurentec376dc2021-04-08 20:41:22 +02001164void AudioFlinger::ThreadBase::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs __unused)
1165{
1166 ALOGE("%s should only be called in RecordThread", __func__);
1167}
1168
Glenn Kasten0f11b512014-01-31 16:18:54 -08001169void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001170{
1171 sp<ThreadBase> thread = mThread.promote();
1172 if (thread != 0) {
1173 thread->clearPowerManager();
1174 }
1175 ALOGW("power manager service died !!!");
1176}
1177
Eric Laurent81784c32012-11-19 14:55:58 -08001178void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001179 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001180{
1181 sp<EffectChain> chain = getEffectChain_l(sessionId);
1182 if (chain != 0) {
1183 if (type != NULL) {
1184 chain->setEffectSuspended_l(type, suspend);
1185 } else {
1186 chain->setEffectSuspendedAll_l(suspend);
1187 }
1188 }
1189
1190 updateSuspendedSessions_l(type, suspend, sessionId);
1191}
1192
1193void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1194{
1195 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1196 if (index < 0) {
1197 return;
1198 }
1199
1200 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1201 mSuspendedSessions.valueAt(index);
1202
1203 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001204 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001205 for (int j = 0; j < desc->mRefCount; j++) {
1206 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1207 chain->setEffectSuspendedAll_l(true);
1208 } else {
1209 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1210 desc->mType.timeLow);
1211 chain->setEffectSuspended_l(&desc->mType, true);
1212 }
1213 }
1214 }
1215}
1216
1217void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1218 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001219 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001220{
1221 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1222
1223 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1224
1225 if (suspend) {
1226 if (index >= 0) {
1227 sessionEffects = mSuspendedSessions.valueAt(index);
1228 } else {
1229 mSuspendedSessions.add(sessionId, sessionEffects);
1230 }
1231 } else {
1232 if (index < 0) {
1233 return;
1234 }
1235 sessionEffects = mSuspendedSessions.valueAt(index);
1236 }
1237
1238
1239 int key = EffectChain::kKeyForSuspendAll;
1240 if (type != NULL) {
1241 key = type->timeLow;
1242 }
1243 index = sessionEffects.indexOfKey(key);
1244
1245 sp<SuspendedSessionDesc> desc;
1246 if (suspend) {
1247 if (index >= 0) {
1248 desc = sessionEffects.valueAt(index);
1249 } else {
1250 desc = new SuspendedSessionDesc();
1251 if (type != NULL) {
1252 desc->mType = *type;
1253 }
1254 sessionEffects.add(key, desc);
1255 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1256 }
1257 desc->mRefCount++;
1258 } else {
1259 if (index < 0) {
1260 return;
1261 }
1262 desc = sessionEffects.valueAt(index);
1263 if (--desc->mRefCount == 0) {
1264 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1265 sessionEffects.removeItemsAt(index);
1266 if (sessionEffects.isEmpty()) {
1267 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1268 sessionId);
1269 mSuspendedSessions.removeItem(sessionId);
1270 }
1271 }
1272 }
1273 if (!sessionEffects.isEmpty()) {
1274 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1275 }
1276}
1277
Eric Laurent6b446ce2019-12-13 10:56:31 -08001278void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1279 audio_session_t sessionId,
1280 bool threadLocked) {
1281 if (!threadLocked) {
1282 mLock.lock();
1283 }
Eric Laurent81784c32012-11-19 14:55:58 -08001284
Eric Laurent81784c32012-11-19 14:55:58 -08001285 if (mType != RECORD) {
1286 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1287 // another session. This gives the priority to well behaved effect control panels
1288 // and applications not using global effects.
1289 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1290 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001291 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001292 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1293 }
1294 }
1295
Eric Laurent6b446ce2019-12-13 10:56:31 -08001296 if (!threadLocked) {
1297 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001298 }
1299}
1300
Eric Laurent4c415062016-06-17 16:14:16 -07001301// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1302status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1303 const effect_descriptor_t *desc, audio_session_t sessionId)
1304{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001305 // No global output effect sessions on record threads
1306 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1307 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001308 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1309 desc->name, mThreadName);
1310 return BAD_VALUE;
1311 }
1312 // only pre processing effects on record thread
1313 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1314 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1315 desc->name, mThreadName);
1316 return BAD_VALUE;
1317 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001318
1319 // always allow effects without processing load or latency
1320 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1321 return NO_ERROR;
1322 }
1323
Eric Laurent4c415062016-06-17 16:14:16 -07001324 audio_input_flags_t flags = mInput->flags;
1325 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1326 if (flags & AUDIO_INPUT_FLAG_RAW) {
1327 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1328 desc->name, mThreadName);
1329 return BAD_VALUE;
1330 }
1331 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1332 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1333 desc->name, mThreadName);
1334 return BAD_VALUE;
1335 }
1336 }
jiabineb3bda02020-06-30 14:07:03 -07001337
1338 if (EffectModule::isHapticGenerator(&desc->type)) {
1339 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1340 return BAD_VALUE;
1341 }
Eric Laurent4c415062016-06-17 16:14:16 -07001342 return NO_ERROR;
1343}
1344
1345// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1346status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1347 const effect_descriptor_t *desc, audio_session_t sessionId)
1348{
1349 // no preprocessing on playback threads
1350 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001351 ALOGW("%s: pre processing effect %s created on playback"
1352 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001353 return BAD_VALUE;
1354 }
1355
Eric Laurent3e4de772017-07-16 16:55:08 -07001356 // always allow effects without processing load or latency
1357 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1358 return NO_ERROR;
1359 }
1360
jiabineb3bda02020-06-30 14:07:03 -07001361 if (EffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
1362 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1363 __func__);
1364 return BAD_VALUE;
1365 }
1366
Eric Laurentf690c462021-09-17 14:47:03 +02001367 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1368 && mType != SPATIALIZER) {
1369 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1370 __func__, mType);
1371 return BAD_VALUE;
1372 }
1373
Eric Laurent4c415062016-06-17 16:14:16 -07001374 switch (mType) {
1375 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001376#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001377 // Reject any effect on mixer multichannel sinks.
1378 // TODO: fix both format and multichannel issues with effects.
1379 if (mChannelCount != FCC_2) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001380 ALOGW("%s: effect %s for multichannel(%d) on MIXER thread %s",
1381 __func__, desc->name, mChannelCount, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001382 return BAD_VALUE;
1383 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001384#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001385 audio_output_flags_t flags = mOutput->flags;
1386 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1387 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1388 // global effects are applied only to non fast tracks if they are SW
1389 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1390 break;
1391 }
1392 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1393 // only post processing on output stage session
1394 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001395 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1396 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001397 return BAD_VALUE;
1398 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001399 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1400 // only post processing on output stage session
1401 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001402 ALOGW("%s: non post processing effect %s not allowed on device session",
1403 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001404 return BAD_VALUE;
1405 }
Eric Laurent4c415062016-06-17 16:14:16 -07001406 } else {
1407 // no restriction on effects applied on non fast tracks
1408 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1409 break;
1410 }
1411 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001412
Eric Laurent4c415062016-06-17 16:14:16 -07001413 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001414 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001415 return BAD_VALUE;
1416 }
1417 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001418 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1419 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001420 return BAD_VALUE;
1421 }
1422 }
1423 } break;
1424 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001425 // nothing actionable on offload threads, if the effect:
1426 // - is offloadable: the effect can be created
1427 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1428 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001429 break;
1430 case DIRECT:
1431 // Reject any effect on Direct output threads for now, since the format of
1432 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001433 ALOGW("%s: effect %s on DIRECT output thread %s",
1434 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001435 return BAD_VALUE;
1436 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001437#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001438 // Reject any effect on mixer multichannel sinks.
1439 // TODO: fix both format and multichannel issues with effects.
1440 if (mChannelCount != FCC_2) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001441 ALOGW("%s: effect %s for multichannel(%d) on DUPLICATING thread %s",
1442 __func__, desc->name, mChannelCount, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001443 return BAD_VALUE;
1444 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001445#endif
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001446 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001447 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1448 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001449 return BAD_VALUE;
1450 }
1451 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001452 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1453 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001454 return BAD_VALUE;
1455 }
1456 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001457 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1458 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001459 return BAD_VALUE;
1460 }
1461 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001462 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001463 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1464 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1465 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1466 // are supported and added after the spatializer.
1467 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1468 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1469 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001470 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001471 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1472 // only post processing , downmixer or spatializer effects on output stage session
1473 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1474 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1475 break;
1476 }
1477 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1478 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1479 __func__, desc->name);
1480 return BAD_VALUE;
1481 }
1482 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1483 // only post processing on output stage session
1484 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1485 ALOGW("%s: non post processing effect %s not allowed on device session",
1486 __func__, desc->name);
1487 return BAD_VALUE;
1488 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001489 }
1490 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001491 default:
1492 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1493 }
1494
1495 return NO_ERROR;
1496}
1497
Eric Laurent81784c32012-11-19 14:55:58 -08001498// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1499sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1500 const sp<AudioFlinger::Client>& client,
1501 const sp<IEffectClient>& effectClient,
1502 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001503 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001504 effect_descriptor_t *desc,
1505 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001506 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001507 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001508 bool probe,
1509 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001510{
1511 sp<EffectModule> effect;
1512 sp<EffectHandle> handle;
1513 status_t lStatus;
1514 sp<EffectChain> chain;
1515 bool chainCreated = false;
1516 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001517 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001518
1519 lStatus = initCheck();
1520 if (lStatus != NO_ERROR) {
1521 ALOGW("createEffect_l() Audio driver not initialized.");
1522 goto Exit;
1523 }
1524
Eric Laurent81784c32012-11-19 14:55:58 -08001525 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1526
1527 { // scope for mLock
1528 Mutex::Autolock _l(mLock);
1529
Eric Laurent4c415062016-06-17 16:14:16 -07001530 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001531 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001532 goto Exit;
1533 }
1534
Eric Laurent81784c32012-11-19 14:55:58 -08001535 // check for existing effect chain with the requested audio session
1536 chain = getEffectChain_l(sessionId);
1537 if (chain == 0) {
1538 // create a new chain for this session
1539 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1540 chain = new EffectChain(this, sessionId);
1541 addEffectChain_l(chain);
1542 chain->setStrategy(getStrategyForSession_l(sessionId));
1543 chainCreated = true;
1544 } else {
1545 effect = chain->getEffectFromDesc_l(desc);
1546 }
1547
1548 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1549
1550 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001551 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001552 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001553 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001554 if (lStatus != NO_ERROR) {
1555 goto Exit;
1556 }
1557 effectCreated = true;
1558
jiabinc52b1ff2019-10-31 17:20:42 -07001559 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001560 effect->setDevices(outDeviceTypeAddrs());
1561 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001562 effect->setMode(mAudioFlinger->getMode());
1563 effect->setAudioSource(mAudioSource);
1564 }
jiabin1319f5a2021-03-30 22:21:24 +00001565 if (effect->isHapticGenerator()) {
1566 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1567 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001568 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
1569 std::move(mAudioFlinger->getDefaultVibratorInfo_l());
1570 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001571 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001572 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001573 }
1574 }
Eric Laurent81784c32012-11-19 14:55:58 -08001575 // create effect handle and connect it to effect module
Eric Laurentde8caf42021-08-11 17:19:25 +02001576 handle = new EffectHandle(effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001577 lStatus = handle->initCheck();
1578 if (lStatus == OK) {
1579 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001580 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001581 }
Eric Laurent81784c32012-11-19 14:55:58 -08001582 if (enabled != NULL) {
1583 *enabled = (int)effect->isEnabled();
1584 }
1585 }
1586
1587Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001588 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001589 Mutex::Autolock _l(mLock);
1590 if (effectCreated) {
1591 chain->removeEffect_l(effect);
1592 }
Eric Laurent81784c32012-11-19 14:55:58 -08001593 if (chainCreated) {
1594 removeEffectChain_l(chain);
1595 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001596 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001597 }
1598
Glenn Kasten9156ef32013-08-06 15:39:08 -07001599 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001600 return handle;
1601}
1602
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001603void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1604 bool unpinIfLast)
1605{
1606 bool remove = false;
1607 sp<EffectModule> effect;
1608 {
1609 Mutex::Autolock _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001610 sp<EffectBase> effectBase = handle->effect().promote();
1611 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001612 return;
1613 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001614 effect = effectBase->asEffectModule();
1615 if (effect == nullptr) {
1616 return;
1617 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001618 // restore suspended effects if the disconnected handle was enabled and the last one.
1619 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1620 if (remove) {
1621 removeEffect_l(effect, true);
1622 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001623 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001624 }
1625 if (remove) {
1626 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001627 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001628 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001629 }
1630 }
1631}
1632
Eric Laurent6b446ce2019-12-13 10:56:31 -08001633void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001634 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001635 Mutex::Autolock _l(mLock);
1636 broadcast_l();
1637 }
1638 if (!effect->isOffloadable()) {
1639 if (mType == ThreadBase::OFFLOAD) {
1640 PlaybackThread *t = (PlaybackThread *)this;
1641 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1642 }
1643 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1644 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1645 }
1646 }
1647}
1648
1649void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001650 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001651 Mutex::Autolock _l(mLock);
1652 broadcast_l();
1653 }
1654}
1655
Glenn Kastend848eb42016-03-08 13:42:11 -08001656sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1657 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001658{
1659 Mutex::Autolock _l(mLock);
1660 return getEffect_l(sessionId, effectId);
1661}
1662
Glenn Kastend848eb42016-03-08 13:42:11 -08001663sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1664 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001665{
1666 sp<EffectChain> chain = getEffectChain_l(sessionId);
1667 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1668}
1669
Eric Laurent6c796322019-04-09 14:13:17 -07001670std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1671{
1672 sp<EffectChain> chain = getEffectChain_l(sessionId);
1673 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1674}
1675
Eric Laurent81784c32012-11-19 14:55:58 -08001676// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1677// PlaybackThread::mLock held
1678status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1679{
1680 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001681 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001682 sp<EffectChain> chain = getEffectChain_l(sessionId);
1683 bool chainCreated = false;
1684
Eric Laurent5baf2af2013-09-12 17:37:00 -07001685 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001686 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001687 this, effect->desc().name, effect->desc().flags);
1688
Eric Laurent81784c32012-11-19 14:55:58 -08001689 if (chain == 0) {
1690 // create a new chain for this session
1691 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1692 chain = new EffectChain(this, sessionId);
1693 addEffectChain_l(chain);
1694 chain->setStrategy(getStrategyForSession_l(sessionId));
1695 chainCreated = true;
1696 }
1697 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1698
1699 if (chain->getEffectFromId_l(effect->id()) != 0) {
1700 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1701 this, effect->desc().name, chain.get());
1702 return BAD_VALUE;
1703 }
1704
Eric Laurent5baf2af2013-09-12 17:37:00 -07001705 effect->setOffloaded(mType == OFFLOAD, mId);
1706
Eric Laurent81784c32012-11-19 14:55:58 -08001707 status_t status = chain->addEffect_l(effect);
1708 if (status != NO_ERROR) {
1709 if (chainCreated) {
1710 removeEffectChain_l(chain);
1711 }
1712 return status;
1713 }
1714
jiabin8f278ee2019-11-11 12:16:27 -08001715 effect->setDevices(outDeviceTypeAddrs());
1716 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001717 effect->setMode(mAudioFlinger->getMode());
1718 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001719
Eric Laurent81784c32012-11-19 14:55:58 -08001720 return NO_ERROR;
1721}
1722
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001723void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001724
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001725 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001726 effect_descriptor_t desc = effect->desc();
1727 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1728 detachAuxEffect_l(effect->id());
1729 }
1730
Andy Hungfda44002021-06-03 17:23:16 -07001731 sp<EffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001732 if (chain != 0) {
1733 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001734 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001735 removeEffectChain_l(chain);
1736 }
1737 } else {
1738 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1739 }
1740}
1741
1742void AudioFlinger::ThreadBase::lockEffectChains_l(
1743 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1744{
1745 effectChains = mEffectChains;
1746 for (size_t i = 0; i < mEffectChains.size(); i++) {
1747 mEffectChains[i]->lock();
1748 }
1749}
1750
1751void AudioFlinger::ThreadBase::unlockEffectChains(
1752 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1753{
1754 for (size_t i = 0; i < effectChains.size(); i++) {
1755 effectChains[i]->unlock();
1756 }
1757}
1758
Glenn Kastend848eb42016-03-08 13:42:11 -08001759sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001760{
1761 Mutex::Autolock _l(mLock);
1762 return getEffectChain_l(sessionId);
1763}
1764
Glenn Kastend848eb42016-03-08 13:42:11 -08001765sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1766 const
Eric Laurent81784c32012-11-19 14:55:58 -08001767{
1768 size_t size = mEffectChains.size();
1769 for (size_t i = 0; i < size; i++) {
1770 if (mEffectChains[i]->sessionId() == sessionId) {
1771 return mEffectChains[i];
1772 }
1773 }
1774 return 0;
1775}
1776
1777void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1778{
1779 Mutex::Autolock _l(mLock);
1780 size_t size = mEffectChains.size();
1781 for (size_t i = 0; i < size; i++) {
1782 mEffectChains[i]->setMode_l(mode);
1783 }
1784}
1785
Mikhail Naganovdc769682018-05-04 15:34:08 -07001786void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001787{
1788 config->type = AUDIO_PORT_TYPE_MIX;
1789 config->ext.mix.handle = mId;
1790 config->sample_rate = mSampleRate;
1791 config->format = mFormat;
1792 config->channel_mask = mChannelMask;
1793 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1794 AUDIO_PORT_CONFIG_FORMAT;
1795}
1796
Eric Laurent72e3f392015-05-20 14:43:50 -07001797void AudioFlinger::ThreadBase::systemReady()
1798{
1799 Mutex::Autolock _l(mLock);
1800 if (mSystemReady) {
1801 return;
1802 }
1803 mSystemReady = true;
1804
1805 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1806 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1807 }
1808 mPendingConfigEvents.clear();
1809}
1810
Andy Hungdae27702016-10-31 14:01:16 -07001811template <typename T>
1812ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1813 ssize_t index = mActiveTracks.indexOf(track);
1814 if (index >= 0) {
1815 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1816 return index;
1817 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001818 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001819 mActiveTracksGeneration++;
1820 mLatestActiveTrack = track;
1821 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001822 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001823 return mActiveTracks.add(track);
1824}
1825
1826template <typename T>
1827ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1828 ssize_t index = mActiveTracks.remove(track);
1829 if (index < 0) {
1830 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1831 return index;
1832 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001833 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001834 mActiveTracksGeneration++;
1835 --mBatteryCounter[track->uid()].second;
1836 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001837 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001838#ifdef TEE_SINK
1839 track->dumpTee(-1 /* fd */, "_REMOVE");
1840#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001841 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001842 return index;
1843}
1844
1845template <typename T>
1846void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1847 for (const sp<T> &track : mActiveTracks) {
1848 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001849 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001850 }
1851 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001852 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001853 mActiveTracks.clear();
1854 mLatestActiveTrack.clear();
1855 mBatteryCounter.clear();
1856}
1857
1858template <typename T>
1859void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1860 sp<ThreadBase> thread, bool force) {
1861 // Updates ActiveTracks client uids to the thread wakelock.
1862 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1863 thread->updateWakeLockUids_l(getWakeLockUids());
1864 mLastActiveTracksGeneration = mActiveTracksGeneration;
1865 }
1866
1867 // Updates BatteryNotifier uids
1868 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1869 const uid_t uid = it->first;
1870 ssize_t &previous = it->second.first;
1871 ssize_t &current = it->second.second;
1872 if (current > 0) {
1873 if (previous == 0) {
1874 BatteryNotifier::getInstance().noteStartAudio(uid);
1875 }
1876 previous = current;
1877 ++it;
1878 } else if (current == 0) {
1879 if (previous > 0) {
1880 BatteryNotifier::getInstance().noteStopAudio(uid);
1881 }
1882 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1883 } else /* (current < 0) */ {
1884 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1885 }
1886 }
1887}
Eric Laurent83b88082014-06-20 18:31:16 -07001888
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001889template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001890bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001891 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001892 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001893
1894 for (const sp<T> &track : mActiveTracks) {
1895 // Do not short-circuit as all hasChanged states must be reset
1896 // as all the metadata are going to be sent
1897 hasChanged |= track->readAndClearHasChanged();
1898 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001899 return hasChanged;
1900}
1901
1902template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001903void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1904 const char *funcName, const sp<T> &track) const {
1905 if (mLocalLog != nullptr) {
1906 String8 result;
1907 track->appendDump(result, false /* active */);
1908 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1909 }
1910}
1911
Eric Laurent6acd1d42017-01-04 14:23:29 -08001912void AudioFlinger::ThreadBase::broadcast_l()
1913{
1914 // Thread could be blocked waiting for async
1915 // so signal it to handle state changes immediately
1916 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1917 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1918 mSignalPending = true;
1919 mWaitWorkCV.broadcast();
1920}
1921
Andy Hungd0979812019-02-21 15:51:44 -08001922// Call only from threadLoop() or when it is idle.
1923// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1924void AudioFlinger::ThreadBase::sendStatistics(bool force)
1925{
1926 // Do not log if we have no stats.
1927 // We choose the timestamp verifier because it is the most likely item to be present.
1928 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1929 if (nstats == 0) {
1930 return;
1931 }
1932
1933 // Don't log more frequently than once per 12 hours.
1934 // We use BOOTTIME to include suspend time.
1935 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1936 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1937 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1938 return;
1939 }
1940
1941 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1942 mLastRecordedTimeNs = timeNs;
1943
Ray Essickf27e9872019-12-07 06:28:46 -08001944 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001945
1946#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1947
1948 // thread configuration
1949 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1950 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1951 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1952 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1953 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1954 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1955 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001956 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1957 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001958
1959 // thread statistics
1960 if (mIoJitterMs.getN() > 0) {
1961 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1962 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1963 }
1964 if (mProcessTimeMs.getN() > 0) {
1965 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1966 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1967 }
1968 const auto tsjitter = mTimestampVerifier.getJitterMs();
1969 if (tsjitter.getN() > 0) {
1970 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1971 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1972 }
1973 if (mLatencyMs.getN() > 0) {
1974 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1975 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1976 }
Robert Wu06db0a32021-08-10 19:05:34 +00001977 if (mMonopipePipeDepthStats.getN() > 0) {
1978 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
1979 mMonopipePipeDepthStats.getMean());
1980 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
1981 mMonopipePipeDepthStats.getStdDev());
1982 }
Andy Hungd0979812019-02-21 15:51:44 -08001983
1984 item->selfrecord();
1985}
1986
Eric Laurentd66d7a12021-07-13 13:35:32 +02001987product_strategy_t AudioFlinger::ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
1988{
1989 if (!mAudioFlinger->isAudioPolicyReady()) {
1990 return PRODUCT_STRATEGY_NONE;
1991 }
1992 return AudioSystem::getStrategyForStream(stream);
1993}
1994
Eric Laurent81784c32012-11-19 14:55:58 -08001995// ----------------------------------------------------------------------------
1996// Playback
1997// ----------------------------------------------------------------------------
1998
1999AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
2000 AudioStreamOut* output,
2001 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002002 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002003 bool systemReady,
2004 audio_config_base_t *mixerConfig)
Andy Hungcf10d742020-04-28 15:38:24 -07002005 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002006 mNormalFrameCount(0), mSinkBuffer(NULL),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002007 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002008 mMixerBuffer(NULL),
2009 mMixerBufferSize(0),
2010 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2011 mMixerBufferValid(false),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002012 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002013 mEffectBuffer(NULL),
2014 mEffectBufferSize(0),
2015 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2016 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002017 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002018 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002019 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002020 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002021 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002022 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002023 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002024 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002025 mMixerStatus(MIXER_IDLE),
2026 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002027 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002028 mBytesRemaining(0),
2029 mCurrentWriteLength(0),
2030 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002031 mWriteAckSequence(0),
2032 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08002033 mScreenState(AudioFlinger::mScreenState),
2034 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002035 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002036 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002037 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002038 mDownStreamPatch{},
2039 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002040{
Glenn Kastend7dca052015-03-05 16:05:54 -08002041 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
2042 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002043
2044 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2045 // it would be safer to explicitly pass initial masterVolume/masterMute as
2046 // parameter.
2047 //
2048 // If the HAL we are using has support for master volume or master mute,
2049 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2050 // and the mute set to false).
2051 mMasterVolume = audioFlinger->masterVolume_l();
2052 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002053 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002054 if (mOutput->audioHwDev->canSetMasterVolume()) {
2055 mMasterVolume = 1.0;
2056 }
2057
2058 if (mOutput->audioHwDev->canSetMasterMute()) {
2059 mMasterMute = false;
2060 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002061 mIsMsdDevice = strcmp(
2062 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002063 }
2064
Eric Laurentf1f22e72021-07-13 14:04:14 +02002065 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2066 mMixerChannelMask = mixerConfig->channel_mask;
2067 }
2068
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002069 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002070
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002071 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002072 && mMixerChannelMask != mChannelMask) {
2073 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2074 mChannelMask, mMixerChannelMask);
2075 }
2076
Andy Hungc8fddf32018-08-08 18:32:37 -07002077 // TODO: We may also match on address as well as device type for
2078 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002079 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002080 // TODO: This property should be ensure that only contains one single device type.
2081 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2082 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002083 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2084 : AUDIO_DEVICE_NONE));
2085 }
2086
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002087 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2088 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002089 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08002090 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
2091 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002092 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002093 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2094 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002095 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2096 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002097}
2098
2099AudioFlinger::PlaybackThread::~PlaybackThread()
2100{
Glenn Kasten9e58b552013-01-18 15:09:48 -08002101 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002102 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002103 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002104 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002105 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002106}
2107
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002108// Thread virtuals
2109
2110void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002111{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002112 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002113 ALOGE("The stream is not open yet"); // This should not happen.
2114 } else {
2115 // setEventCallback will need a strong pointer as a parameter. Calling it
2116 // here instead of constructor of PlaybackThread so that the onFirstRef
2117 // callback would not be made on an incompletely constructed object.
2118 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002119 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002120 }
2121 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002122 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002123 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002124}
2125
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002126// ThreadBase virtuals
2127void AudioFlinger::PlaybackThread::preExit()
2128{
2129 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002130 status_t result = mOutput->stream->exit();
2131 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002132}
2133
2134void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002135{
Eric Laurent81784c32012-11-19 14:55:58 -08002136 String8 result;
2137
Marco Nelissenb2208842014-02-07 14:00:50 -08002138 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002139 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2140 const stream_type_t *st = &mStreamTypes[i];
2141 if (i > 0) {
2142 result.appendFormat(", ");
2143 }
2144 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2145 if (st->mute) {
2146 result.append("M");
2147 }
2148 }
2149 result.append("\n");
2150 write(fd, result.string(), result.length());
2151 result.clear();
2152
Eric Laurent81784c32012-11-19 14:55:58 -08002153 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2154 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002155 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002156 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002157
2158 size_t numtracks = mTracks.size();
2159 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002160 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002161 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002162 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002163 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002164 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002165 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002166 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002167 for (size_t i = 0; i < numtracks; ++i) {
2168 sp<Track> track = mTracks[i];
2169 if (track != 0) {
2170 bool active = mActiveTracks.indexOf(track) >= 0;
2171 if (active) {
2172 numactiveseen++;
2173 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002174 result.append(prefix);
2175 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002176 }
2177 }
2178 } else {
2179 result.append("\n");
2180 }
2181 if (numactiveseen != numactive) {
2182 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002183 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002184 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002185 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002186 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002187 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002188 sp<Track> track = mActiveTracks[i];
2189 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002190 result.append(prefix);
2191 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002192 }
2193 }
2194 }
2195
2196 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002197}
2198
Andy Hung61589a42021-06-16 09:37:53 -07002199void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002200{
Andy Hung04cb8f72020-03-20 13:44:33 -07002201 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002202 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002203 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2204 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002205 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2206 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2207 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2208 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002209 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002210 dprintf(fd, " Total writes: %d\n", mNumWrites);
2211 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2212 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2213 dprintf(fd, " Suspend count: %d\n", mSuspended);
2214 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2215 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2216 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2217 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002218 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002219 AudioStreamOut *output = mOutput;
2220 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002221 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002222 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002223 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2224 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2225 if (mPipeSink.get() != nullptr) {
2226 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2227 }
2228 if (output != nullptr) {
2229 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002230 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002231 }
Eric Laurent81784c32012-11-19 14:55:58 -08002232}
2233
Eric Laurent81784c32012-11-19 14:55:58 -08002234// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2235sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2236 const sp<AudioFlinger::Client>& client,
2237 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002238 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002239 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002240 audio_format_t format,
2241 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002242 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002243 size_t *pNotificationFrameCount,
2244 uint32_t notificationsPerBuffer,
2245 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002246 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002247 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002248 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002249 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002250 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002251 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002252 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002253 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002254 const sp<media::IAudioTrackCallback>& callback,
2255 bool isSpatialized)
Eric Laurent81784c32012-11-19 14:55:58 -08002256{
Glenn Kasten74935e42013-12-19 08:56:45 -08002257 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002258 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002259 sp<Track> track;
2260 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002261 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002262 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002263 uint32_t sampleRate;
2264
2265 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2266 lStatus = BAD_VALUE;
2267 goto Exit;
2268 }
Eric Laurent21da6472017-11-09 16:29:26 -08002269
2270 if (*pSampleRate == 0) {
2271 *pSampleRate = mSampleRate;
2272 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002273 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002274
2275 // special case for FAST flag considered OK if fast mixer is present
2276 if (hasFastMixer()) {
2277 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2278 }
2279
2280 // Check if requested flags are compatible with output stream flags
2281 if ((*flags & outputFlags) != *flags) {
2282 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2283 *flags, outputFlags);
2284 *flags = (audio_output_flags_t)(*flags & outputFlags);
2285 }
Eric Laurent81784c32012-11-19 14:55:58 -08002286
Eric Laurent81784c32012-11-19 14:55:58 -08002287 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002288 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002289 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002290 // PCM data
2291 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002292 // TODO: extract as a data library function that checks that a computationally
2293 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002294 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002295 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2296 (channelMask == AUDIO_CHANNEL_OUT_MONO
2297 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002298 // hardware sample rate
2299 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002300 // normal mixer has an associated fast mixer
2301 hasFastMixer() &&
2302 // there are sufficient fast track slots available
2303 (mFastTrackAvailMask != 0)
2304 // FIXME test that MixerThread for this fast track has a capable output HAL
2305 // FIXME add a permission test also?
2306 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002307 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2308 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002309 // read the fast track multiplier property the first time it is needed
2310 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2311 if (ok != 0) {
2312 ALOGE("%s pthread_once failed: %d", __func__, ok);
2313 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002314 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002315 }
Eric Laurent4c415062016-06-17 16:14:16 -07002316
2317 // check compatibility with audio effects.
2318 { // scope for mLock
2319 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002320 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002321 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002322 AUDIO_SESSION_OUTPUT_STAGE,
2323 AUDIO_SESSION_OUTPUT_MIX,
2324 sessionId,
2325 }) {
2326 sp<EffectChain> chain = getEffectChain_l(session);
2327 if (chain.get() != nullptr) {
2328 audio_output_flags_t old = *flags;
2329 chain->checkOutputFlagCompatibility(flags);
2330 if (old != *flags) {
2331 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2332 (int)session, (int)old, (int)*flags);
2333 }
Eric Laurent4c415062016-06-17 16:14:16 -07002334 }
2335 }
2336 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002337 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002338 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2339 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002340 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002341 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002342 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002343 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002344 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002345 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002346 audio_is_linear_pcm(format), channelMask, sampleRate,
2347 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002348 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002349 }
2350 }
Eric Laurent21da6472017-11-09 16:29:26 -08002351
2352 if (!audio_has_proportional_frames(format)) {
2353 if (sharedBuffer != 0) {
2354 // Same comment as below about ignoring frameCount parameter for set()
2355 frameCount = sharedBuffer->size();
2356 } else if (frameCount == 0) {
2357 frameCount = mNormalFrameCount;
2358 }
2359 if (notificationFrameCount != frameCount) {
2360 notificationFrameCount = frameCount;
2361 }
2362 } else if (sharedBuffer != 0) {
2363 // FIXME: Ensure client side memory buffers need
2364 // not have additional alignment beyond sample
2365 // (e.g. 16 bit stereo accessed as 32 bit frame).
2366 size_t alignment = audio_bytes_per_sample(format);
2367 if (alignment & 1) {
2368 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2369 alignment = 1;
2370 }
2371 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2372 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2373 if (channelCount > 1) {
2374 // More than 2 channels does not require stronger alignment than stereo
2375 alignment <<= 1;
2376 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002377 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002378 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002379 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002380 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002381 goto Exit;
2382 }
Eric Laurent21da6472017-11-09 16:29:26 -08002383
2384 // When initializing a shared buffer AudioTrack via constructors,
2385 // there's no frameCount parameter.
2386 // But when initializing a shared buffer AudioTrack via set(),
2387 // there _is_ a frameCount parameter. We silently ignore it.
2388 frameCount = sharedBuffer->size() / frameSize;
2389 } else {
2390 size_t minFrameCount = 0;
2391 // For fast tracks we try to respect the application's request for notifications per buffer.
2392 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2393 if (notificationsPerBuffer > 0) {
2394 // Avoid possible arithmetic overflow during multiplication.
2395 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2396 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2397 notificationsPerBuffer, mFrameCount);
2398 } else {
2399 minFrameCount = mFrameCount * notificationsPerBuffer;
2400 }
2401 }
2402 } else {
2403 // For normal PCM streaming tracks, update minimum frame count.
2404 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2405 // cover audio hardware latency.
2406 // This is probably too conservative, but legacy application code may depend on it.
2407 // If you change this calculation, also review the start threshold which is related.
2408 uint32_t latencyMs = latency_l();
2409 if (latencyMs == 0) {
2410 ALOGE("Error when retrieving output stream latency");
2411 lStatus = UNKNOWN_ERROR;
2412 goto Exit;
2413 }
2414
2415 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2416 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2417
Eric Laurent81784c32012-11-19 14:55:58 -08002418 }
Eric Laurent21da6472017-11-09 16:29:26 -08002419 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002420 frameCount = minFrameCount;
2421 }
Eric Laurent81784c32012-11-19 14:55:58 -08002422 }
Eric Laurent21da6472017-11-09 16:29:26 -08002423
2424 // Make sure that application is notified with sufficient margin before underrun.
2425 // The client can divide the AudioTrack buffer into sub-buffers,
2426 // and expresses its desire to server as the notification frame count.
2427 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2428 size_t maxNotificationFrames;
2429 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2430 // notify every HAL buffer, regardless of the size of the track buffer
2431 maxNotificationFrames = mFrameCount;
2432 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002433 // Triple buffer the notification period for a triple buffered mixer period;
2434 // otherwise, double buffering for the notification period is fine.
2435 //
2436 // TODO: This should be moved to AudioTrack to modify the notification period
2437 // on AudioTrack::setBufferSizeInFrames() changes.
2438 const int nBuffering =
2439 (uint64_t{frameCount} * mSampleRate)
2440 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2441
Eric Laurent21da6472017-11-09 16:29:26 -08002442 maxNotificationFrames = frameCount / nBuffering;
2443 // If client requested a fast track but this was denied, then use the smaller maximum.
2444 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2445 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2446 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2447 maxNotificationFrames = maxNotificationFramesFastDenied;
2448 }
2449 }
2450 }
2451 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2452 if (notificationFrameCount == 0) {
2453 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2454 maxNotificationFrames, frameCount);
2455 } else {
2456 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2457 notificationFrameCount, maxNotificationFrames, frameCount);
2458 }
2459 notificationFrameCount = maxNotificationFrames;
2460 }
2461 }
2462
Glenn Kasten74935e42013-12-19 08:56:45 -08002463 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002464 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002465
Glenn Kastenc3df8382014-03-13 15:05:25 -07002466 switch (mType) {
2467
2468 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002469 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002470 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002471 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2472 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002473 sampleRate, format, channelMask, mOutput, mFormat);
2474 lStatus = BAD_VALUE;
2475 goto Exit;
2476 }
2477 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002478 break;
2479
2480 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002481 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002482 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2483 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002484 sampleRate, format, channelMask, mOutput, mFormat);
2485 lStatus = BAD_VALUE;
2486 goto Exit;
2487 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002488 break;
2489
2490 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002491 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002492 ALOGE("createTrack_l() Bad parameter: format %#x \""
2493 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002494 format, mOutput, mFormat);
2495 lStatus = BAD_VALUE;
2496 goto Exit;
2497 }
Andy Hungcd044842014-08-07 11:04:34 -07002498 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002499 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2500 lStatus = BAD_VALUE;
2501 goto Exit;
2502 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002503 break;
2504
Eric Laurent81784c32012-11-19 14:55:58 -08002505 }
2506
2507 lStatus = initCheck();
2508 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002509 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002510 goto Exit;
2511 }
2512
2513 { // scope for mLock
2514 Mutex::Autolock _l(mLock);
2515
2516 // all tracks in same audio session must share the same routing strategy otherwise
2517 // conflicts will happen when tracks are moved from one output to another by audio policy
2518 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002519 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002520 for (size_t i = 0; i < mTracks.size(); ++i) {
2521 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002522 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002523 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002524 if (sessionId == t->sessionId() && strategy != actual) {
2525 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2526 strategy, actual);
2527 lStatus = BAD_VALUE;
2528 goto Exit;
2529 }
2530 }
2531 }
2532
yucliuc9c49cd2020-07-13 16:25:21 -07002533 // Set DIRECT flag if current thread is DirectOutputThread. This can
2534 // happen when the playback is rerouted to direct output thread by
2535 // dynamic audio policy.
2536 // Do NOT report the flag changes back to client, since the client
2537 // doesn't explicitly request a direct flag.
2538 audio_output_flags_t trackFlags = *flags;
2539 if (mType == DIRECT) {
2540 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2541 }
2542
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002543 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002544 channelMask, frameCount,
2545 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002546 sessionId, creatorPid, attributionSource, trackFlags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002547 TrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
2548 speed, isSpatialized);
Glenn Kasten03003332013-08-06 15:40:54 -07002549
Glenn Kasten03003332013-08-06 15:40:54 -07002550 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2551 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002552 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002553 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002554 goto Exit;
2555 }
2556 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002557 {
2558 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2559 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002560 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002561 }
2562 }
Eric Laurent81784c32012-11-19 14:55:58 -08002563
2564 sp<EffectChain> chain = getEffectChain_l(sessionId);
2565 if (chain != 0) {
2566 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2567 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002568 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002569 chain->incTrackCnt();
2570 }
2571
Eric Laurent05067782016-06-01 18:27:28 -07002572 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002573 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2574 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2575 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002576 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002577 }
2578 }
2579
2580 lStatus = NO_ERROR;
2581
2582Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002583 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002584 return track;
2585}
2586
Andy Hung1bc088a2018-02-09 15:57:31 -08002587template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002588ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2589{
Andy Hungc0691382018-09-12 18:01:57 -07002590 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002591 const ssize_t index = mTracks.remove(track);
2592 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002593 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002594 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002595 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002596 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002597 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002598 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002599 }
2600 return index;
2601}
2602
Eric Laurent81784c32012-11-19 14:55:58 -08002603uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2604{
2605 return latency;
2606}
2607
2608uint32_t AudioFlinger::PlaybackThread::latency() const
2609{
2610 Mutex::Autolock _l(mLock);
2611 return latency_l();
2612}
2613uint32_t AudioFlinger::PlaybackThread::latency_l() const
2614{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002615 uint32_t latency;
2616 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2617 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002618 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002619 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002620}
2621
2622void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2623{
2624 Mutex::Autolock _l(mLock);
2625 // Don't apply master volume in SW if our HAL can do it for us.
2626 if (mOutput && mOutput->audioHwDev &&
2627 mOutput->audioHwDev->canSetMasterVolume()) {
2628 mMasterVolume = 1.0;
2629 } else {
2630 mMasterVolume = value;
2631 }
2632}
2633
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002634void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2635{
2636 mMasterBalance.store(balance);
2637}
2638
Eric Laurent81784c32012-11-19 14:55:58 -08002639void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2640{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002641 if (isDuplicating()) {
2642 return;
2643 }
Eric Laurent81784c32012-11-19 14:55:58 -08002644 Mutex::Autolock _l(mLock);
2645 // Don't apply master mute in SW if our HAL can do it for us.
2646 if (mOutput && mOutput->audioHwDev &&
2647 mOutput->audioHwDev->canSetMasterMute()) {
2648 mMasterMute = false;
2649 } else {
2650 mMasterMute = muted;
2651 }
2652}
2653
2654void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2655{
2656 Mutex::Autolock _l(mLock);
2657 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002658 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002659}
2660
2661void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2662{
2663 Mutex::Autolock _l(mLock);
2664 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002665 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002666}
2667
2668float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2669{
2670 Mutex::Autolock _l(mLock);
2671 return mStreamTypes[stream].volume;
2672}
2673
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002674void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2675{
2676 mOutput->stream->setVolume(left, right);
2677}
2678
Eric Laurent81784c32012-11-19 14:55:58 -08002679// addTrack_l() must be called with ThreadBase::mLock held
2680status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2681{
2682 status_t status = ALREADY_EXISTS;
2683
Eric Laurent81784c32012-11-19 14:55:58 -08002684 if (mActiveTracks.indexOf(track) < 0) {
2685 // the track is newly added, make sure it fills up all its
2686 // buffers before playing. This is to ensure the client will
2687 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002688 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002689 TrackBase::track_state state = track->mState;
2690 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002691 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002692 mLock.lock();
2693 // abort track was stopped/paused while we released the lock
2694 if (state != track->mState) {
2695 if (status == NO_ERROR) {
2696 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002697 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002698 mLock.lock();
2699 }
2700 return INVALID_OPERATION;
2701 }
2702 // abort if start is rejected by audio policy manager
2703 if (status != NO_ERROR) {
2704 return PERMISSION_DENIED;
2705 }
2706#ifdef ADD_BATTERY_DATA
2707 // to track the speaker usage
2708 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2709#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002710 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002711 }
2712
Eric Laurent51716182016-02-29 18:00:56 -08002713 // set retry count for buffer fill
2714 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002715 if (track->isStopping_1()) {
2716 track->mRetryCount = kMaxTrackStopRetriesOffload;
2717 } else {
2718 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2719 }
2720 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002721 } else {
2722 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002723 track->mFillingUpStatus =
2724 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002725 }
2726
jiabineb3bda02020-06-30 14:07:03 -07002727 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2728 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2729 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2730 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002731 // Unlock due to VibratorService will lock for this call and will
2732 // call Tracks.mute/unmute which also require thread's lock.
2733 mLock.unlock();
2734 const int intensity = AudioFlinger::onExternalVibrationStart(
2735 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002736 std::optional<media::AudioVibratorInfo> vibratorInfo;
2737 {
2738 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2739 // used to play this track.
2740 Mutex::Autolock _l(mAudioFlinger->mLock);
2741 vibratorInfo = std::move(mAudioFlinger->getDefaultVibratorInfo_l());
2742 }
jiabin57303cc2018-12-18 15:45:57 -08002743 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002744 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
Lais Andradebc3f37a2021-07-02 00:13:19 +01002745 if (vibratorInfo) {
2746 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2747 }
2748
jiabin57303cc2018-12-18 15:45:57 -08002749 // Haptic playback should be enabled by vibrator service.
2750 if (track->getHapticPlaybackEnabled()) {
2751 // Disable haptic playback of all active track to ensure only
2752 // one track playing haptic if current track should play haptic.
2753 for (const auto &t : mActiveTracks) {
2754 t->setHapticPlaybackEnabled(false);
2755 }
jiabin245cdd92018-12-07 17:55:15 -08002756 }
jiabine70bc7f2020-06-30 22:07:55 -07002757
2758 // Set haptic intensity for effect
2759 if (chain != nullptr) {
2760 chain->setHapticIntensity_l(track->id(), intensity);
2761 }
jiabin245cdd92018-12-07 17:55:15 -08002762 }
2763
Eric Laurent81784c32012-11-19 14:55:58 -08002764 track->mResetDone = false;
Andy Hung59de4262021-06-14 10:53:54 -07002765 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002766 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002767 if (chain != 0) {
2768 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2769 track->sessionId());
2770 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002771 }
2772
Andy Hungc2b11cb2020-04-22 09:04:01 -07002773 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002774 status = NO_ERROR;
2775 }
2776
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002777 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002778 return status;
2779}
2780
Eric Laurentbfb1b832013-01-07 09:53:42 -08002781bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002782{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002783 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002784 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002785 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2786 track->mState = TrackBase::STOPPED;
2787 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002788 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002789 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002790 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002791 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002792
2793 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002794}
2795
2796void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2797{
2798 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002799
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002800 String8 result;
2801 track->appendDump(result, false /* active */);
2802 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002803
Eric Laurent81784c32012-11-19 14:55:58 -08002804 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002805 {
2806 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2807 mAudioTrackCallbacks.erase(track);
2808 }
Eric Laurent81784c32012-11-19 14:55:58 -08002809 if (track->isFastTrack()) {
2810 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002811 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002812 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2813 mFastTrackAvailMask |= 1 << index;
2814 // redundant as track is about to be destroyed, for dumpsys only
2815 track->mFastIndex = -1;
2816 }
2817 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2818 if (chain != 0) {
2819 chain->decTrackCnt();
2820 }
2821}
2822
2823String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2824{
Eric Laurent81784c32012-11-19 14:55:58 -08002825 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002826 String8 out_s8;
2827 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2828 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002829 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002830 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002831}
2832
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002833status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2834 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002835 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002836 return NO_INIT;
2837 }
2838 return mOutput->stream->selectPresentation(presentationId, programId);
2839}
2840
Mikhail Naganov88536df2021-07-26 17:30:29 -07002841void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002842 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002843 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07002844 sp<AudioIoDescriptor> desc;
2845 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002846 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002847 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002848 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002849 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002850 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
2851 mSampleRate, mFormat, mChannelMask,
2852 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
2853 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08002854 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002855 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002856 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07002857 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002858 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002859 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002860 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08002861 break;
2862 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002863 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002864}
2865
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002866void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002867{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002868 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002869}
2870
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002871void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002872{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002873 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002874}
2875
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002876void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002877{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002878 mCallbackThread->setAsyncError();
2879}
2880
jiabinf6eb4c32020-02-25 14:06:25 -08002881void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2882 const std::basic_string<uint8_t>& metadataBs)
2883{
2884 std::thread([this, metadataBs]() {
2885 audio_utils::metadata::Data metadata =
2886 audio_utils::metadata::dataFromByteString(metadataBs);
2887 if (metadata.empty()) {
2888 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2889 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2890 (int)metadataBs.size());
2891 return;
2892 }
2893
2894 audio_utils::metadata::ByteString metaDataStr =
2895 audio_utils::metadata::byteStringFromData(metadata);
2896 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2897 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002898 for (const auto& callbackPair : mAudioTrackCallbacks) {
2899 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002900 }
2901 }).detach();
2902}
2903
Eric Laurent3b4529e2013-09-05 18:09:19 -07002904void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002905{
2906 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002907 // reject out of sequence requests
2908 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2909 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002910 mWaitWorkCV.signal();
2911 }
2912}
2913
Eric Laurent3b4529e2013-09-05 18:09:19 -07002914void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002915{
2916 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002917 // reject out of sequence requests
2918 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002919 // Register discontinuity when HW drain is completed because that can cause
2920 // the timestamp frame position to reset to 0 for direct and offload threads.
2921 // (Out of sequence requests are ignored, since the discontinuity would be handled
2922 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002923 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002924 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002925 mWaitWorkCV.signal();
2926 }
2927}
2928
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002929void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002930{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002931 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002932 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2933 mSampleRate = audioConfig.sample_rate;
2934 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002935 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002936 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002937 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002938 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07002939 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2940 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002941 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02002942
2943 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
2944 mMixerChannelMask = mChannelMask;
2945 }
2946
Andy Hunge5412692014-05-16 11:25:07 -07002947 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002948 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002949
Eric Laurentf1f22e72021-07-13 14:04:14 +02002950 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
2951
Phil Burkca5e6142015-07-14 09:42:29 -07002952 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002953 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002954 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002955 // Get format from the shim, which will be different than the HAL format
2956 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002957 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002958 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002959 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002960 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002961 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07002962 LOG_FATAL("HAL format %#x not supported for mixed output",
2963 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002964 }
Phil Burk062e67a2015-02-11 13:40:50 -08002965 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002966 result = mOutput->stream->getBufferSize(&mBufferSize);
2967 LOG_ALWAYS_FATAL_IF(result != OK,
2968 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002969 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02002970 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002971 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002972 mFrameCount);
2973 }
2974
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002975 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2976 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002977 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002978 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002979 }
2980 }
2981
Eric Laurentd1f69b02014-12-15 14:33:13 -08002982 mHwSupportsPause = false;
2983 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002984 bool supportsPause = false, supportsResume = false;
2985 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2986 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002987 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002988 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002989 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002990 } else if (supportsResume) {
2991 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002992 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002993 }
2994 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002995 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2996 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2997 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002998
Andy Hungfbfc3952015-01-15 13:33:51 -08002999 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3000 // For best precision, we use float instead of the associated output
3001 // device format (typically PCM 16 bit).
3002
3003 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3004 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3005 mBufferSize = mFrameSize * mFrameCount;
3006
3007 // TODO: We currently use the associated output device channel mask and sample rate.
3008 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3009 // (if a valid mask) to avoid premature downmix.
3010 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3011 // instead of the output device sample rate to avoid loss of high frequency information.
3012 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3013 }
3014
Andy Hung09a50072014-02-27 14:30:47 -08003015 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003016 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003017 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003018 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3019 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003020 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3021 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003022
Eric Laurent81784c32012-11-19 14:55:58 -08003023 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3024 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3025 maxNormalFrameCount = maxNormalFrameCount & ~15;
3026 if (maxNormalFrameCount < minNormalFrameCount) {
3027 maxNormalFrameCount = minNormalFrameCount;
3028 }
3029 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3030 if (multiplier <= 1.0) {
3031 multiplier = 1.0;
3032 } else if (multiplier <= 2.0) {
3033 if (2 * mFrameCount <= maxNormalFrameCount) {
3034 multiplier = 2.0;
3035 } else {
3036 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3037 }
3038 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003039 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003040 }
3041 }
3042 mNormalFrameCount = multiplier * mFrameCount;
3043 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003044 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003045 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3046 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003047 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003048 mNormalFrameCount);
3049
Andy Hung08fb1742015-05-31 23:22:10 -07003050 // Check if we want to throttle the processing to no more than 2x normal rate
3051 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003052 mThreadThrottleTimeMs = 0;
3053 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003054 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3055
Andy Hung010a1a12014-03-13 13:57:33 -07003056 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3057 // Originally this was int16_t[] array, need to remove legacy implications.
3058 free(mSinkBuffer);
3059 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003060
Andy Hung5b10a202014-03-13 13:59:29 -07003061 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3062 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3063 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003064 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003065
Andy Hung69aed5f2014-02-25 17:24:40 -08003066 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3067 // drives the output.
3068 free(mMixerBuffer);
3069 mMixerBuffer = NULL;
3070 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003071 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003072 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003073 * audio_bytes_per_sample(mMixerBufferFormat);
3074 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3075 }
Andy Hung98ef9782014-03-04 14:46:50 -08003076 free(mEffectBuffer);
3077 mEffectBuffer = NULL;
3078 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07003079 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003080 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003081 * audio_bytes_per_sample(mEffectBufferFormat);
3082 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3083 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003084
Eric Laurentb62d0362021-10-26 17:40:18 +02003085 if (mType == SPATIALIZER) {
3086 free(mPostSpatializerBuffer);
3087 mPostSpatializerBuffer = nullptr;
3088 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3089 * audio_bytes_per_sample(mEffectBufferFormat);
3090 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3091 }
3092
Mikhail Naganov55773032020-10-01 15:08:13 -07003093 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3094 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003095 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3096 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003097 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003098
Eric Laurent81784c32012-11-19 14:55:58 -08003099 // force reconfiguration of effect chains and engines to take new buffer size and audio
3100 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003101 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003102 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3103 // matter.
3104 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
3105 Vector< sp<EffectChain> > effectChains = mEffectChains;
3106 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07003107 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
3108 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003109 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003110
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003111 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003112 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003113 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3114 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3115 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3116 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3117 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3118 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3119 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3120 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3121 (int32_t)mHapticChannelMask)
3122 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3123 (int32_t)mHapticChannelCount)
3124 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3125 formatToString(mHALFormat).c_str())
3126 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3127 (int32_t)mFrameCount) // sic - added HAL
3128 ;
3129 uint32_t latencyMs;
3130 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3131 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3132 }
3133 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003134}
3135
Kevin Rocard069c2712018-03-29 19:09:14 -07003136void AudioFlinger::PlaybackThread::updateMetadata_l()
3137{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003138 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Kevin Rocard12381092018-04-11 09:19:59 -07003139 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003140 }
3141 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003142 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07003143 for (const sp<Track> &track : mActiveTracks) {
3144 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01003145 // Do not forward metadata for PatchTrack with unspecified stream type
3146 if (track->streamType() != AUDIO_STREAM_PATCH) {
3147 track->copyMetadataTo(backInserter);
3148 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003149 }
Kevin Rocard12381092018-04-11 09:19:59 -07003150 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00003151}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003152
Kevin Rocard12381092018-04-11 09:19:59 -07003153void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
3154 const StreamOutHalInterface::SourceMetadata& metadata)
3155{
3156 mOutput->stream->updateSourceMetadata(metadata);
3157};
3158
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003159status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08003160{
3161 if (halFrames == NULL || dspFrames == NULL) {
3162 return BAD_VALUE;
3163 }
3164 Mutex::Autolock _l(mLock);
3165 if (initCheck() != NO_ERROR) {
3166 return INVALID_OPERATION;
3167 }
Andy Hung818e7a32016-02-16 18:08:07 -08003168 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003169 *halFrames = framesWritten;
3170
3171 if (isSuspended()) {
3172 // return an estimation of rendered frames when the output is suspended
3173 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003174 *dspFrames = (uint32_t)
3175 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003176 return NO_ERROR;
3177 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003178 status_t status;
3179 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003180 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003181 *dspFrames = (size_t)frames;
3182 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003183 }
3184}
3185
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003186product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003187{
3188 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3189 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3190 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003191 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003192 }
3193 for (size_t i = 0; i < mTracks.size(); i++) {
3194 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003195 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003196 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003197 }
3198 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003199 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003200}
3201
3202
Phil Burk062e67a2015-02-11 13:40:50 -08003203AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003204{
3205 Mutex::Autolock _l(mLock);
3206 return mOutput;
3207}
3208
Phil Burk062e67a2015-02-11 13:40:50 -08003209AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003210{
3211 Mutex::Autolock _l(mLock);
3212 AudioStreamOut *output = mOutput;
3213 mOutput = NULL;
3214 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3215 // must push a NULL and wait for ack
3216 mOutputSink.clear();
3217 mPipeSink.clear();
3218 mNormalSink.clear();
3219 return output;
3220}
3221
3222// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003223sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003224{
3225 if (mOutput == NULL) {
3226 return NULL;
3227 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003228 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003229}
3230
3231uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3232{
3233 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3234}
3235
3236status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3237{
3238 if (!isValidSyncEvent(event)) {
3239 return BAD_VALUE;
3240 }
3241
3242 Mutex::Autolock _l(mLock);
3243
3244 for (size_t i = 0; i < mTracks.size(); ++i) {
3245 sp<Track> track = mTracks[i];
3246 if (event->triggerSession() == track->sessionId()) {
3247 (void) track->setSyncEvent(event);
3248 return NO_ERROR;
3249 }
3250 }
3251
3252 return NAME_NOT_FOUND;
3253}
3254
3255bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3256{
3257 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3258}
3259
3260void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3261 const Vector< sp<Track> >& tracksToRemove)
3262{
Andy Hungfe726a62018-09-27 15:17:25 -07003263 // Miscellaneous track cleanup when removed from the active list,
3264 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003265#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003266 for (const auto& track : tracksToRemove) {
3267 if (track->isExternalTrack()) {
3268 // to track the speaker usage
3269 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003270 }
3271 }
Andy Hungfe726a62018-09-27 15:17:25 -07003272#else
3273 (void)tracksToRemove; // suppress unused warning
3274#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003275}
3276
3277void AudioFlinger::PlaybackThread::checkSilentMode_l()
3278{
3279 if (!mMasterMute) {
3280 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003281 if (mOutDeviceTypeAddrs.empty()) {
3282 ALOGD("ro.audio.silent is ignored since no output device is set");
3283 return;
3284 }
jiabinc52b1ff2019-10-31 17:20:42 -07003285 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003286 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3287 return;
3288 }
Eric Laurent81784c32012-11-19 14:55:58 -08003289 if (property_get("ro.audio.silent", value, "0") > 0) {
3290 char *endptr;
3291 unsigned long ul = strtoul(value, &endptr, 0);
3292 if (*endptr == '\0' && ul != 0) {
3293 ALOGD("Silence is golden");
3294 // The setprop command will not allow a property to be changed after
3295 // the first time it is set, so we don't have to worry about un-muting.
3296 setMasterMute_l(true);
3297 }
3298 }
3299 }
3300}
3301
3302// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003303ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003304{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003305 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003306 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003307 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003308 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003309
3310 // If an NBAIO sink is present, use it to write the normal mixer's submix
3311 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003312
Andy Hung010a1a12014-03-13 13:57:33 -07003313 const size_t count = mBytesRemaining / mFrameSize;
3314
Simon Wilson2d590962012-11-29 15:18:50 -08003315 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003316 // update the setpoint when AudioFlinger::mScreenState changes
3317 uint32_t screenState = AudioFlinger::mScreenState;
3318 if (screenState != mScreenState) {
3319 mScreenState = screenState;
3320 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3321 if (pipe != NULL) {
3322 pipe->setAvgFrames((mScreenState & 1) ?
3323 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3324 }
3325 }
Andy Hung010a1a12014-03-13 13:57:33 -07003326 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003327 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003328 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003329 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003330#ifdef TEE_SINK
3331 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3332#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003333 } else {
3334 bytesWritten = framesWritten;
3335 }
3336 // otherwise use the HAL / AudioStreamOut directly
3337 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003338 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003339
Eric Laurentbfb1b832013-01-07 09:53:42 -08003340 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003341 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3342 mWriteAckSequence += 2;
3343 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003344 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003345 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003346 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003347 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003348 // FIXME We should have an implementation of timestamps for direct output threads.
3349 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003350 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003351 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003352
Eric Laurentbfb1b832013-01-07 09:53:42 -08003353 if (mUseAsyncWrite &&
3354 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3355 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003356 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003357 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003358 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003359 }
Eric Laurent81784c32012-11-19 14:55:58 -08003360 }
3361
Eric Laurent81784c32012-11-19 14:55:58 -08003362 mNumWrites++;
3363 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003364 if (mStandby) {
3365 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003366 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003367 mStandby = false;
3368 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003369 return bytesWritten;
3370}
3371
3372void AudioFlinger::PlaybackThread::threadLoop_drain()
3373{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003374 bool supportsDrain = false;
3375 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003376 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3377 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003378 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3379 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003380 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003381 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003382 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003383 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003384 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003385 }
3386}
3387
3388void AudioFlinger::PlaybackThread::threadLoop_exit()
3389{
Eric Laurent275e8e92014-11-30 15:14:47 -08003390 {
3391 Mutex::Autolock _l(mLock);
3392 for (size_t i = 0; i < mTracks.size(); i++) {
3393 sp<Track> track = mTracks[i];
3394 track->invalidate();
3395 }
Andy Hungdae27702016-10-31 14:01:16 -07003396 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3397 // After we exit there are no more track changes sent to BatteryNotifier
3398 // because that requires an active threadLoop.
3399 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3400 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003401 }
Eric Laurent81784c32012-11-19 14:55:58 -08003402}
3403
3404/*
3405The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003406 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003407 - mActiveSleepTimeUs from activeSleepTimeUs()
3408 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003409 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3410 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003411 - maxPeriod from frame count and sample rate (MIXER only)
3412
3413The parameters that affect these derived values are:
3414 - frame count
3415 - frame size
3416 - sample rate
3417 - device type: A2DP or not
3418 - device latency
3419 - format: PCM or not
3420 - active sleep time
3421 - idle sleep time
3422*/
3423
3424void AudioFlinger::PlaybackThread::cacheParameters_l()
3425{
Andy Hung25c2dac2014-02-27 14:56:00 -08003426 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003427 mActiveSleepTimeUs = activeSleepTimeUs();
3428 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003429
3430 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3431 // truncating audio when going to standby.
3432 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003433 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003434 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3435 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3436 }
3437 }
Eric Laurent81784c32012-11-19 14:55:58 -08003438}
3439
Eric Laurent13084622016-05-17 10:51:49 -07003440bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003441{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003442 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003443 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003444 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003445 size_t size = mTracks.size();
3446 for (size_t i = 0; i < size; i++) {
3447 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003448 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003449 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003450 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003451 }
3452 }
Eric Laurent13084622016-05-17 10:51:49 -07003453 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003454}
3455
Haynes Mathew George05317d22016-05-03 16:34:26 -07003456void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3457{
3458 Mutex::Autolock _l(mLock);
3459 invalidateTracks_l(streamType);
3460}
3461
jiabinf042b9b2021-05-07 23:46:28 +00003462// getTrackById_l must be called with holding thread lock
3463AudioFlinger::PlaybackThread::Track* AudioFlinger::PlaybackThread::getTrackById_l(
3464 audio_port_handle_t trackPortId) {
3465 for (size_t i = 0; i < mTracks.size(); i++) {
3466 if (mTracks[i]->portId() == trackPortId) {
3467 return mTracks[i].get();
3468 }
3469 }
3470 return nullptr;
3471}
3472
Eric Laurent81784c32012-11-19 14:55:58 -08003473status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3474{
Glenn Kastend848eb42016-03-08 13:42:11 -08003475 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003476 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003477 effect_buffer_t *buffer = nullptr; // only used for non global sessions
3478
Andy Hungd3639922022-04-28 18:00:49 -07003479 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003480 if (!audio_is_global_session(session)) {
3481 // player sessions on a spatializer output will use a dedicated input buffer and
3482 // will either output multi channel to mEffectBuffer if the track is spatilaized
3483 // or stereo to mPostSpatializerBuffer if not spatialized.
3484 uint32_t channelMask;
3485 bool isSessionSpatialized =
3486 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3487 if (isSessionSpatialized) {
3488 channelMask = mMixerChannelMask;
3489 } else {
3490 channelMask = mChannelMask;
3491 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003492 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003493 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003494 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003495 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003496 &halInBuffer);
3497 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003498
3499 result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3500 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3501 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3502 &halOutBuffer);
3503 if (result != OK) return result;
3504
rago94a1ee82017-07-21 15:11:02 -07003505#ifdef FLOAT_EFFECT_CHAIN
3506 buffer = halInBuffer->audioBuffer()->f32;
3507#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003508 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003509#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003510 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3511 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003512 } else {
3513 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3514 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3515 // mPostSpatializerBuffer as output buffer
3516 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
3517 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3518 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3519 if (result != OK) return result;
3520 result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3521 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3522 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003523
Eric Laurentb62d0362021-10-26 17:40:18 +02003524 if (session == AUDIO_SESSION_DEVICE) {
3525 halInBuffer = halOutBuffer;
3526 }
3527 }
3528 } else {
3529 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3530 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3531 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3532 &halInBuffer);
3533 if (result != OK) return result;
3534 halOutBuffer = halInBuffer;
3535 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3536 if (!audio_is_global_session(session)) {
3537 buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
3538 // Only one effect chain can be present in direct output thread and it uses
3539 // the sink buffer as input
3540 if (mType != DIRECT) {
3541 size_t numSamples = mNormalFrameCount
3542 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3543 + mHapticChannelCount);
3544 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
3545 numSamples * sizeof(effect_buffer_t),
3546 &halInBuffer);
3547 if (result != OK) return result;
3548#ifdef FLOAT_EFFECT_CHAIN
3549 buffer = halInBuffer->audioBuffer()->f32;
3550#else
3551 buffer = halInBuffer->audioBuffer()->s16;
3552#endif
3553 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3554 buffer, session);
3555 }
3556 }
3557 }
3558
3559 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003560 // Attach all tracks with same session ID to this chain.
3561 for (size_t i = 0; i < mTracks.size(); ++i) {
3562 sp<Track> track = mTracks[i];
3563 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003564 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3565 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003566 track->setMainBuffer(buffer);
3567 chain->incTrackCnt();
3568 }
3569 }
3570
3571 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003572 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003573 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003574 ALOGV("addEffectChain_l() activating track %p on session %d",
3575 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003576 chain->incActiveTrackCnt();
3577 }
3578 }
3579 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003580
Eric Laurentaaa44472014-09-12 17:41:50 -07003581 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003582 chain->setInBuffer(halInBuffer);
3583 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003584 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3585 // chains list in order to be processed last as it contains output device effects.
3586 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3587 // processing effects specific to an output stream before effects applied to all streams
3588 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003589 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3590 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003591 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003592 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003593 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003594 // Effect chain for other sessions are inserted at beginning of effect
3595 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003596 // sessions is not important.
3597 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003598 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3599 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003600 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003601 size_t size = mEffectChains.size();
3602 size_t i = 0;
3603 for (i = 0; i < size; i++) {
3604 if (mEffectChains[i]->sessionId() < session) {
3605 break;
3606 }
3607 }
3608 mEffectChains.insertAt(chain, i);
3609 checkSuspendOnAddEffectChain_l(chain);
3610
3611 return NO_ERROR;
3612}
3613
3614size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3615{
Glenn Kastend848eb42016-03-08 13:42:11 -08003616 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003617
3618 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3619
3620 for (size_t i = 0; i < mEffectChains.size(); i++) {
3621 if (chain == mEffectChains[i]) {
3622 mEffectChains.removeAt(i);
3623 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003624 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003625 if (session == track->sessionId()) {
3626 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3627 chain.get(), session);
3628 chain->decActiveTrackCnt();
3629 }
3630 }
3631
3632 // detach all tracks with same session ID from this chain
3633 for (size_t i = 0; i < mTracks.size(); ++i) {
3634 sp<Track> track = mTracks[i];
3635 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003636 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003637 chain->decTrackCnt();
3638 }
3639 }
3640 break;
3641 }
3642 }
3643 return mEffectChains.size();
3644}
3645
3646status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003647 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003648{
3649 Mutex::Autolock _l(mLock);
3650 return attachAuxEffect_l(track, EffectId);
3651}
3652
3653status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003654 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003655{
3656 status_t status = NO_ERROR;
3657
3658 if (EffectId == 0) {
3659 track->setAuxBuffer(0, NULL);
3660 } else {
3661 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3662 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3663 if (effect != 0) {
3664 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3665 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3666 } else {
3667 status = INVALID_OPERATION;
3668 }
3669 } else {
3670 status = BAD_VALUE;
3671 }
3672 }
3673 return status;
3674}
3675
3676void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3677{
3678 for (size_t i = 0; i < mTracks.size(); ++i) {
3679 sp<Track> track = mTracks[i];
3680 if (track->auxEffectId() == effectId) {
3681 attachAuxEffect_l(track, 0);
3682 }
3683 }
3684}
3685
3686bool AudioFlinger::PlaybackThread::threadLoop()
3687{
Glenn Kasten388d5712017-04-07 14:38:41 -07003688 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003689
Eric Laurent81784c32012-11-19 14:55:58 -08003690 Vector< sp<Track> > tracksToRemove;
3691
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003692 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003693 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003694
3695 // MIXER
3696 nsecs_t lastWarning = 0;
3697
3698 // DUPLICATING
3699 // FIXME could this be made local to while loop?
3700 writeFrames = 0;
3701
3702 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003703 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003704
Andy Hungd3639922022-04-28 18:00:49 -07003705 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003706 sleepTimeShift = 0;
3707 }
3708
3709 CpuStats cpuStats;
3710 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3711
3712 acquireWakeLock();
3713
Glenn Kasteneef598c2017-04-03 14:41:13 -07003714 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3715 // thread associated with this PlaybackThread.
3716 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3717 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003718 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3719 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003720 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003721 const char *logString = NULL;
3722
rago1bb90822017-05-02 18:31:48 -07003723 // Estimated time for next buffer to be written to hal. This is used only on
3724 // suspended mode (for now) to help schedule the wait time until next iteration.
3725 nsecs_t timeLoopNextNs = 0;
3726
Eric Laurent664539d2013-09-23 18:24:31 -07003727 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003728
Andy Hung2dbffc22018-08-08 18:50:41 -07003729 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003730
Eric Laurentb3f315a2021-07-13 15:09:05 +02003731 sendCheckOutputStageEffectsEvent();
3732
Andy Hung446f4df2019-02-21 12:26:41 -08003733 // loopCount is used for statistics and diagnostics.
3734 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003735 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003736 // Log merge requests are performed during AudioFlinger binder transactions, but
3737 // that does not cover audio playback. It's requested here for that reason.
3738 mAudioFlinger->requestLogMerge();
3739
Eric Laurent81784c32012-11-19 14:55:58 -08003740 cpuStats.sample(myName);
3741
3742 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003743 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003744 bool isHapticSessionSpatialized = false;
Andy Hungc1646382019-04-30 16:12:10 -07003745 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003746
Andy Hung2dbffc22018-08-08 18:50:41 -07003747 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3748 //
jiabinc52b1ff2019-10-31 17:20:42 -07003749 // Note: we access outDeviceTypes() outside of mLock.
3750 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003751 // Here, we try for the AF lock, but do not block on it as the latency
3752 // is more informational.
3753 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3754 std::vector<PatchPanel::SoftwarePatch> swPatches;
3755 double latencyMs;
3756 status_t status = INVALID_OPERATION;
3757 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3758 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3759 && swPatches.size() > 0) {
3760 status = swPatches[0].getLatencyMs_l(&latencyMs);
3761 downstreamPatchHandle = swPatches[0].getPatchHandle();
3762 }
3763 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003764 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003765 lastDownstreamPatchHandle = downstreamPatchHandle;
3766 }
3767 if (status == OK) {
3768 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003769 // latency of 5 seconds).
3770 const double minLatency = 0., maxLatency = 5000.;
3771 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003772 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003773 } else {
3774 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003775 if (latencyMs < minLatency) latencyMs = minLatency;
3776 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003777 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003778 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003779 }
3780 mAudioFlinger->mLock.unlock();
3781 }
3782 } else {
3783 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3784 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003785 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003786 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3787 }
3788 }
3789
Eric Laurentb3f315a2021-07-13 15:09:05 +02003790 if (mCheckOutputStageEffects.exchange(false)) {
3791 checkOutputStageEffects();
3792 }
3793
Eric Laurent81784c32012-11-19 14:55:58 -08003794 { // scope for mLock
3795
3796 Mutex::Autolock _l(mLock);
3797
Eric Laurent021cf962014-05-13 10:18:14 -07003798 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003799 if (mCheckOutputStageEffects.load()) {
3800 continue;
3801 }
Eric Laurent10351942014-05-08 18:49:52 -07003802
Glenn Kasteneef598c2017-04-03 14:41:13 -07003803 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003804 if (logString != NULL) {
3805 mNBLogWriter->logTimestamp();
3806 mNBLogWriter->log(logString);
3807 logString = NULL;
3808 }
3809
Dean Wheatley12473e92021-03-18 23:00:55 +11003810 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003811
Eric Laurent81784c32012-11-19 14:55:58 -08003812 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003813 if (mSignalPending) {
3814 // A signal was raised while we were unlocked
3815 mSignalPending = false;
3816 } else if (waitingAsyncCallback_l()) {
3817 if (exitPending()) {
3818 break;
3819 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003820 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003821 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003822 releaseWakeLock_l();
3823 released = true;
3824 }
Andy Hung10cbff12017-02-21 17:30:14 -08003825
3826 const int64_t waitNs = computeWaitTimeNs_l();
3827 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3828 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3829 if (status == TIMED_OUT) {
3830 mSignalPending = true; // if timeout recheck everything
3831 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003832 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003833 if (released) {
3834 acquireWakeLock_l();
3835 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003836 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3837 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003838
3839 continue;
3840 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003841 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003842 isSuspended()) {
3843 // put audio hardware into standby after short delay
3844 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003845
3846 threadLoop_standby();
3847
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003848 // This is where we go into standby
3849 if (!mStandby) {
3850 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003851 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003852 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07003853 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003854 }
Andy Hungd0979812019-02-21 15:51:44 -08003855 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003856 }
3857
Eric Tan39ec8d62018-07-24 09:49:29 -07003858 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003859 // we're about to wait, flush the binder command buffer
3860 IPCThreadState::self()->flushCommands();
3861
3862 clearOutputTracks();
3863
3864 if (exitPending()) {
3865 break;
3866 }
3867
3868 releaseWakeLock_l();
3869 // wait until we have something to do...
3870 ALOGV("%s going to sleep", myName.string());
3871 mWaitWorkCV.wait(mLock);
3872 ALOGV("%s waking up", myName.string());
3873 acquireWakeLock_l();
3874
3875 mMixerStatus = MIXER_IDLE;
3876 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3877 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003878 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003879 checkSilentMode_l();
3880
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003881 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3882 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07003883 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003884 sleepTimeShift = 0;
3885 }
3886
3887 continue;
3888 }
3889 }
Eric Laurent81784c32012-11-19 14:55:58 -08003890 // mMixerStatusIgnoringFastTracks is also updated internally
3891 mMixerStatus = prepareTracks_l(&tracksToRemove);
3892
Andy Hungdae27702016-10-31 14:01:16 -07003893 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003894
Kevin Rocard069c2712018-03-29 19:09:14 -07003895 updateMetadata_l();
3896
Eric Laurent81784c32012-11-19 14:55:58 -08003897 // prevent any changes in effect chain list and in each effect chain
3898 // during mixing and effect process as the audio buffers could be deleted
3899 // or modified if an effect is created or deleted
3900 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003901
3902 // Determine which session to pick up haptic data.
3903 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003904 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003905 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02003906 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07003907 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003908 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02003909 if (effectChain != nullptr
3910 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07003911 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02003912 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02003913 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07003914 break;
3915 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003916 if (activeHapticSessionId == AUDIO_SESSION_NONE
3917 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07003918 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02003919 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02003920 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07003921 }
3922 }
3923 }
3924
Andy Hungc1646382019-04-30 16:12:10 -07003925 // Acquire a local copy of active tracks with lock (release w/o lock).
3926 //
3927 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3928 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3929 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3930 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003931 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003932
Eric Laurentbfb1b832013-01-07 09:53:42 -08003933 if (mBytesRemaining == 0) {
3934 mCurrentWriteLength = 0;
3935 if (mMixerStatus == MIXER_TRACKS_READY) {
3936 // threadLoop_mix() sets mCurrentWriteLength
3937 threadLoop_mix();
3938 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3939 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003940 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003941 // must be written to HAL
3942 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003943 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003944 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003945
3946 // Tally underrun frames as we are inserting 0s here.
3947 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003948 if (track->mFillingUpStatus == Track::FS_ACTIVE
3949 && !track->isStopped()
3950 && !track->isPaused()
3951 && !track->isTerminated()) {
3952 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3953 __func__, track->id(), track->getTrackStateAsString(),
3954 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003955 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3956 }
3957 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003958 }
3959 }
Andy Hung98ef9782014-03-04 14:46:50 -08003960 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003961 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003962 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3963 // or mSinkBuffer (if there are no effects).
3964 //
3965 // This is done pre-effects computation; if effects change to
3966 // support higher precision, this needs to move.
3967 //
3968 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003969 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02003970 uint32_t mixerChannelCount = mEffectBufferValid ?
3971 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
Andy Hung98ef9782014-03-04 14:46:50 -08003972 if (mMixerBufferValid) {
3973 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3974 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3975
Andy Hung2ddee192015-12-18 17:34:44 -08003976 // mono blend occurs for mixer threads only (not direct or offloaded)
3977 // and is handled here if we're going directly to the sink.
3978 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003979 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3980 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003981 }
3982
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003983 if (!hasFastMixer()) {
3984 // Balance must take effect after mono conversion.
3985 // We do it here if there is no FastMixer.
3986 // mBalance detects zero balance within the class for speed (not needed here).
3987 mBalance.setBalance(mMasterBalance.load());
3988 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3989 }
3990
Andy Hung98ef9782014-03-04 14:46:50 -08003991 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02003992 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08003993
3994 // If we're going directly to the sink and there are haptic channels,
3995 // we should adjust channels as the sample data is partially interleaved
3996 // in this case.
3997 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3998 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3999 mChannelCount + mHapticChannelCount,
4000 audio_bytes_per_sample(format),
4001 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4002 }
Andy Hung98ef9782014-03-04 14:46:50 -08004003 }
4004
Eric Laurentbfb1b832013-01-07 09:53:42 -08004005 mBytesRemaining = mCurrentWriteLength;
4006 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004007 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4008 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4009 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4010 mBytesWritten += mBytesRemaining;
4011 mFramesWritten += framesRemaining;
4012 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004013 mBytesRemaining = 0;
4014 }
Eric Laurent81784c32012-11-19 14:55:58 -08004015
Eric Laurentbfb1b832013-01-07 09:53:42 -08004016 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004017 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004018 for (size_t i = 0; i < effectChains.size(); i ++) {
4019 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004020 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004021 if (activeHapticSessionId != AUDIO_SESSION_NONE
4022 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004023 // Haptic data is active in this case, copy it directly from
4024 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004025 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4026 audio_channel_count_from_out_mask(mMixerChannelMask) :
4027 mChannelCount;
4028 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4029 hapticSessionChannelCount = mChannelCount;
4030 }
4031
jiabin47affe52019-04-04 18:02:07 -07004032 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004033 * audio_bytes_per_frame(hapticSessionChannelCount,
4034 EFFECT_BUFFER_FORMAT);
jiabin47affe52019-04-04 18:02:07 -07004035 memcpy_by_audio_format(
4036 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
4037 EFFECT_BUFFER_FORMAT,
4038 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
4039 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
4040 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004041 }
Eric Laurent81784c32012-11-19 14:55:58 -08004042 }
4043 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004044 // Process effect chains for offloaded thread even if no audio
4045 // was read from audio track: process only updates effect state
4046 // and thus does have to be synchronized with audio writes but may have
4047 // to be called while waiting for async write callback
4048 if (mType == OFFLOAD) {
4049 for (size_t i = 0; i < effectChains.size(); i ++) {
4050 effectChains[i]->process_l();
4051 }
4052 }
Eric Laurent81784c32012-11-19 14:55:58 -08004053
Andy Hung98ef9782014-03-04 14:46:50 -08004054 // Only if the Effects buffer is enabled and there is data in the
4055 // Effects buffer (buffer valid), we need to
4056 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004057 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08004058 if (mEffectBufferValid) {
4059 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004060 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004061 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004062 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004063 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004064 }
4065
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004066 if (!hasFastMixer()) {
4067 // Balance must take effect after mono conversion.
4068 // We do it here if there is no FastMixer.
4069 // mBalance detects zero balance within the class for speed (not needed here).
4070 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004071 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004072 }
4073
Eric Laurentb62d0362021-10-26 17:40:18 +02004074 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4075 // mPostSpatializerBuffer if the haptics track is spatialized.
4076 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4077 // For other thread types, the haptics channels are already in mEffectBuffer.
4078 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4079 const size_t srcBufferSize = mNormalFrameCount *
4080 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4081 mEffectBufferFormat);
4082 const size_t dstBufferSize = mNormalFrameCount
4083 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4084
4085 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4086 mEffectBufferFormat,
4087 (uint8_t*)mEffectBuffer + srcBufferSize,
4088 mEffectBufferFormat,
4089 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004090 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004091
4092 memcpy_by_audio_format(mSinkBuffer, mFormat, effectBuffer, mEffectBufferFormat,
4093 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
4094
jiabin245cdd92018-12-07 17:55:15 -08004095 // The sample data is partially interleaved when haptic channels exist,
4096 // we need to adjust channels here.
4097 if (mHapticChannelCount > 0) {
4098 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4099 mChannelCount + mHapticChannelCount,
4100 audio_bytes_per_sample(mFormat),
4101 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4102 }
Andy Hung98ef9782014-03-04 14:46:50 -08004103 }
4104
Eric Laurent81784c32012-11-19 14:55:58 -08004105 // enable changes in effect chain
4106 unlockEffectChains(effectChains);
4107
Eric Laurentbfb1b832013-01-07 09:53:42 -08004108 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004109 // mSleepTimeUs == 0 means we must write to audio hardware
4110 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004111 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004112 // writePeriodNs is updated >= 0 when ret > 0.
4113 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004114 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004115 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004116 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004117 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004118 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004119 if (ret < 0) {
4120 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004121 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004122 mBytesWritten += ret;
4123 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004124 const int64_t frames = ret / mFrameSize;
4125 mFramesWritten += frames;
4126
4127 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4128 // process information relating to write time.
4129 if (audio_has_proportional_frames(mFormat)) {
4130 // we are in a continuous mixing cycle
4131 if (mMixerStatus == MIXER_TRACKS_READY &&
4132 loopCount == lastLoopCountWritten + 1) {
4133
4134 const double jitterMs =
4135 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4136 {frames, writePeriodNs},
4137 {0, 0} /* lastTimestamp */, mSampleRate);
4138 const double processMs =
4139 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4140
4141 Mutex::Autolock _l(mLock);
4142 mIoJitterMs.add(jitterMs);
4143 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004144
4145 if (mPipeSink.get() != nullptr) {
4146 // Using the Monopipe availableToWrite, we estimate the current
4147 // buffer size.
4148 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4149 const ssize_t
4150 availableToWrite = mPipeSink->availableToWrite();
4151 const size_t pipeFrames = monoPipe->maxFrames();
4152 const size_t
4153 remainingFrames = pipeFrames - max(availableToWrite, 0);
4154 mMonopipePipeDepthStats.add(remainingFrames);
4155 }
Andy Hung446f4df2019-02-21 12:26:41 -08004156 }
4157
4158 // write blocked detection
4159 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004160 if ((mType == MIXER || mType == SPATIALIZER)
4161 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004162 mNumDelayedWrites++;
4163 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4164 ATRACE_NAME("underrun");
4165 ALOGW("write blocked for %lld msecs, "
4166 "%d delayed writes, thread %d",
4167 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4168 mNumDelayedWrites, mId);
4169 lastWarning = lastIoEndNs;
4170 }
4171 }
4172 }
4173 // update timing info.
4174 mLastIoBeginNs = lastIoBeginNs;
4175 mLastIoEndNs = lastIoEndNs;
4176 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004177 }
4178 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4179 (mMixerStatus == MIXER_DRAIN_ALL)) {
4180 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004181 }
Andy Hungd3639922022-04-28 18:00:49 -07004182 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004183
4184 if (mThreadThrottle
4185 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004186 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004187 // Limit MixerThread data processing to no more than twice the
4188 // expected processing rate.
4189 //
4190 // This helps prevent underruns with NuPlayer and other applications
4191 // which may set up buffers that are close to the minimum size, or use
4192 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4193 //
4194 // The throttle smooths out sudden large data drains from the device,
4195 // e.g. when it comes out of standby, which often causes problems with
4196 // (1) mixer threads without a fast mixer (which has its own warm-up)
4197 // (2) minimum buffer sized tracks (even if the track is full,
4198 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004199 //
4200 // Total time spent in last processing cycle equals time spent in
4201 // 1. threadLoop_write, as well as time spent in
4202 // 2. threadLoop_mix (significant for heavy mixing, especially
4203 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004204
Andy Hung446f4df2019-02-21 12:26:41 -08004205 // it's OK if deltaMs is an overestimate.
4206
4207 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004208
Ivan Lozanoea04d392017-11-07 14:37:07 -08004209 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004210 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004211 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004212
Andy Hung08fb1742015-05-31 23:22:10 -07004213 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004214 // notify of throttle start on verbose log
4215 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4216 "mixer(%p) throttle begin:"
4217 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004218 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004219 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004220 // Throttle must be attributed to the previous mixer loop's write time
4221 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004222 // This also ensures proper timing statistics.
4223 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004224 } else {
4225 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4226 if (diff > 0) {
4227 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004228 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004229 ALOGD_IF(!isSingleDeviceType(
4230 outDeviceTypes(), audio_is_a2dp_out_device) &&
4231 !isSingleDeviceType(
4232 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004233 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004234 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4235 }
Andy Hung08fb1742015-05-31 23:22:10 -07004236 }
4237 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004238 }
Eric Laurent81784c32012-11-19 14:55:58 -08004239
Eric Laurentbfb1b832013-01-07 09:53:42 -08004240 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004241 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004242 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004243 // suspended requires accurate metering of sleep time.
4244 if (isSuspended()) {
4245 // advance by expected sleepTime
4246 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4247 const nsecs_t nowNs = systemTime();
4248
4249 // compute expected next time vs current time.
4250 // (negative deltas are treated as delays).
4251 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4252 if (deltaNs < -kMaxNextBufferDelayNs) {
4253 // Delays longer than the max allowed trigger a reset.
4254 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4255 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4256 timeLoopNextNs = nowNs + deltaNs;
4257 } else if (deltaNs < 0) {
4258 // Delays within the max delay allowed: zero the delta/sleepTime
4259 // to help the system catch up in the next iteration(s)
4260 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4261 deltaNs = 0;
4262 }
4263 // update sleep time (which is >= 0)
4264 mSleepTimeUs = deltaNs / 1000;
4265 }
Eric Laurente93cc032016-05-05 10:15:10 -07004266 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4267 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004268 }
Glenn Kastene7754022014-10-31 12:11:26 -07004269 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004270 }
Eric Laurent81784c32012-11-19 14:55:58 -08004271 }
4272
4273 // Finally let go of removed track(s), without the lock held
4274 // since we can't guarantee the destructors won't acquire that
4275 // same lock. This will also mutate and push a new fast mixer state.
4276 threadLoop_removeTracks(tracksToRemove);
4277 tracksToRemove.clear();
4278
4279 // FIXME I don't understand the need for this here;
4280 // it was in the original code but maybe the
4281 // assignment in saveOutputTracks() makes this unnecessary?
4282 clearOutputTracks();
4283
4284 // Effect chains will be actually deleted here if they were removed from
4285 // mEffectChains list during mixing or effects processing
4286 effectChains.clear();
4287
4288 // FIXME Note that the above .clear() is no longer necessary since effectChains
4289 // is now local to this block, but will keep it for now (at least until merge done).
4290 }
4291
Eric Laurentbfb1b832013-01-07 09:53:42 -08004292 threadLoop_exit();
4293
Eric Laurentcf817a22014-08-04 20:36:31 -07004294 if (!mStandby) {
4295 threadLoop_standby();
4296 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004297 }
4298
4299 releaseWakeLock();
4300
4301 ALOGV("Thread %p type %d exiting", this, mType);
4302 return false;
4303}
4304
Dean Wheatley12473e92021-03-18 23:00:55 +11004305void AudioFlinger::PlaybackThread::collectTimestamps_l()
4306{
Dean Wheatley12473e92021-03-18 23:00:55 +11004307 if (mStandby) {
4308 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4309 return;
4310 } else if (mHwPaused) {
4311 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4312 return;
4313 }
4314
4315 // Gather the framesReleased counters for all active tracks,
4316 // and associate with the sink frames written out. We need
4317 // this to convert the sink timestamp to the track timestamp.
4318 bool kernelLocationUpdate = false;
4319 ExtendedTimestamp timestamp; // use private copy to fetch
4320
4321 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4322 // HAL may be draining some small duration buffered data for fade out.
4323 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4324 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4325 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4326 mSampleRate);
4327
4328 if (isTimestampCorrectionEnabled()) {
4329 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4330 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4331 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4332 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4333 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4334 = correctedTimestamp.mFrames;
4335 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4336 = correctedTimestamp.mTimeNs;
4337 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4338 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4339 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4340
4341 // Note: Downstream latency only added if timestamp correction enabled.
4342 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4343 const int64_t newPosition =
4344 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4345 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4346 // prevent retrograde
4347 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4348 newPosition,
4349 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4350 - mSuspendedFrames));
4351 }
4352 }
4353
4354 // We always fetch the timestamp here because often the downstream
4355 // sink will block while writing.
4356
4357 // We keep track of the last valid kernel position in case we are in underrun
4358 // and the normal mixer period is the same as the fast mixer period, or there
4359 // is some error from the HAL.
4360 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4361 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4362 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4363 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4364 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4365
4366 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4367 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4368 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4369 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4370 }
4371
4372 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4373 kernelLocationUpdate = true;
4374 } else {
4375 ALOGVV("getTimestamp error - no valid kernel position");
4376 }
4377
4378 // copy over kernel info
4379 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4380 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4381 + mSuspendedFrames; // add frames discarded when suspended
4382 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4383 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4384 } else {
4385 mTimestampVerifier.error();
4386 }
4387
4388 // mFramesWritten for non-offloaded tracks are contiguous
4389 // even after standby() is called. This is useful for the track frame
4390 // to sink frame mapping.
4391 bool serverLocationUpdate = false;
4392 if (mFramesWritten != mLastFramesWritten) {
4393 serverLocationUpdate = true;
4394 mLastFramesWritten = mFramesWritten;
4395 }
4396 // Only update timestamps if there is a meaningful change.
4397 // Either the kernel timestamp must be valid or we have written something.
4398 if (kernelLocationUpdate || serverLocationUpdate) {
4399 if (serverLocationUpdate) {
4400 // use the time before we called the HAL write - it is a bit more accurate
4401 // to when the server last read data than the current time here.
4402 //
4403 // If we haven't written anything, mLastIoBeginNs will be -1
4404 // and we use systemTime().
4405 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4406 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4407 ? systemTime() : mLastIoBeginNs;
4408 }
4409
4410 for (const sp<Track> &t : mActiveTracks) {
4411 if (!t->isFastTrack()) {
4412 t->updateTrackFrameInfo(
4413 t->mAudioTrackServerProxy->framesReleased(),
4414 mFramesWritten,
4415 mSampleRate,
4416 mTimestamp);
4417 }
4418 }
4419 }
4420
4421 if (audio_has_proportional_frames(mFormat)) {
4422 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4423 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4424 mLatencyMs.add(latencyMs);
4425 }
4426 }
4427#if 0
4428 // logFormat example
4429 if (z % 100 == 0) {
4430 timespec ts;
4431 clock_gettime(CLOCK_MONOTONIC, &ts);
4432 LOGT("This is an integer %d, this is a float %f, this is my "
4433 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4434 LOGT("A deceptive null-terminated string %\0");
4435 }
4436 ++z;
4437#endif
4438}
4439
Eric Laurentbfb1b832013-01-07 09:53:42 -08004440// removeTracks_l() must be called with ThreadBase::mLock held
4441void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4442{
Andy Hungfe726a62018-09-27 15:17:25 -07004443 for (const auto& track : tracksToRemove) {
4444 mActiveTracks.remove(track);
4445 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4446 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4447 if (chain != 0) {
4448 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4449 __func__, track->id(), chain.get(), track->sessionId());
4450 chain->decActiveTrackCnt();
4451 }
4452 // If an external client track, inform APM we're no longer active, and remove if needed.
4453 // We do this under lock so that the state is consistent if the Track is destroyed.
4454 if (track->isExternalTrack()) {
4455 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004456 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004457 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004458 }
4459 }
Andy Hungfe726a62018-09-27 15:17:25 -07004460 if (track->isTerminated()) {
4461 // remove from our tracks vector
4462 removeTrack_l(track);
4463 }
jiabineb3bda02020-06-30 14:07:03 -07004464 if (mHapticChannelCount > 0 &&
4465 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4466 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004467 mLock.unlock();
4468 // Unlock due to VibratorService will lock for this call and will
4469 // call Tracks.mute/unmute which also require thread's lock.
4470 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4471 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004472
4473 // When the track is stop, set the haptic intensity as MUTE
4474 // for the HapticGenerator effect.
4475 if (chain != nullptr) {
4476 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4477 }
jiabin245cdd92018-12-07 17:55:15 -08004478 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004479 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004480}
Eric Laurent81784c32012-11-19 14:55:58 -08004481
Eric Laurentaccc1472013-09-20 09:36:34 -07004482status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4483{
4484 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004485 ExtendedTimestamp ets;
4486 status_t status = mNormalSink->getTimestamp(ets);
4487 if (status == NO_ERROR) {
4488 status = ets.getBestTimestamp(&timestamp);
4489 }
4490 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004491 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004492 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004493 collectTimestamps_l();
4494 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4495 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004496 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004497 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4498 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4499 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4500 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4501 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004502 }
4503 return INVALID_OPERATION;
4504}
Eric Laurent1c333e22014-05-20 10:48:17 -07004505
Eric Laurenteab90452019-06-24 15:17:46 -07004506// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4507// still applied by the mixer.
4508// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4509// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4510// if more than one track are active
4511status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4512{
4513 status_t result = NO_ERROR;
4514 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4515 if (*volume != mLeftVolFloat) {
4516 result = mOutput->stream->setVolume(*volume, *volume);
4517 ALOGE_IF(result != OK,
4518 "Error when setting output stream volume: %d", result);
4519 if (result == NO_ERROR) {
4520 mLeftVolFloat = *volume;
4521 }
4522 }
4523 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4524 // remove stream volume contribution from software volume.
4525 if (mLeftVolFloat == *volume) {
4526 *volume = 1.0f;
4527 }
4528 }
4529 return result;
4530}
4531
Eric Laurent054d9d32015-04-24 08:48:48 -07004532status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4533 audio_patch_handle_t *handle)
4534{
Andy Hungf60abce2016-08-26 11:37:54 -07004535 status_t status;
4536 if (property_get_bool("af.patch_park", false /* default_value */)) {
4537 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4538 // or if HAL does not properly lock against access.
4539 AutoPark<FastMixer> park(mFastMixer);
4540 status = PlaybackThread::createAudioPatch_l(patch, handle);
4541 } else {
4542 status = PlaybackThread::createAudioPatch_l(patch, handle);
4543 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004544 return status;
4545}
4546
Eric Laurent1c333e22014-05-20 10:48:17 -07004547status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4548 audio_patch_handle_t *handle)
4549{
4550 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004551
4552 // store new device and send to effects
4553 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004554 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004555 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004556 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4557 && !mOutput->audioHwDev->supportsAudioPatches(),
4558 "Enumerated device type(%#x) must not be used "
4559 "as it does not support audio patches",
4560 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004561 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07004562 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4563 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004564 }
4565
François Gaffie0c280aa2018-07-25 10:02:15 +02004566 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004567#ifdef ADD_BATTERY_DATA
4568 // when changing the audio output device, call addBatteryData to notify
4569 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004570 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004571 uint32_t params = 0;
4572 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004573 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004574 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004575 }
4576
Eric Laurent054d9d32015-04-24 08:48:48 -07004577 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004578 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004579 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4580 }
4581
4582 if (params != 0) {
4583 addBatteryData(params);
4584 }
4585 }
4586#endif
4587
4588 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004589 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004590 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004591
jiabinc52b1ff2019-10-31 17:20:42 -07004592 // mPatch.num_sinks is not set when the thread is created so that
4593 // the first patch creation triggers an ioConfigChanged callback
4594 bool configChanged = (mPatch.num_sinks == 0) ||
4595 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004596 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004597 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004598 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004599
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004600 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004601 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4602 status = hwDevice->createAudioPatch(patch->num_sources,
4603 patch->sources,
4604 patch->num_sinks,
4605 patch->sinks,
4606 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004607 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004608 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004609 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004610 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004611 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004612
4613 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004614 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004615 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004616 // also dispatch to active AudioTracks for MediaMetrics
4617 for (const auto &track : mActiveTracks) {
4618 track->logEndInterval();
4619 track->logBeginInterval(patchSinksAsString);
4620 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004621
Eric Laurente8726fe2015-06-26 09:39:24 -07004622 if (configChanged) {
4623 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4624 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004625 return status;
4626}
4627
Eric Laurent054d9d32015-04-24 08:48:48 -07004628status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4629{
Andy Hungf60abce2016-08-26 11:37:54 -07004630 status_t status;
4631 if (property_get_bool("af.patch_park", false /* default_value */)) {
4632 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4633 // or if HAL does not properly lock against access.
4634 AutoPark<FastMixer> park(mFastMixer);
4635 status = PlaybackThread::releaseAudioPatch_l(handle);
4636 } else {
4637 status = PlaybackThread::releaseAudioPatch_l(handle);
4638 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004639 return status;
4640}
4641
Eric Laurent1c333e22014-05-20 10:48:17 -07004642status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4643{
4644 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004645
jiabinc52b1ff2019-10-31 17:20:42 -07004646 mPatch = audio_patch{};
4647 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004648
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004649 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004650 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4651 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004652 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004653 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004654 }
4655 return status;
4656}
4657
Eric Laurent83b88082014-06-20 18:31:16 -07004658void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4659{
4660 Mutex::Autolock _l(mLock);
4661 mTracks.add(track);
4662}
4663
4664void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4665{
4666 Mutex::Autolock _l(mLock);
4667 destroyTrack_l(track);
4668}
4669
Mikhail Naganovdc769682018-05-04 15:34:08 -07004670void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004671{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004672 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004673 config->role = AUDIO_PORT_ROLE_SOURCE;
4674 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4675 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004676 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4677 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4678 config->flags.output = mOutput->flags;
4679 }
Eric Laurent83b88082014-06-20 18:31:16 -07004680}
4681
Eric Laurent81784c32012-11-19 14:55:58 -08004682// ----------------------------------------------------------------------------
4683
4684AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004685 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
4686 : PlaybackThread(audioFlinger, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004687 // mAudioMixer below
4688 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004689 mFastMixerFutex(0),
4690 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004691 // mOutputSink below
4692 // mPipeSink below
4693 // mNormalSink below
4694{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004695 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004696 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004697 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004698 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004699 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4700 mNormalFrameCount);
4701 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4702
Andy Hungfbfc3952015-01-15 13:33:51 -08004703 if (type == DUPLICATING) {
4704 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4705 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4706 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4707 return;
4708 }
Eric Laurent81784c32012-11-19 14:55:58 -08004709 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004710 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004711 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004712 const NBAIO_Format offers[1] = {Format_from_SR_C(
4713 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004714#if !LOG_NDEBUG
4715 ssize_t index =
4716#else
4717 (void)
4718#endif
4719 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004720 ALOG_ASSERT(index == 0);
4721
4722 // initialize fast mixer depending on configuration
4723 bool initFastMixer;
Eric Laurentb62d0362021-10-26 17:40:18 +02004724 if (mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004725 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004726 } else {
4727 switch (kUseFastMixer) {
4728 case FastMixer_Never:
4729 initFastMixer = false;
4730 break;
4731 case FastMixer_Always:
4732 initFastMixer = true;
4733 break;
4734 case FastMixer_Static:
4735 case FastMixer_Dynamic:
4736 initFastMixer = mFrameCount < mNormalFrameCount;
4737 break;
4738 }
4739 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4740 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4741 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004742 }
4743 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004744 audio_format_t fastMixerFormat;
4745 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4746 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4747 } else {
4748 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4749 }
4750 if (mFormat != fastMixerFormat) {
4751 // change our Sink format to accept our intermediate precision
4752 mFormat = fastMixerFormat;
4753 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004754 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004755 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4756 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4757 }
Eric Laurent81784c32012-11-19 14:55:58 -08004758
4759 // create a MonoPipe to connect our submix to FastMixer
4760 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004761
Andy Hung1258c1a2014-05-23 21:22:17 -07004762 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004763 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004764 format.mFormat = fastMixerFormat;
4765 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4766
Eric Laurent81784c32012-11-19 14:55:58 -08004767 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4768 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4769 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4770 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4771 const NBAIO_Format offers[1] = {format};
4772 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004773#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004774 ssize_t index =
4775#else
4776 (void)
4777#endif
4778 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004779 ALOG_ASSERT(index == 0);
4780 monoPipe->setAvgFrames((mScreenState & 1) ?
4781 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4782 mPipeSink = monoPipe;
4783
Eric Laurent81784c32012-11-19 14:55:58 -08004784 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004785 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004786 FastMixerStateQueue *sq = mFastMixer->sq();
4787#ifdef STATE_QUEUE_DUMP
4788 sq->setObserverDump(&mStateQueueObserverDump);
4789 sq->setMutatorDump(&mStateQueueMutatorDump);
4790#endif
4791 FastMixerState *state = sq->begin();
4792 FastTrack *fastTrack = &state->mFastTracks[0];
4793 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4794 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4795 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004796 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4797 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4798 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004799 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004800 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004801 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01004802 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08004803 fastTrack->mGeneration++;
4804 state->mFastTracksGen++;
4805 state->mTrackMask = 1;
4806 // fast mixer will use the HAL output sink
4807 state->mOutputSink = mOutputSink.get();
4808 state->mOutputSinkGen++;
4809 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004810 // specify sink channel mask when haptic channel mask present as it can not
4811 // be calculated directly from channel count
4812 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004813 ? AUDIO_CHANNEL_NONE
4814 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004815 state->mCommand = FastMixerState::COLD_IDLE;
4816 // already done in constructor initialization list
4817 //mFastMixerFutex = 0;
4818 state->mColdFutexAddr = &mFastMixerFutex;
4819 state->mColdGen++;
4820 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004821 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4822 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004823 sq->end();
4824 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4825
Eric Tan0513b5d2018-09-17 10:32:48 -07004826 NBLog::thread_info_t info;
4827 info.id = mId;
4828 info.type = NBLog::FASTMIXER;
4829 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4830
Eric Laurent81784c32012-11-19 14:55:58 -08004831 // start the fast mixer
4832 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4833 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004834 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004835 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004836
4837#ifdef AUDIO_WATCHDOG
4838 // create and start the watchdog
4839 mAudioWatchdog = new AudioWatchdog();
4840 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4841 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4842 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004843 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004844#endif
Andy Hung8946a282018-04-19 20:04:56 -07004845 } else {
4846#ifdef TEE_SINK
4847 // Only use the MixerThread tee if there is no FastMixer.
4848 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4849 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4850#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004851 }
4852
4853 switch (kUseFastMixer) {
4854 case FastMixer_Never:
4855 case FastMixer_Dynamic:
4856 mNormalSink = mOutputSink;
4857 break;
4858 case FastMixer_Always:
4859 mNormalSink = mPipeSink;
4860 break;
4861 case FastMixer_Static:
4862 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4863 break;
4864 }
4865}
4866
4867AudioFlinger::MixerThread::~MixerThread()
4868{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004869 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004870 FastMixerStateQueue *sq = mFastMixer->sq();
4871 FastMixerState *state = sq->begin();
4872 if (state->mCommand == FastMixerState::COLD_IDLE) {
4873 int32_t old = android_atomic_inc(&mFastMixerFutex);
4874 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004875 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004876 }
4877 }
4878 state->mCommand = FastMixerState::EXIT;
4879 sq->end();
4880 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4881 mFastMixer->join();
4882 // Though the fast mixer thread has exited, it's state queue is still valid.
4883 // We'll use that extract the final state which contains one remaining fast track
4884 // corresponding to our sub-mix.
4885 state = sq->begin();
4886 ALOG_ASSERT(state->mTrackMask == 1);
4887 FastTrack *fastTrack = &state->mFastTracks[0];
4888 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4889 delete fastTrack->mBufferProvider;
4890 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004891 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004892#ifdef AUDIO_WATCHDOG
4893 if (mAudioWatchdog != 0) {
4894 mAudioWatchdog->requestExit();
4895 mAudioWatchdog->requestExitAndWait();
4896 mAudioWatchdog.clear();
4897 }
4898#endif
4899 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004900 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004901 delete mAudioMixer;
4902}
4903
4904
4905uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4906{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004907 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004908 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4909 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4910 }
4911 return latency;
4912}
4913
Eric Laurentbfb1b832013-01-07 09:53:42 -08004914ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004915{
4916 // FIXME we should only do one push per cycle; confirm this is true
4917 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004918 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004919 FastMixerStateQueue *sq = mFastMixer->sq();
4920 FastMixerState *state = sq->begin();
4921 if (state->mCommand != FastMixerState::MIX_WRITE &&
4922 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4923 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004924
4925 // FIXME workaround for first HAL write being CPU bound on some devices
4926 ATRACE_BEGIN("write");
4927 mOutput->write((char *)mSinkBuffer, 0);
4928 ATRACE_END();
4929
Eric Laurent81784c32012-11-19 14:55:58 -08004930 int32_t old = android_atomic_inc(&mFastMixerFutex);
4931 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004932 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004933 }
4934#ifdef AUDIO_WATCHDOG
4935 if (mAudioWatchdog != 0) {
4936 mAudioWatchdog->resume();
4937 }
4938#endif
4939 }
4940 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004941#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004942 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004943 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004944#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004945 sq->end();
4946 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4947 if (kUseFastMixer == FastMixer_Dynamic) {
4948 mNormalSink = mPipeSink;
4949 }
4950 } else {
4951 sq->end(false /*didModify*/);
4952 }
4953 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004954 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004955}
4956
4957void AudioFlinger::MixerThread::threadLoop_standby()
4958{
4959 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004960 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004961 FastMixerStateQueue *sq = mFastMixer->sq();
4962 FastMixerState *state = sq->begin();
4963 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004964 // Report any frames trapped in the Monopipe
4965 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4966 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4967 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4968 "monoPipeWritten:%lld monoPipeLeft:%lld",
4969 (long long)mFramesWritten, (long long)mSuspendedFrames,
4970 (long long)mPipeSink->framesWritten(), pipeFrames);
4971 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4972
Eric Laurent81784c32012-11-19 14:55:58 -08004973 state->mCommand = FastMixerState::COLD_IDLE;
4974 state->mColdFutexAddr = &mFastMixerFutex;
4975 state->mColdGen++;
4976 mFastMixerFutex = 0;
4977 sq->end();
4978 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4979 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4980 if (kUseFastMixer == FastMixer_Dynamic) {
4981 mNormalSink = mOutputSink;
4982 }
4983#ifdef AUDIO_WATCHDOG
4984 if (mAudioWatchdog != 0) {
4985 mAudioWatchdog->pause();
4986 }
4987#endif
4988 } else {
4989 sq->end(false /*didModify*/);
4990 }
4991 }
4992 PlaybackThread::threadLoop_standby();
4993}
4994
Eric Laurentbfb1b832013-01-07 09:53:42 -08004995bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4996{
4997 return false;
4998}
4999
5000bool AudioFlinger::PlaybackThread::shouldStandby_l()
5001{
5002 return !mStandby;
5003}
5004
5005bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
5006{
5007 Mutex::Autolock _l(mLock);
5008 return waitingAsyncCallback_l();
5009}
5010
Eric Laurent81784c32012-11-19 14:55:58 -08005011// shared by MIXER and DIRECT, overridden by DUPLICATING
5012void AudioFlinger::PlaybackThread::threadLoop_standby()
5013{
5014 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005015 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005016 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005017 // discard any pending drain or write ack by incrementing sequence
5018 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5019 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005020 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005021 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5022 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005023 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005024 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005025}
5026
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005027void AudioFlinger::PlaybackThread::onAddNewTrack_l()
5028{
5029 ALOGV("signal playback thread");
5030 broadcast_l();
5031}
5032
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005033void AudioFlinger::PlaybackThread::onAsyncError()
5034{
5035 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5036 invalidateTracks((audio_stream_type_t)i);
5037 }
5038}
5039
Eric Laurent81784c32012-11-19 14:55:58 -08005040void AudioFlinger::MixerThread::threadLoop_mix()
5041{
Eric Laurent81784c32012-11-19 14:55:58 -08005042 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005043 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005044 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005045 // increase sleep time progressively when application underrun condition clears.
5046 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5047 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5048 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005049 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005050 sleepTimeShift--;
5051 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005052 mSleepTimeUs = 0;
5053 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005054 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005055
Eric Laurent81784c32012-11-19 14:55:58 -08005056}
5057
5058void AudioFlinger::MixerThread::threadLoop_sleepTime()
5059{
5060 // If no tracks are ready, sleep once for the duration of an output
5061 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005062 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005063 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005064 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5065 // Using the Monopipe availableToWrite, we estimate the
5066 // sleep time to retry for more data (before we underrun).
5067 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5068 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5069 const size_t pipeFrames = monoPipe->maxFrames();
5070 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5071 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5072 const size_t framesDelay = std::min(
5073 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5074 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5075 pipeFrames, framesLeft, framesDelay);
5076 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5077 } else {
5078 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5079 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5080 mSleepTimeUs = kMinThreadSleepTimeUs;
5081 }
5082 // reduce sleep time in case of consecutive application underruns to avoid
5083 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5084 // duration we would end up writing less data than needed by the audio HAL if
5085 // the condition persists.
5086 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5087 sleepTimeShift++;
5088 }
Eric Laurent81784c32012-11-19 14:55:58 -08005089 }
5090 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005091 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005092 }
5093 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005094 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5095 // before effects processing or output.
5096 if (mMixerBufferValid) {
5097 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005098 if (mType == SPATIALIZER) {
5099 memset(mSinkBuffer, 0, mSinkBufferSize);
5100 }
Andy Hung98ef9782014-03-04 14:46:50 -08005101 } else {
5102 memset(mSinkBuffer, 0, mSinkBufferSize);
5103 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005104 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005105 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5106 "anticipated start");
5107 }
5108 // TODO add standby time extension fct of effect tail
5109}
5110
5111// prepareTracks_l() must be called with ThreadBase::mLock held
5112AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
5113 Vector< sp<Track> > *tracksToRemove)
5114{
Andy Hungc0691382018-09-12 18:01:57 -07005115 // clean up deleted track ids in AudioMixer before allocating new tracks
5116 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5117 // for each trackId, destroy it in the AudioMixer
5118 if (mAudioMixer->exists(trackId)) {
5119 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005120 }
5121 });
Andy Hungc0691382018-09-12 18:01:57 -07005122 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005123
5124 mixer_state mixerStatus = MIXER_IDLE;
5125 // find out which tracks need to be processed
5126 size_t count = mActiveTracks.size();
5127 size_t mixedTracks = 0;
5128 size_t tracksWithEffect = 0;
5129 // counts only _active_ fast tracks
5130 size_t fastTracks = 0;
5131 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5132
5133 float masterVolume = mMasterVolume;
5134 bool masterMute = mMasterMute;
5135
5136 if (masterMute) {
5137 masterVolume = 0;
5138 }
5139 // Delegate master volume control to effect in output mix effect chain if needed
5140 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
5141 if (chain != 0) {
5142 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5143 chain->setVolume_l(&v, &v);
5144 masterVolume = (float)((v + (1 << 23)) >> 24);
5145 chain.clear();
5146 }
5147
5148 // prepare a new state to push
5149 FastMixerStateQueue *sq = NULL;
5150 FastMixerState *state = NULL;
5151 bool didModify = false;
5152 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005153 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005154 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005155 sq = mFastMixer->sq();
5156 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005157 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005158 }
5159
Andy Hung69aed5f2014-02-25 17:24:40 -08005160 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005161 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005162
Andy Hungbd3b2b02018-05-21 10:53:11 -07005163 // DeferredOperations handles statistics after setting mixerStatus.
5164 class DeferredOperations {
5165 public:
Andy Hungea840382020-05-05 21:50:17 -07005166 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5167 : mMixerStatus(mixerStatus)
5168 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005169
5170 // when leaving scope, tally frames properly.
5171 ~DeferredOperations() {
5172 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5173 // because that is when the underrun occurs.
5174 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005175 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005176 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005177 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005178 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005179 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005180 }
5181 }
Andy Hungea840382020-05-05 21:50:17 -07005182 // send the max underrun frames for this mixer period
5183 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005184 }
5185
5186 // tallyUnderrunFrames() is called to update the track counters
5187 // with the number of underrun frames for a particular mixer period.
5188 // We defer tallying until we know the final mixer status.
5189 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
5190 mUnderrunFrames.emplace_back(track, underrunFrames);
5191 }
5192
5193 private:
5194 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005195 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07005196 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005197 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005198 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005199
jiabin245cdd92018-12-07 17:55:15 -08005200 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005201 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07005202 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005203
5204 // this const just means the local variable doesn't change
5205 Track* const track = t.get();
5206
5207 // process fast tracks
5208 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005209 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5210 "%s(%d): FastTrack(%d) present without FastMixer",
5211 __func__, id(), track->id());
5212
jiabin245cdd92018-12-07 17:55:15 -08005213 if (track->getHapticPlaybackEnabled()) {
5214 noFastHapticTrack = false;
5215 }
Eric Laurent81784c32012-11-19 14:55:58 -08005216
5217 // It's theoretically possible (though unlikely) for a fast track to be created
5218 // and then removed within the same normal mix cycle. This is not a problem, as
5219 // the track never becomes active so it's fast mixer slot is never touched.
5220 // The converse, of removing an (active) track and then creating a new track
5221 // at the identical fast mixer slot within the same normal mix cycle,
5222 // is impossible because the slot isn't marked available until the end of each cycle.
5223 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005224 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005225 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5226 FastTrack *fastTrack = &state->mFastTracks[j];
5227
5228 // Determine whether the track is currently in underrun condition,
5229 // and whether it had a recent underrun.
5230 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5231 FastTrackUnderruns underruns = ftDump->mUnderruns;
5232 uint32_t recentFull = (underruns.mBitFields.mFull -
5233 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
5234 uint32_t recentPartial = (underruns.mBitFields.mPartial -
5235 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
5236 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
5237 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
5238 uint32_t recentUnderruns = recentPartial + recentEmpty;
5239 track->mObservedUnderruns = underruns;
5240 // don't count underruns that occur while stopping or pausing
5241 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005242 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005243 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5244 recentUnderruns > 0) {
5245 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005246 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005247 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005248 // Immediately account for FastTrack underruns.
5249 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005250
5251 // This is similar to the state machine for normal tracks,
5252 // with a few modifications for fast tracks.
5253 bool isActive = true;
5254 switch (track->mState) {
5255 case TrackBase::STOPPING_1:
5256 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005257 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005258 track->mState = TrackBase::STOPPING_2;
5259 }
5260 break;
5261 case TrackBase::PAUSING:
5262 // ramp down is not yet implemented
5263 track->setPaused();
5264 break;
5265 case TrackBase::RESUMING:
5266 // ramp up is not yet implemented
5267 track->mState = TrackBase::ACTIVE;
5268 break;
5269 case TrackBase::ACTIVE:
5270 if (recentFull > 0 || recentPartial > 0) {
5271 // track has provided at least some frames recently: reset retry count
5272 track->mRetryCount = kMaxTrackRetries;
5273 }
5274 if (recentUnderruns == 0) {
5275 // no recent underruns: stay active
5276 break;
5277 }
5278 // there has recently been an underrun of some kind
5279 if (track->sharedBuffer() == 0) {
5280 // were any of the recent underruns "empty" (no frames available)?
5281 if (recentEmpty == 0) {
5282 // no, then ignore the partial underruns as they are allowed indefinitely
5283 break;
5284 }
5285 // there has recently been an "empty" underrun: decrement the retry counter
5286 if (--(track->mRetryCount) > 0) {
5287 break;
5288 }
5289 // indicate to client process that the track was disabled because of underrun;
5290 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005291 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005292 // remove from active list, but state remains ACTIVE [confusing but true]
5293 isActive = false;
5294 break;
5295 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005296 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005297 case TrackBase::STOPPING_2:
5298 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005299 case TrackBase::STOPPED:
5300 case TrackBase::FLUSHED: // flush() while active
5301 // Check for presentation complete if track is inactive
5302 // We have consumed all the buffers of this track.
5303 // This would be incomplete if we auto-paused on underrun
5304 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005305 uint32_t latency = 0;
5306 status_t result = mOutput->stream->getLatency(&latency);
5307 ALOGE_IF(result != OK,
5308 "Error when retrieving output stream latency: %d", result);
5309 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005310 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005311 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5312 // track stays in active list until presentation is complete
5313 break;
5314 }
5315 }
5316 if (track->isStopping_2()) {
5317 track->mState = TrackBase::STOPPED;
5318 }
5319 if (track->isStopped()) {
5320 // Can't reset directly, as fast mixer is still polling this track
5321 // track->reset();
5322 // So instead mark this track as needing to be reset after push with ack
5323 resetMask |= 1 << i;
5324 }
5325 isActive = false;
5326 break;
5327 case TrackBase::IDLE:
5328 default:
Andy Hung959b5b82021-09-24 10:46:20 -07005329 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005330 }
5331
5332 if (isActive) {
5333 // was it previously inactive?
5334 if (!(state->mTrackMask & (1 << j))) {
5335 ExtendedAudioBufferProvider *eabp = track;
5336 VolumeProvider *vp = track;
5337 fastTrack->mBufferProvider = eabp;
5338 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005339 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005340 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005341 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005342 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005343 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005344 fastTrack->mGeneration++;
5345 state->mTrackMask |= 1 << j;
5346 didModify = true;
5347 // no acknowledgement required for newly active tracks
5348 }
Kevin Rocard12381092018-04-11 09:19:59 -07005349 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005350 float volume;
5351 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5352 volume = 0.f;
5353 } else {
5354 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5355 }
5356
5357 handleVoipVolume_l(&volume);
5358
Eric Laurent81784c32012-11-19 14:55:58 -08005359 // cache the combined master volume and stream type volume for fast mixer; this
5360 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005361 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005362 proxy->framesReleased()).first;
5363 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005364 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005365 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5366 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5367 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005368
Kevin Rocard12381092018-04-11 09:19:59 -07005369 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005370 ++fastTracks;
5371 } else {
5372 // was it previously active?
5373 if (state->mTrackMask & (1 << j)) {
5374 fastTrack->mBufferProvider = NULL;
5375 fastTrack->mGeneration++;
5376 state->mTrackMask &= ~(1 << j);
5377 didModify = true;
5378 // If any fast tracks were removed, we must wait for acknowledgement
5379 // because we're about to decrement the last sp<> on those tracks.
5380 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5381 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005382 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5383 // AudioTrack may start (which may not be with a start() but with a write()
5384 // after underrun) and immediately paused or released. In that case the
5385 // FastTrack state hasn't had time to update.
5386 // TODO Remove the ALOGW when this theory is confirmed.
5387 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005388 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung959b5b82021-09-24 10:46:20 -07005389 j, (int)track->mState, state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005390 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005391 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005392 }
5393 tracksToRemove->add(track);
5394 // Avoids a misleading display in dumpsys
5395 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5396 }
jiabin245cdd92018-12-07 17:55:15 -08005397 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5398 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5399 didModify = true;
5400 }
Eric Laurent81784c32012-11-19 14:55:58 -08005401 continue;
5402 }
5403
5404 { // local variable scope to avoid goto warning
5405
5406 audio_track_cblk_t* cblk = track->cblk();
5407
5408 // The first time a track is added we wait
5409 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005410 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005411
5412 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005413 // use the trackId as the AudioMixer name.
5414 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005415 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005416 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005417 track->mChannelMask,
5418 track->mFormat,
5419 track->mSessionId);
5420 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005421 ALOGW("%s(): AudioMixer cannot create track(%d)"
5422 " mask %#x, format %#x, sessionId %d",
5423 __func__, trackId,
5424 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005425 tracksToRemove->add(track);
5426 track->invalidate(); // consider it dead.
5427 continue;
5428 }
5429 }
5430
Eric Laurent81784c32012-11-19 14:55:58 -08005431 // make sure that we have enough frames to mix one full buffer.
5432 // enforce this condition only once to enable draining the buffer in case the client
5433 // app does not call stop() and relies on underrun to stop:
5434 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5435 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005436 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005437 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005438 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005439
5440 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005441 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005442 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5443 // add frames already consumed but not yet released by the resampler
5444 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005445 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005446
Eric Laurent81784c32012-11-19 14:55:58 -08005447 uint32_t minFrames = 1;
5448 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5449 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005450 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005451 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005452
5453 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005454 if (ATRACE_ENABLED()) {
5455 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005456 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005457 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005458 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005459 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005460 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005461 !track->isPaused() && !track->isTerminated())
5462 {
Andy Hungc0691382018-09-12 18:01:57 -07005463 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005464
5465 mixedTracks++;
5466
Andy Hung69aed5f2014-02-25 17:24:40 -08005467 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5468 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005469 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005470 if (track->mainBuffer() != mSinkBuffer &&
5471 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005472 if (mEffectBufferEnabled) {
5473 mEffectBufferValid = true; // Later can set directly.
5474 }
Eric Laurent81784c32012-11-19 14:55:58 -08005475 chain = getEffectChain_l(track->sessionId());
5476 // Delegate volume control to effect in track effect chain if needed
5477 if (chain != 0) {
5478 tracksWithEffect++;
5479 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005480 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005481 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005482 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005483 }
5484 }
5485
5486
5487 int param = AudioMixer::VOLUME;
5488 if (track->mFillingUpStatus == Track::FS_FILLED) {
5489 // no ramp for the first volume setting
5490 track->mFillingUpStatus = Track::FS_ACTIVE;
5491 if (track->mState == TrackBase::RESUMING) {
5492 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005493 // If a new track is paused immediately after start, do not ramp on resume.
5494 if (cblk->mServer != 0) {
5495 param = AudioMixer::RAMP_VOLUME;
5496 }
Eric Laurent81784c32012-11-19 14:55:58 -08005497 }
Andy Hungc0691382018-09-12 18:01:57 -07005498 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005499 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005500 // FIXME should not make a decision based on mServer
5501 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005502 // If the track is stopped before the first frame was mixed,
5503 // do not apply ramp
5504 param = AudioMixer::RAMP_VOLUME;
5505 }
5506
5507 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005508 uint32_t vl, vr; // in U8.24 integer format
5509 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005510 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005511 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005512 // Always fetch volumeshaper volume to ensure state is updated.
5513 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5514 const float vh = track->getVolumeHandler()->getVolume(
5515 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005516
Eric Laurenteab90452019-06-24 15:17:46 -07005517 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5518 v = 0;
5519 }
5520
5521 handleVoipVolume_l(&v);
5522
5523 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005524 vl = vr = 0;
5525 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005526 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005527 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005528 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005529 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5530 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005531 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005532 if (vlf > GAIN_FLOAT_UNITY) {
5533 ALOGV("Track left volume out of range: %.3g", vlf);
5534 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005535 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005536 if (vrf > GAIN_FLOAT_UNITY) {
5537 ALOGV("Track right volume out of range: %.3g", vrf);
5538 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005539 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005540 // now apply the master volume and stream type volume and shaper volume
5541 vlf *= v * vh;
5542 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005543 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005544 // then derive vl and vr as U8.24 versions for the effect chain
5545 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5546 vl = (uint32_t) (scaleto8_24 * vlf);
5547 vr = (uint32_t) (scaleto8_24 * vrf);
5548 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005549 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005550 // send level comes from shared memory and so may be corrupt
5551 if (sendLevel > MAX_GAIN_INT) {
5552 ALOGV("Track send level out of range: %04X", sendLevel);
5553 sendLevel = MAX_GAIN_INT;
5554 }
Andy Hung6be49402014-05-30 10:42:03 -07005555 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5556 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005557 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005558
Kevin Rocard12381092018-04-11 09:19:59 -07005559 track->setFinalVolume((vrf + vlf) / 2.f);
5560
Eric Laurent81784c32012-11-19 14:55:58 -08005561 // Delegate volume control to effect in track effect chain if needed
5562 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5563 // Do not ramp volume if volume is controlled by effect
5564 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005565 // Update remaining floating point volume levels
5566 vlf = (float)vl / (1 << 24);
5567 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005568 track->mHasVolumeController = true;
5569 } else {
5570 // force no volume ramp when volume controller was just disabled or removed
5571 // from effect chain to avoid volume spike
5572 if (track->mHasVolumeController) {
5573 param = AudioMixer::VOLUME;
5574 }
5575 track->mHasVolumeController = false;
5576 }
5577
Eric Laurent81784c32012-11-19 14:55:58 -08005578 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005579 mAudioMixer->setBufferProvider(trackId, track);
5580 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005581
Andy Hungc0691382018-09-12 18:01:57 -07005582 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5583 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5584 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005585 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005586 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005587 AudioMixer::TRACK,
5588 AudioMixer::FORMAT, (void *)track->format());
5589 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005590 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005591 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005592 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005593
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005594 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005595 mAudioMixer->setParameter(
5596 trackId,
5597 AudioMixer::TRACK,
5598 AudioMixer::MIXER_CHANNEL_MASK,
5599 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5600 } else {
5601 mAudioMixer->setParameter(
5602 trackId,
5603 AudioMixer::TRACK,
5604 AudioMixer::MIXER_CHANNEL_MASK,
5605 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5606 }
5607
Glenn Kastene3aa6592012-12-04 12:22:46 -08005608 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005609 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005610 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005611 if (reqSampleRate == 0) {
5612 reqSampleRate = mSampleRate;
5613 } else if (reqSampleRate > maxSampleRate) {
5614 reqSampleRate = maxSampleRate;
5615 }
Eric Laurent81784c32012-11-19 14:55:58 -08005616 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005617 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005618 AudioMixer::RESAMPLE,
5619 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005620 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005621
Andy Hung333ab962019-05-28 20:23:35 -07005622 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005623 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005624 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005625 AudioMixer::TIMESTRETCH,
5626 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005627 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005628
Andy Hung69aed5f2014-02-25 17:24:40 -08005629 /*
5630 * Select the appropriate output buffer for the track.
5631 *
Andy Hung98ef9782014-03-04 14:46:50 -08005632 * Tracks with effects go into their own effects chain buffer
5633 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005634 *
5635 * Other tracks can use mMixerBuffer for higher precision
5636 * channel accumulation. If this buffer is enabled
5637 * (mMixerBufferEnabled true), then selected tracks will accumulate
5638 * into it.
5639 *
5640 */
5641 if (mMixerBufferEnabled
5642 && (track->mainBuffer() == mSinkBuffer
5643 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005644 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005645 mAudioMixer->setParameter(
5646 trackId,
5647 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005648 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005649 mAudioMixer->setParameter(
5650 trackId,
5651 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005652 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005653 } else {
5654 mAudioMixer->setParameter(
5655 trackId,
5656 AudioMixer::TRACK,
5657 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5658 mAudioMixer->setParameter(
5659 trackId,
5660 AudioMixer::TRACK,
5661 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5662 // TODO: override track->mainBuffer()?
5663 mMixerBufferValid = true;
5664 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005665 } else {
5666 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005667 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005668 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005669 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005670 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005671 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005672 AudioMixer::TRACK,
5673 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5674 }
Eric Laurent81784c32012-11-19 14:55:58 -08005675 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005676 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005677 AudioMixer::TRACK,
5678 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005679 mAudioMixer->setParameter(
5680 trackId,
5681 AudioMixer::TRACK,
5682 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005683 mAudioMixer->setParameter(
5684 trackId,
5685 AudioMixer::TRACK,
5686 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Lais Andradebc3f37a2021-07-02 00:13:19 +01005687 mAudioMixer->setParameter(
5688 trackId,
5689 AudioMixer::TRACK,
5690 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)(&(track->mHapticMaxAmplitude)));
Eric Laurent81784c32012-11-19 14:55:58 -08005691
5692 // reset retry count
5693 track->mRetryCount = kMaxTrackRetries;
5694
5695 // If one track is ready, set the mixer ready if:
5696 // - the mixer was not ready during previous round OR
5697 // - no other track is not ready
5698 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5699 mixerStatus != MIXER_TRACKS_ENABLED) {
5700 mixerStatus = MIXER_TRACKS_READY;
5701 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005702
5703 // Enable the next few lines to instrument a test for underrun log handling.
5704 // TODO: Remove when we have a better way of testing the underrun log.
5705#if 0
5706 static int i;
5707 if ((++i & 0xf) == 0) {
5708 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5709 }
5710#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005711 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005712 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005713 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005714 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5715 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005716 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005717 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005718 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005719
Eric Laurent81784c32012-11-19 14:55:58 -08005720 // clear effect chain input buffer if an active track underruns to avoid sending
5721 // previous audio buffer again to effects
5722 chain = getEffectChain_l(track->sessionId());
5723 if (chain != 0) {
5724 chain->clearInputBuffer();
5725 }
5726
Andy Hungc0691382018-09-12 18:01:57 -07005727 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005728 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5729 track->isStopped() || track->isPaused()) {
5730 // We have consumed all the buffers of this track.
5731 // Remove it from the list of active tracks.
5732 // TODO: use actual buffer filling status instead of latency when available from
5733 // audio HAL
5734 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005735 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005736 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5737 if (track->isStopped()) {
5738 track->reset();
5739 }
5740 tracksToRemove->add(track);
5741 }
5742 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005743 // No buffers for this track. Give it a few chances to
5744 // fill a buffer, then remove it from active list.
5745 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005746 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5747 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005748 tracksToRemove->add(track);
5749 // indicate to client process that the track was disabled because of underrun;
5750 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005751 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005752 // If one track is not ready, mark the mixer also not ready if:
5753 // - the mixer was ready during previous round OR
5754 // - no other track is ready
5755 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5756 mixerStatus != MIXER_TRACKS_READY) {
5757 mixerStatus = MIXER_TRACKS_ENABLED;
5758 }
5759 }
Andy Hungc0691382018-09-12 18:01:57 -07005760 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005761 }
5762
5763 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005764
5765 }
5766
jiabin245cdd92018-12-07 17:55:15 -08005767 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5768 // When there is no fast track playing haptic and FastMixer exists,
5769 // enabling the first FastTrack, which provides mixed data from normal
5770 // tracks, to play haptic data.
5771 FastTrack *fastTrack = &state->mFastTracks[0];
5772 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5773 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5774 didModify = true;
5775 }
5776 }
5777
Eric Laurent81784c32012-11-19 14:55:58 -08005778 // Push the new FastMixer state if necessary
5779 bool pauseAudioWatchdog = false;
5780 if (didModify) {
5781 state->mFastTracksGen++;
5782 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5783 if (kUseFastMixer == FastMixer_Dynamic &&
5784 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5785 state->mCommand = FastMixerState::COLD_IDLE;
5786 state->mColdFutexAddr = &mFastMixerFutex;
5787 state->mColdGen++;
5788 mFastMixerFutex = 0;
5789 if (kUseFastMixer == FastMixer_Dynamic) {
5790 mNormalSink = mOutputSink;
5791 }
5792 // If we go into cold idle, need to wait for acknowledgement
5793 // so that fast mixer stops doing I/O.
5794 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5795 pauseAudioWatchdog = true;
5796 }
Eric Laurent81784c32012-11-19 14:55:58 -08005797 }
5798 if (sq != NULL) {
5799 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005800 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5801 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5802 // when bringing the output sink into standby.)
5803 //
5804 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5805 //
5806 // This occurs with BT suspend when we idle the FastMixer with
5807 // active tracks, which may be added or removed.
5808 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005809 }
5810#ifdef AUDIO_WATCHDOG
5811 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5812 mAudioWatchdog->pause();
5813 }
5814#endif
5815
5816 // Now perform the deferred reset on fast tracks that have stopped
5817 while (resetMask != 0) {
5818 size_t i = __builtin_ctz(resetMask);
5819 ALOG_ASSERT(i < count);
5820 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005821 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005822 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5823 track->reset();
5824 }
5825
Andy Hung80d03d22018-04-10 10:32:11 -07005826 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5827 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5828 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5829 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5830 // See also the implementation of destroyTrack_l().
5831 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005832 const int trackId = track->id();
5833 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5834 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005835 }
5836 }
5837
Eric Laurent81784c32012-11-19 14:55:58 -08005838 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005839 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005840
Eric Laurentb3f315a2021-07-13 15:09:05 +02005841 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
5842 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07005843 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005844 }
5845
5846 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005847 // as long as there are effects we should clear the effects buffer, to avoid
5848 // passing a non-clean buffer to the effect chain
5849 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02005850 if (mType == SPATIALIZER) {
5851 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
5852 }
Eric Laurent97d547d2014-09-02 14:45:53 -07005853 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005854 // sink or mix buffer must be cleared if all tracks are connected to an
5855 // effect chain as in this case the mixer will not write to the sink or mix buffer
5856 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02005857 // always clear sink buffer for spatializer output as the output of the spatializer
5858 // effect will be accumulated into it
5859 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5860 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005861 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005862 if (mMixerBufferValid) {
5863 memset(mMixerBuffer, 0, mMixerBufferSize);
5864 // TODO: In testing, mSinkBuffer below need not be cleared because
5865 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5866 // after mixing.
5867 //
5868 // To enforce this guarantee:
5869 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5870 // (mixedTracks == 0 && fastTracks > 0))
5871 // must imply MIXER_TRACKS_READY.
5872 // Later, we may clear buffers regardless, and skip much of this logic.
5873 }
Andy Hung98ef9782014-03-04 14:46:50 -08005874 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005875 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005876 }
5877
5878 // if any fast tracks, then status is ready
5879 mMixerStatusIgnoringFastTracks = mixerStatus;
5880 if (fastTracks > 0) {
5881 mixerStatus = MIXER_TRACKS_READY;
5882 }
5883 return mixerStatus;
5884}
5885
Eric Laurentad7dd962016-09-22 12:38:37 -07005886// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005887uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005888{
5889 uint32_t trackCount = 0;
5890 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005891 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005892 trackCount++;
5893 }
5894 }
5895 return trackCount;
5896}
5897
Brian Lindahl65e90012022-07-27 18:01:07 +02005898bool AudioFlinger::PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut * output)
ziyangch8f194f12021-12-01 13:48:04 -08005899{
Brian Lindahl65e90012022-07-27 18:01:07 +02005900 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
5901 // could falsely detect that the frame position has stalled due to underrun because we haven't
5902 // given the Audio HAL enough time to update.
5903 const nsecs_t nowNs = systemTime();
5904 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
5905 return mLatchedValue;
5906 }
5907 mPreviousNs = nowNs;
5908 mLatchedValue = false;
5909 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08005910 uint64_t position = 0;
5911 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02005912 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08005913 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02005914 if (position != mPreviousPosition) {
5915 mPreviousPosition = position;
5916 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08005917 }
5918 }
Brian Lindahl65e90012022-07-27 18:01:07 +02005919 return mLatchedValue;
5920}
5921
5922void AudioFlinger::PlaybackThread::IsTimestampAdvancing::clear()
5923{
5924 mLatchedValue = true;
5925 mPreviousPosition = 0;
5926 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08005927}
5928
Andy Hung1bc088a2018-02-09 15:57:31 -08005929// isTrackAllowed_l() must be called with ThreadBase::mLock held
5930bool AudioFlinger::MixerThread::isTrackAllowed_l(
5931 audio_channel_mask_t channelMask, audio_format_t format,
5932 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005933{
Andy Hung1bc088a2018-02-09 15:57:31 -08005934 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5935 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005936 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005937 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005938 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005939 ALOGW("%s: invalid format: %#x", __func__, format);
5940 return false;
5941 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005942 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005943 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5944 return false;
5945 }
5946 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005947}
5948
Eric Laurent10351942014-05-08 18:49:52 -07005949// checkForNewParameter_l() must be called with ThreadBase::mLock held
5950bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5951 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005952{
Eric Laurent81784c32012-11-19 14:55:58 -08005953 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07005954 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005955
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005956 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005957
Eric Laurent10351942014-05-08 18:49:52 -07005958 AudioParameter param = AudioParameter(keyValuePair);
5959 int value;
5960 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5961 reconfig = true;
5962 }
5963 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005964 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005965 status = BAD_VALUE;
5966 } else {
5967 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005968 reconfig = true;
5969 }
Eric Laurent10351942014-05-08 18:49:52 -07005970 }
5971 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005972 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005973 status = BAD_VALUE;
5974 } else {
5975 // no need to save value, since it's constant
5976 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005977 }
Eric Laurent10351942014-05-08 18:49:52 -07005978 }
5979 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5980 // do not accept frame count changes if tracks are open as the track buffer
5981 // size depends on frame count and correct behavior would not be guaranteed
5982 // if frame count is changed after track creation
5983 if (!mTracks.isEmpty()) {
5984 status = INVALID_OPERATION;
5985 } else {
5986 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005987 }
Eric Laurent10351942014-05-08 18:49:52 -07005988 }
5989 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005990 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005991 }
Eric Laurent81784c32012-11-19 14:55:58 -08005992
Eric Laurent10351942014-05-08 18:49:52 -07005993 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005994 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005995 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005996 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07005997 if (!mStandby) {
5998 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07005999 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07006000 mStandby = true;
6001 }
Eric Laurent10351942014-05-08 18:49:52 -07006002 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006003 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006004 }
Eric Laurent10351942014-05-08 18:49:52 -07006005 if (status == NO_ERROR && reconfig) {
6006 readOutputParameters_l();
6007 delete mAudioMixer;
6008 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006009 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006010 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08006011 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006012 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08006013 track->mChannelMask,
6014 track->mFormat,
6015 track->mSessionId);
6016 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006017 "%s(): AudioMixer cannot create track(%d)"
6018 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006019 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07006020 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07006021 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006022 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006023 }
Eric Laurent81784c32012-11-19 14:55:58 -08006024 }
6025
Dean Wheatley68918102021-03-19 22:09:19 +11006026 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006027}
6028
6029
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006030void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006031{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006032 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006033 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006034 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006035 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006036 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6037 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6038 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006039 if (hasFastMixer()) {
6040 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6041
6042 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6043 // while we are dumping it. It may be inconsistent, but it won't mutate!
6044 // This is a large object so we place it on the heap.
6045 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006046 const std::unique_ptr<FastMixerDumpState> copy =
6047 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006048 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006049
6050#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006051 // Similar for state queue
6052 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6053 observerCopy.dump(fd);
6054 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6055 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006056#endif
6057
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006058#ifdef AUDIO_WATCHDOG
6059 if (mAudioWatchdog != 0) {
6060 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6061 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6062 wdCopy.dump(fd);
6063 }
6064#endif
6065
6066 } else {
6067 dprintf(fd, " No FastMixer\n");
6068 }
Eric Laurent81784c32012-11-19 14:55:58 -08006069}
6070
6071uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
6072{
6073 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6074}
6075
6076uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
6077{
6078 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6079}
6080
6081void AudioFlinger::MixerThread::cacheParameters_l()
6082{
6083 PlaybackThread::cacheParameters_l();
6084
6085 // FIXME: Relaxed timing because of a certain device that can't meet latency
6086 // Should be reduced to 2x after the vendor fixes the driver issue
6087 // increase threshold again due to low power audio mode. The way this warning
6088 // threshold is calculated and its usefulness should be reconsidered anyway.
6089 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6090}
6091
6092// ----------------------------------------------------------------------------
6093
6094AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006095 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
6096 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006097{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006098 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006099}
6100
Eric Laurent81784c32012-11-19 14:55:58 -08006101AudioFlinger::DirectOutputThread::~DirectOutputThread()
6102{
6103}
6104
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006105void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006106{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006107 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006108 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6109 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6110}
6111
6112void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
6113{
6114 Mutex::Autolock _l(mLock);
6115 if (mMasterBalance != balance) {
6116 mMasterBalance.store(balance);
6117 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6118 broadcast_l();
6119 }
6120}
6121
Eric Laurent5850c4c2016-11-10 13:04:31 -08006122void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006123{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006124 float left, right;
6125
Andy Hung333ab962019-05-28 20:23:35 -07006126 // Ensure volumeshaper state always advances even when muted.
6127 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
6128 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
6129 proxy->framesReleased());
6130 mVolumeShaperActive = shaperActive;
6131
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006132 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006133 left = right = 0;
6134 } else {
6135 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006136 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006137
Glenn Kastenc56f3422014-03-21 17:53:17 -07006138 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6139 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6140 if (left > GAIN_FLOAT_UNITY) {
6141 left = GAIN_FLOAT_UNITY;
6142 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006143 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07006144 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6145 if (right > GAIN_FLOAT_UNITY) {
6146 right = GAIN_FLOAT_UNITY;
6147 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006148 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006149 }
6150
6151 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07006152 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006153 if (left != mLeftVolFloat || right != mRightVolFloat) {
6154 mLeftVolFloat = left;
6155 mRightVolFloat = right;
6156
Eric Laurentbfb1b832013-01-07 09:53:42 -08006157 // Delegate volume control to effect in track effect chain if needed
6158 // only one effect chain can be present on DirectOutputThread, so if
6159 // there is one, the track is connected to it
6160 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006161 // if effect chain exists, volume is handled by it.
6162 // Convert volumes from float to 8.24
6163 uint32_t vl = (uint32_t)(left * (1 << 24));
6164 uint32_t vr = (uint32_t)(right * (1 << 24));
6165 // Direct/Offload effect chains set output volume in setVolume_l().
6166 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6167 } else {
6168 // otherwise we directly set the volume.
6169 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006170 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006171 }
6172 }
6173}
6174
Phil Burk43b4dcc2015-06-09 16:53:44 -07006175void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
6176{
6177 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07006178 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006179
Eric Laurent0f0631e2015-07-06 18:01:25 -07006180 if (previousTrack != 0 && latestTrack != 0) {
6181 if (mType == DIRECT) {
6182 if (previousTrack.get() != latestTrack.get()) {
6183 mFlushPending = true;
6184 }
6185 } else /* mType == OFFLOAD */ {
6186 if (previousTrack->sessionId() != latestTrack->sessionId()) {
6187 mFlushPending = true;
6188 }
6189 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006190 } else if (previousTrack == 0) {
6191 // there could be an old track added back during track transition for direct
6192 // output, so always issues flush to flush data of the previous track if it
6193 // was already destroyed with HAL paused, then flush can resume the playback
6194 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006195 }
6196 PlaybackThread::onAddNewTrack_l();
6197}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006198
Eric Laurent81784c32012-11-19 14:55:58 -08006199AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
6200 Vector< sp<Track> > *tracksToRemove
6201)
6202{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006203 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006204 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006205 bool doHwPause = false;
6206 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006207
6208 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006209 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006210 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006211 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006212 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006213 continue;
6214 }
6215
Eric Laurent5850c4c2016-11-10 13:04:31 -08006216 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006217#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006218 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006219#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006220 // Only consider last track started for volume and mixer state control.
6221 // In theory an older track could underrun and restart after the new one starts
6222 // but as we only care about the transition phase between two tracks on a
6223 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006224 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006225 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006226
Kuowei Li23666472021-01-20 10:23:25 +08006227 if (track->isPausePending()) {
6228 track->pauseAck();
6229 // It is possible a track might have been flushed or stopped.
6230 // Other operations such as flush pending might occur on the next prepare.
6231 if (track->isPausing()) {
6232 track->setPaused();
6233 }
6234 // Always perform pause, as an immediate flush will change
6235 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006236 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006237 doHwPause = true;
6238 mHwPaused = true;
6239 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006240 } else if (track->isFlushPending()) {
6241 track->flushAck();
6242 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006243 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006244 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006245 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006246 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006247 if (last) {
6248 mLeftVolFloat = mRightVolFloat = -1.0;
6249 if (mHwPaused) {
6250 doHwResume = true;
6251 mHwPaused = false;
6252 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006253 }
6254 }
6255
Eric Laurent81784c32012-11-19 14:55:58 -08006256 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006257 // for all its buffers to be filled before processing it.
6258 // Allow draining the buffer in case the client
6259 // app does not call stop() and relies on underrun to stop:
6260 // hence the test on (track->mRetryCount > 1).
Andy Hung455982f2021-04-27 17:46:12 -07006261 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
6262 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6263 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006264 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006265
6266 // target retry count that we will use is based on the time we wait for retries.
6267 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6268 // the retry threshold is when we accept any size for PCM data. This is slightly
6269 // smaller than the retry count so we can push small bits of data without a glitch.
6270 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006271 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006272 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung455982f2021-04-27 17:46:12 -07006273 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006274 minFrames = mNormalFrameCount;
6275 } else {
6276 minFrames = 1;
6277 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006278
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006279 const size_t framesReady = track->framesReady();
6280 const int trackId = track->id();
6281 if (ATRACE_ENABLED()) {
6282 std::string traceName("nRdy");
6283 traceName += std::to_string(trackId);
6284 ATRACE_INT(traceName.c_str(), framesReady);
6285 }
6286 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006287 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006288 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006289 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006290
6291 if (track->mFillingUpStatus == Track::FS_FILLED) {
6292 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006293 if (last) {
6294 // make sure processVolume_l() will apply new volume even if 0
6295 mLeftVolFloat = mRightVolFloat = -1.0;
6296 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006297 if (!mHwSupportsPause) {
6298 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006299 }
6300 }
6301
6302 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006303 processVolume_l(track, last);
6304 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006305 sp<Track> previousTrack = mPreviousTrack.promote();
6306 if (previousTrack != 0) {
6307 if (track != previousTrack.get()) {
6308 // Flush any data still being written from last track
6309 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006310 // Invalidate previous track to force a seek when resuming.
6311 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006312 }
6313 }
6314 mPreviousTrack = track;
6315
Eric Laurentd595b7c2013-04-03 17:27:56 -07006316 // reset retry count
Andy Hung455982f2021-04-27 17:46:12 -07006317 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006318 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006319 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006320 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006321 doHwResume = true;
6322 mHwPaused = false;
6323 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006324 }
Eric Laurent81784c32012-11-19 14:55:58 -08006325 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006326 // clear effect chain input buffer if the last active track started underruns
6327 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006328 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006329 mEffectChains[0]->clearInputBuffer();
6330 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006331 if (track->isStopping_1()) {
6332 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07006333 if (last && mHwPaused) {
6334 doHwResume = true;
6335 mHwPaused = false;
6336 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006337 }
6338 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6339 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006340 // We have consumed all the buffers of this track.
6341 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006342 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006343 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006344 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006345 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006346 if (presComplete) {
6347 mOutput->presentationComplete();
6348 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006349 if (track->isStopping_2()) {
6350 track->mState = TrackBase::STOPPED;
6351 }
Eric Laurent81784c32012-11-19 14:55:58 -08006352 if (track->isStopped()) {
6353 track->reset();
6354 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006355 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006356 }
6357 } else {
6358 // No buffers for this track. Give it a few chances to
6359 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006360 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006361 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Eric Laurent81784c32012-11-19 14:55:58 -08006362 if (--(track->mRetryCount) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006363 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
ziyangch8f194f12021-12-01 13:48:04 -08006364 track->mRetryCount = kMaxTrackRetriesOffload;
6365 } else {
6366 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6367 tracksToRemove->add(track);
6368 // indicate to client process that the track was disabled because of
6369 // underrun; it will then automatically call start() when data is available
6370 track->disable();
6371 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6372 // unlike mixerthread, HAL can be paused for direct output
6373 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6374 "minFrames = %u, mFormat = %#x",
6375 framesReady, minFrames, mFormat);
6376 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6377 doHwPause = true;
6378 mHwPaused = true;
6379 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006380 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006381 } else if (last) {
6382 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006383 }
6384 }
6385 }
6386 }
6387
Eric Laurentd1f69b02014-12-15 14:33:13 -08006388 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006389 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006390 for (size_t i = 0; i < mTracks.size(); i++) {
6391 if (mTracks[i]->isFlushPending()) {
6392 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006393 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006394 }
6395 }
6396 }
6397
6398 // make sure the pause/flush/resume sequence is executed in the right order.
6399 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6400 // before flush and then resume HW. This can happen in case of pause/flush/resume
6401 // if resume is received before pause is executed.
6402 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006403 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006404 status_t result = mOutput->stream->pause();
6405 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006406 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006407 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006408 flushHw_l();
6409 }
6410 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006411 status_t result = mOutput->stream->resume();
6412 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006413 }
Eric Laurent81784c32012-11-19 14:55:58 -08006414 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006415 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006416
6417 return mixerStatus;
6418}
6419
6420void AudioFlinger::DirectOutputThread::threadLoop_mix()
6421{
Eric Laurent81784c32012-11-19 14:55:58 -08006422 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006423 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006424 // output audio to hardware
6425 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006426 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006427 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006428 status_t status = mActiveTrack->getNextBuffer(&buffer);
6429 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006430 // no need to pad with 0 for compressed audio
6431 if (audio_has_proportional_frames(mFormat)) {
6432 memset(curBuf, 0, frameCount * mFrameSize);
6433 }
Eric Laurent81784c32012-11-19 14:55:58 -08006434 break;
6435 }
6436 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6437 frameCount -= buffer.frameCount;
6438 curBuf += buffer.frameCount * mFrameSize;
6439 mActiveTrack->releaseBuffer(&buffer);
6440 }
Andy Hung2098f272014-02-27 14:00:06 -08006441 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006442 mSleepTimeUs = 0;
6443 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006444 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006445}
6446
6447void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6448{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006449 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006450 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006451 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006452 return;
6453 }
Andy Hung85ba3332021-04-27 17:40:26 -07006454 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6455 mSleepTimeUs = mActiveSleepTimeUs;
6456 } else {
6457 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006458 }
Andy Hung85ba3332021-04-27 17:40:26 -07006459 // Note: In S or later, we do not write zeroes for
6460 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006461}
6462
Eric Laurentd1f69b02014-12-15 14:33:13 -08006463void AudioFlinger::DirectOutputThread::threadLoop_exit()
6464{
6465 {
6466 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006467 for (size_t i = 0; i < mTracks.size(); i++) {
6468 if (mTracks[i]->isFlushPending()) {
6469 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006470 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006471 }
6472 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006473 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006474 flushHw_l();
6475 }
6476 }
6477 PlaybackThread::threadLoop_exit();
6478}
6479
6480// must be called with thread mutex locked
6481bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6482{
6483 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006484 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006485
6486 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6487 // after a timeout and we will enter standby then.
6488 if (mTracks.size() > 0) {
6489 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006490 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6491 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006492 }
6493
Eric Laurent5cff4032015-05-26 13:49:58 -07006494 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006495}
6496
Eric Laurent10351942014-05-08 18:49:52 -07006497// checkForNewParameter_l() must be called with ThreadBase::mLock held
6498bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6499 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006500{
6501 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006502 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006503
Eric Laurent10351942014-05-08 18:49:52 -07006504 AudioParameter param = AudioParameter(keyValuePair);
6505 int value;
6506 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006507 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006508 }
Eric Laurent10351942014-05-08 18:49:52 -07006509 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6510 // do not accept frame count changes if tracks are open as the track buffer
6511 // size depends on frame count and correct behavior would not be garantied
6512 // if frame count is changed after track creation
6513 if (!mTracks.isEmpty()) {
6514 status = INVALID_OPERATION;
6515 } else {
6516 reconfig = true;
6517 }
6518 }
6519 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006520 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006521 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006522 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006523 if (!mStandby) {
6524 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006525 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07006526 mStandby = true;
6527 }
Eric Laurent10351942014-05-08 18:49:52 -07006528 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006529 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006530 }
6531 if (status == NO_ERROR && reconfig) {
6532 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006533 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006534 }
6535 }
6536
Dean Wheatley68918102021-03-19 22:09:19 +11006537 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006538}
6539
6540uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6541{
6542 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006543 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006544 time = PlaybackThread::activeSleepTimeUs();
6545 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006546 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006547 }
6548 return time;
6549}
6550
6551uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6552{
6553 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006554 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006555 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6556 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006557 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006558 }
6559 return time;
6560}
6561
6562uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6563{
6564 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006565 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006566 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6567 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006568 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006569 }
6570 return time;
6571}
6572
6573void AudioFlinger::DirectOutputThread::cacheParameters_l()
6574{
6575 PlaybackThread::cacheParameters_l();
6576
6577 // use shorter standby delay as on normal output to release
6578 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006579 // no delay on outputs with HW A/V sync
6580 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006581 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006582 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006583 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006584 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006585 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006586 }
Eric Laurent81784c32012-11-19 14:55:58 -08006587}
6588
Eric Laurente659ef42014-09-29 13:06:46 -07006589void AudioFlinger::DirectOutputThread::flushHw_l()
6590{
ziyangch8f194f12021-12-01 13:48:04 -08006591 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08006592 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006593 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006594 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006595 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006596 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006597}
6598
Andy Hung10cbff12017-02-21 17:30:14 -08006599int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6600 // If a VolumeShaper is active, we must wake up periodically to update volume.
6601 const int64_t NS_PER_MS = 1000000;
6602 return mVolumeShaperActive ?
6603 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6604}
6605
Eric Laurent81784c32012-11-19 14:55:58 -08006606// ----------------------------------------------------------------------------
6607
Eric Laurentbfb1b832013-01-07 09:53:42 -08006608AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006609 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006610 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006611 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006612 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006613 mDrainSequence(0),
6614 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006615{
6616}
6617
6618AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6619{
6620}
6621
6622void AudioFlinger::AsyncCallbackThread::onFirstRef()
6623{
6624 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6625}
6626
6627bool AudioFlinger::AsyncCallbackThread::threadLoop()
6628{
6629 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006630 uint32_t writeAckSequence;
6631 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006632 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006633
6634 {
6635 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006636 while (!((mWriteAckSequence & 1) ||
6637 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006638 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006639 exitPending())) {
6640 mWaitWorkCV.wait(mLock);
6641 }
6642
Eric Laurentbfb1b832013-01-07 09:53:42 -08006643 if (exitPending()) {
6644 break;
6645 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006646 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6647 mWriteAckSequence, mDrainSequence);
6648 writeAckSequence = mWriteAckSequence;
6649 mWriteAckSequence &= ~1;
6650 drainSequence = mDrainSequence;
6651 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006652 asyncError = mAsyncError;
6653 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006654 }
6655 {
Eric Laurent4de95592013-09-26 15:28:21 -07006656 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6657 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006658 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006659 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006660 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006661 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006662 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006663 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006664 if (asyncError) {
6665 playbackThread->onAsyncError();
6666 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006667 }
6668 }
6669 }
6670 return false;
6671}
6672
6673void AudioFlinger::AsyncCallbackThread::exit()
6674{
6675 ALOGV("AsyncCallbackThread::exit");
6676 Mutex::Autolock _l(mLock);
6677 requestExit();
6678 mWaitWorkCV.broadcast();
6679}
6680
Eric Laurent3b4529e2013-09-05 18:09:19 -07006681void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006682{
6683 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006684 // bit 0 is cleared
6685 mWriteAckSequence = sequence << 1;
6686}
6687
6688void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6689{
6690 Mutex::Autolock _l(mLock);
6691 // ignore unexpected callbacks
6692 if (mWriteAckSequence & 2) {
6693 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006694 mWaitWorkCV.signal();
6695 }
6696}
6697
Eric Laurent3b4529e2013-09-05 18:09:19 -07006698void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006699{
6700 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006701 // bit 0 is cleared
6702 mDrainSequence = sequence << 1;
6703}
6704
6705void AudioFlinger::AsyncCallbackThread::resetDraining()
6706{
6707 Mutex::Autolock _l(mLock);
6708 // ignore unexpected callbacks
6709 if (mDrainSequence & 2) {
6710 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006711 mWaitWorkCV.signal();
6712 }
6713}
6714
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006715void AudioFlinger::AsyncCallbackThread::setAsyncError()
6716{
6717 Mutex::Autolock _l(mLock);
6718 mAsyncError = true;
6719 mWaitWorkCV.signal();
6720}
6721
Eric Laurentbfb1b832013-01-07 09:53:42 -08006722
6723// ----------------------------------------------------------------------------
6724AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006725 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6726 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
ziyangch8f194f12021-12-01 13:48:04 -08006727 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006728{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006729 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006730 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006731 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006732}
6733
Eric Laurentbfb1b832013-01-07 09:53:42 -08006734void AudioFlinger::OffloadThread::threadLoop_exit()
6735{
6736 if (mFlushPending || mHwPaused) {
6737 // If a flush is pending or track was paused, just discard buffered data
6738 flushHw_l();
6739 } else {
6740 mMixerStatus = MIXER_DRAIN_ALL;
6741 threadLoop_drain();
6742 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006743 if (mUseAsyncWrite) {
6744 ALOG_ASSERT(mCallbackThread != 0);
6745 mCallbackThread->exit();
6746 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006747 PlaybackThread::threadLoop_exit();
6748}
6749
6750AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6751 Vector< sp<Track> > *tracksToRemove
6752)
6753{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006754 size_t count = mActiveTracks.size();
6755
6756 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006757 bool doHwPause = false;
6758 bool doHwResume = false;
6759
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006760 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006761
Eric Laurentbfb1b832013-01-07 09:53:42 -08006762 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006763 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006764 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006765#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006766 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006767#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006768 // Only consider last track started for volume and mixer state control.
6769 // In theory an older track could underrun and restart after the new one starts
6770 // but as we only care about the transition phase between two tracks on a
6771 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006772 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006773 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006774
Haynes Mathew George7844f672014-01-15 12:32:55 -08006775 if (track->isInvalid()) {
6776 ALOGW("An invalidated track shouldn't be in active list");
6777 tracksToRemove->add(track);
6778 continue;
6779 }
6780
6781 if (track->mState == TrackBase::IDLE) {
6782 ALOGW("An idle track shouldn't be in active list");
6783 continue;
6784 }
6785
Kuowei Li23666472021-01-20 10:23:25 +08006786 if (track->isPausePending()) {
6787 track->pauseAck();
6788 // It is possible a track might have been flushed or stopped.
6789 // Other operations such as flush pending might occur on the next prepare.
6790 if (track->isPausing()) {
6791 track->setPaused();
6792 }
6793 // Always perform pause if last, as an immediate flush will change
6794 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006795 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006796 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006797 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006798 mHwPaused = true;
6799 }
6800 // If we were part way through writing the mixbuffer to
6801 // the HAL we must save this until we resume
6802 // BUG - this will be wrong if a different track is made active,
6803 // in that case we want to discard the pending data in the
6804 // mixbuffer and tell the client to present it again when the
6805 // track is resumed
6806 mPausedWriteLength = mCurrentWriteLength;
6807 mPausedBytesRemaining = mBytesRemaining;
6808 mBytesRemaining = 0; // stop writing
6809 }
6810 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006811 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006812 if (track->isStopping_1()) {
6813 track->mRetryCount = kMaxTrackStopRetriesOffload;
6814 } else {
6815 track->mRetryCount = kMaxTrackRetriesOffload;
6816 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006817 track->flushAck();
6818 if (last) {
6819 mFlushPending = true;
6820 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006821 } else if (track->isResumePending()){
6822 track->resumeAck();
6823 if (last) {
6824 if (mPausedBytesRemaining) {
6825 // Need to continue write that was interrupted
6826 mCurrentWriteLength = mPausedWriteLength;
6827 mBytesRemaining = mPausedBytesRemaining;
6828 mPausedBytesRemaining = 0;
6829 }
6830 if (mHwPaused) {
6831 doHwResume = true;
6832 mHwPaused = false;
6833 // threadLoop_mix() will handle the case that we need to
6834 // resume an interrupted write
6835 }
6836 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006837 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006838
Eric Laurent3df841a2016-07-15 15:15:40 -07006839 mLeftVolFloat = mRightVolFloat = -1.0;
6840
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006841 // Do not handle new data in this iteration even if track->framesReady()
6842 mixerStatus = MIXER_TRACKS_ENABLED;
6843 }
6844 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006845 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006846 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006847 if (track->mFillingUpStatus == Track::FS_FILLED) {
6848 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006849 if (last) {
6850 // make sure processVolume_l() will apply new volume even if 0
6851 mLeftVolFloat = mRightVolFloat = -1.0;
6852 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006853 }
6854
6855 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006856 sp<Track> previousTrack = mPreviousTrack.promote();
6857 if (previousTrack != 0) {
6858 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006859 // Flush any data still being written from last track
6860 mBytesRemaining = 0;
6861 if (mPausedBytesRemaining) {
6862 // Last track was paused so we also need to flush saved
6863 // mixbuffer state and invalidate track so that it will
6864 // re-submit that unwritten data when it is next resumed
6865 mPausedBytesRemaining = 0;
6866 // Invalidate is a bit drastic - would be more efficient
6867 // to have a flag to tell client that some of the
6868 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006869 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006870 }
6871 // flush data already sent to the DSP if changing audio session as audio
6872 // comes from a different source. Also invalidate previous track to force a
6873 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006874 if (previousTrack->sessionId() != track->sessionId()) {
6875 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006876 }
6877 }
6878 }
6879 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006880 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006881 if (track->isStopping_1()) {
6882 track->mRetryCount = kMaxTrackStopRetriesOffload;
6883 } else {
6884 track->mRetryCount = kMaxTrackRetriesOffload;
6885 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006886 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006887 mixerStatus = MIXER_TRACKS_READY;
6888 }
6889 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006890 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006891 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006892 if (--(track->mRetryCount) <= 0) {
6893 // Hardware buffer can hold a large amount of audio so we must
6894 // wait for all current track's data to drain before we say
6895 // that the track is stopped.
6896 if (mBytesRemaining == 0) {
6897 // Only start draining when all data in mixbuffer
6898 // has been written
6899 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6900 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6901 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6902 if (last && !mStandby) {
6903 // do not modify drain sequence if we are already draining. This happens
6904 // when resuming from pause after drain.
6905 if ((mDrainSequence & 1) == 0) {
6906 mSleepTimeUs = 0;
6907 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6908 mixerStatus = MIXER_DRAIN_TRACK;
6909 mDrainSequence += 2;
6910 }
6911 if (mHwPaused) {
6912 // It is possible to move from PAUSED to STOPPING_1 without
6913 // a resume so we must ensure hardware is running
6914 doHwResume = true;
6915 mHwPaused = false;
6916 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006917 }
6918 }
Eric Laurente93cc032016-05-05 10:15:10 -07006919 } else if (last) {
6920 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6921 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006922 }
6923 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006924 // Drain has completed or we are in standby, signal presentation complete
6925 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006926 track->mState = TrackBase::STOPPED;
Atneya Nair0cae0432022-05-10 18:12:12 -04006927 mOutput->presentationComplete();
6928 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08006929 track->reset();
6930 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006931 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006932 if (!mUseAsyncWrite) {
6933 // If we don't get explicit drain notification we must
6934 // register discontinuity regardless of whether this is
6935 // the previous (!last) or the upcoming (last) track
6936 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006937 mTimestampVerifier.discontinuity(
6938 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006939 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006940 }
6941 } else {
6942 // No buffers for this track. Give it a few chances to
6943 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02006944 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006945 if (--(track->mRetryCount) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006946 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hungf8044752016-07-27 14:58:11 -07006947 track->mRetryCount = kMaxTrackRetriesOffload;
6948 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006949 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6950 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006951 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006952 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006953 // it will then automatically call start() when data is available
6954 track->disable();
6955 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006956 } else if (last){
6957 mixerStatus = MIXER_TRACKS_ENABLED;
6958 }
6959 }
6960 }
6961 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006962 if (track->isReady()) { // check ready to prevent premature start.
6963 processVolume_l(track, last);
6964 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006965 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006966
Eric Laurentea0fade2013-10-04 16:23:48 -07006967 // make sure the pause/flush/resume sequence is executed in the right order.
6968 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6969 // before flush and then resume HW. This can happen in case of pause/flush/resume
6970 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006971 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006972 status_t result = mOutput->stream->pause();
6973 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006974 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006975 if (mFlushPending) {
6976 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006977 }
Eric Laurentfd477972013-10-25 18:10:40 -07006978 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006979 status_t result = mOutput->stream->resume();
6980 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006981 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006982
Eric Laurentbfb1b832013-01-07 09:53:42 -08006983 // remove all the tracks that need to be...
6984 removeTracks_l(*tracksToRemove);
6985
6986 return mixerStatus;
6987}
6988
Eric Laurentbfb1b832013-01-07 09:53:42 -08006989// must be called with thread mutex locked
6990bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6991{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006992 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6993 mWriteAckSequence, mDrainSequence);
6994 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006995 return true;
6996 }
6997 return false;
6998}
6999
Eric Laurentbfb1b832013-01-07 09:53:42 -08007000bool AudioFlinger::OffloadThread::waitingAsyncCallback()
7001{
7002 Mutex::Autolock _l(mLock);
7003 return waitingAsyncCallback_l();
7004}
7005
7006void AudioFlinger::OffloadThread::flushHw_l()
7007{
Eric Laurente659ef42014-09-29 13:06:46 -07007008 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007009 // Flush anything still waiting in the mixbuffer
7010 mCurrentWriteLength = 0;
7011 mBytesRemaining = 0;
7012 mPausedWriteLength = 0;
7013 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007014 // reset bytes written count to reflect that DSP buffers are empty after flush.
7015 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007016
Eric Laurentbfb1b832013-01-07 09:53:42 -08007017 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007018 // discard any pending drain or write ack by incrementing sequence
7019 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7020 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007021 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007022 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7023 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007024 }
7025}
7026
Haynes Mathew George05317d22016-05-03 16:34:26 -07007027void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
7028{
7029 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007030 if (PlaybackThread::invalidateTracks_l(streamType)) {
7031 mFlushPending = true;
7032 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007033}
7034
Eric Laurentbfb1b832013-01-07 09:53:42 -08007035// ----------------------------------------------------------------------------
7036
Eric Laurent81784c32012-11-19 14:55:58 -08007037AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07007038 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07007039 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007040 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007041 mWaitTimeMs(UINT_MAX)
7042{
7043 addOutputTrack(mainThread);
7044}
7045
7046AudioFlinger::DuplicatingThread::~DuplicatingThread()
7047{
7048 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7049 mOutputTracks[i]->destroy();
7050 }
7051}
7052
7053void AudioFlinger::DuplicatingThread::threadLoop_mix()
7054{
7055 // mix buffers...
7056 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007057 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007058 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007059 if (mMixerBufferValid) {
7060 memset(mMixerBuffer, 0, mMixerBufferSize);
7061 } else {
7062 memset(mSinkBuffer, 0, mSinkBufferSize);
7063 }
Eric Laurent81784c32012-11-19 14:55:58 -08007064 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007065 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007066 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007067 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007068 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007069}
7070
7071void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
7072{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007073 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007074 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007075 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007076 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007077 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007078 }
7079 } else if (mBytesWritten != 0) {
7080 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7081 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007082 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007083 } else {
7084 // flush remaining overflow buffers in output tracks
7085 writeFrames = 0;
7086 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007087 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007088 }
7089}
7090
Eric Laurentbfb1b832013-01-07 09:53:42 -08007091ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007092{
7093 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007094 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7095
7096 // Consider the first OutputTrack for timestamp and frame counting.
7097
7098 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7099 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7100 // we always claim success.
7101 if (i == 0) {
7102 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7103 ALOGD_IF(correction != 0 && writeFrames != 0,
7104 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7105 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7106 mFramesWritten -= correction;
7107 }
7108
7109 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007110 }
Andy Hungcf10d742020-04-28 15:38:24 -07007111 if (mStandby) {
7112 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007113 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007114 mStandby = false;
7115 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007116 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007117}
7118
7119void AudioFlinger::DuplicatingThread::threadLoop_standby()
7120{
7121 // DuplicatingThread implements standby by stopping all tracks
7122 for (size_t i = 0; i < outputTracks.size(); i++) {
7123 outputTracks[i]->stop();
7124 }
7125}
7126
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007127void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08007128{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007129 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007130
7131 std::stringstream ss;
7132 const size_t numTracks = mOutputTracks.size();
7133 ss << " " << numTracks << " OutputTracks";
7134 if (numTracks > 0) {
7135 ss << ":";
7136 for (const auto &track : mOutputTracks) {
7137 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007138 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007139 if (thread.get() != nullptr) {
7140 ss << thread.get() << ", " << thread->id();
7141 } else {
7142 ss << "null";
7143 }
7144 ss << ")";
7145 }
7146 }
7147 ss << "\n";
7148 std::string result = ss.str();
7149 write(fd, result.c_str(), result.size());
7150}
7151
Eric Laurent81784c32012-11-19 14:55:58 -08007152void AudioFlinger::DuplicatingThread::saveOutputTracks()
7153{
7154 outputTracks = mOutputTracks;
7155}
7156
7157void AudioFlinger::DuplicatingThread::clearOutputTracks()
7158{
7159 outputTracks.clear();
7160}
7161
7162void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
7163{
7164 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007165 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7166 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7167 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7168 const size_t frameCount =
7169 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7170 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7171 // from different OutputTracks and their associated MixerThreads (e.g. one may
7172 // nearly empty and the other may be dropping data).
7173
Svet Ganov33761132021-05-13 22:51:08 +00007174 // TODO b/182392769: use attribution source util, move to server edge
7175 AttributionSourceState attributionSource = AttributionSourceState();
7176 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007177 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007178 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007179 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007180 attributionSource.token = sp<BBinder>::make();
Andy Hungc25b84a2015-01-14 19:04:10 -08007181 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007182 this,
7183 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007184 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007185 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007186 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007187 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007188 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7189 if (status != NO_ERROR) {
7190 ALOGE("addOutputTrack() initCheck failed %d", status);
7191 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007192 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007193 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7194 mOutputTracks.add(outputTrack);
7195 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7196 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007197}
7198
7199void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
7200{
7201 Mutex::Autolock _l(mLock);
7202 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7203 if (mOutputTracks[i]->thread() == thread) {
7204 mOutputTracks[i]->destroy();
7205 mOutputTracks.removeAt(i);
7206 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007207 if (thread->getOutput() == mOutput) {
7208 mOutput = NULL;
7209 }
Eric Laurent81784c32012-11-19 14:55:58 -08007210 return;
7211 }
7212 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007213 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007214}
7215
7216// caller must hold mLock
7217void AudioFlinger::DuplicatingThread::updateWaitTime_l()
7218{
7219 mWaitTimeMs = UINT_MAX;
7220 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7221 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
7222 if (strong != 0) {
7223 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7224 if (waitTimeMs < mWaitTimeMs) {
7225 mWaitTimeMs = waitTimeMs;
7226 }
7227 }
7228 }
7229}
7230
7231
7232bool AudioFlinger::DuplicatingThread::outputsReady(
7233 const SortedVector< sp<OutputTrack> > &outputTracks)
7234{
7235 for (size_t i = 0; i < outputTracks.size(); i++) {
7236 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
7237 if (thread == 0) {
7238 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7239 outputTracks[i].get());
7240 return false;
7241 }
7242 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
7243 // see note at standby() declaration
7244 if (playbackThread->standby() && !playbackThread->isSuspended()) {
7245 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7246 thread.get());
7247 return false;
7248 }
7249 }
7250 return true;
7251}
7252
Kevin Rocard12381092018-04-11 09:19:59 -07007253void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
7254 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007255{
Kevin Rocard12381092018-04-11 09:19:59 -07007256 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7257 outputTrack->setMetadatas(metadata.tracks);
7258 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007259}
7260
Eric Laurent81784c32012-11-19 14:55:58 -08007261uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
7262{
7263 return (mWaitTimeMs * 1000) / 2;
7264}
7265
7266void AudioFlinger::DuplicatingThread::cacheParameters_l()
7267{
7268 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7269 updateWaitTime_l();
7270
7271 MixerThread::cacheParameters_l();
7272}
7273
Eric Laurentb3f315a2021-07-13 15:09:05 +02007274// ----------------------------------------------------------------------------
7275
Eric Laurentfa0f6742021-08-17 18:39:44 +02007276AudioFlinger::SpatializerThread::SpatializerThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007277 AudioStreamOut* output,
7278 audio_io_handle_t id,
7279 bool systemReady,
7280 audio_config_base_t *mixerConfig)
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007281 : MixerThread(audioFlinger, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007282{
7283}
7284
Eric Laurentfa0f6742021-08-17 18:39:44 +02007285void AudioFlinger::SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007286{
7287 bool hasVirtualizer = false;
7288 bool hasDownMixer = false;
7289 sp<EffectHandle> finalDownMixer;
7290 {
7291 Mutex::Autolock _l(mLock);
7292 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
7293 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007294 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007295 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7296 }
7297
7298 finalDownMixer = mFinalDownMixer;
7299 mFinalDownMixer.clear();
7300 }
7301
7302 if (hasVirtualizer) {
7303 if (finalDownMixer != nullptr) {
7304 int32_t ret;
7305 finalDownMixer->disable(&ret);
7306 }
7307 finalDownMixer.clear();
7308 } else if (!hasDownMixer) {
7309 std::vector<effect_descriptor_t> descriptors;
7310 status_t status = mAudioFlinger->mEffectsFactoryHal->getDescriptors(
7311 EFFECT_UIID_DOWNMIX, &descriptors);
7312 if (status != NO_ERROR) {
7313 return;
7314 }
7315 ALOG_ASSERT(!descriptors.empty(),
7316 "%s getDescriptors() returned no error but empty list", __func__);
7317
7318 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7319 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007320 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007321
7322 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7323 ALOGW("%s error creating downmixer %d", __func__, status);
7324 finalDownMixer.clear();
7325 } else {
7326 int32_t ret;
7327 finalDownMixer->enable(&ret);
7328 }
7329 }
7330
7331 {
7332 Mutex::Autolock _l(mLock);
7333 mFinalDownMixer = finalDownMixer;
7334 }
7335}
7336
Eric Laurent6acd1d42017-01-04 14:23:29 -08007337
Eric Laurent81784c32012-11-19 14:55:58 -08007338// ----------------------------------------------------------------------------
7339// Record
7340// ----------------------------------------------------------------------------
7341
7342AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
7343 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007344 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007345 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007346 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07007347 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007348 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007349 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007350 mActiveTracks(&this->mLocalLog),
7351 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007352 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007353 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007354 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7355 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007356 // mFastCapture below
7357 , mFastCaptureFutex(0)
7358 // mInputSource
7359 // mPipeSink
7360 // mPipeSource
7361 , mPipeFramesP2(0)
7362 // mPipeMemory
7363 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007364 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007365 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007366{
Glenn Kastend7dca052015-03-05 16:05:54 -08007367 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7368 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007369
George Burgess IVa8f90c12020-05-14 11:27:19 -07007370 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007371 mIsMsdDevice = strcmp(
7372 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7373 }
7374
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007375 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007376
Andy Hungc8fddf32018-08-08 18:32:37 -07007377 // TODO: We may also match on address as well as device type for
7378 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007379 // TODO: This property should be ensure that only contains one single device type.
7380 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7381 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007382 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7383 : AUDIO_DEVICE_NONE));
7384
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007385 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007386 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007387 size_t numCounterOffers = 0;
7388 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007389#if !LOG_NDEBUG
7390 ssize_t index =
7391#else
7392 (void)
7393#endif
7394 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007395 ALOG_ASSERT(index == 0);
7396
7397 // initialize fast capture depending on configuration
7398 bool initFastCapture;
7399 switch (kUseFastCapture) {
7400 case FastCapture_Never:
7401 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007402 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007403 break;
7404 case FastCapture_Always:
7405 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007406 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007407 break;
7408 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07007409 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007410 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
7411 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
7412 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007413 break;
7414 // case FastCapture_Dynamic:
7415 }
7416
7417 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007418 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007419 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007420 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7421 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007422 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007423 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007424 const sp<MemoryDealer> roHeap(readOnlyHeap());
7425 sp<IMemory> pipeMemory;
7426 if ((roHeap == 0) ||
7427 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007428 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007429 ALOGE("not enough memory for pipe buffer size=%zu; "
7430 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7431 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7432 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007433 goto failed;
7434 }
7435 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7436 memset(pipeBuffer, 0, pipeSize);
7437 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7438 const NBAIO_Format offers[1] = {format};
7439 size_t numCounterOffers = 0;
7440 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7441 ALOG_ASSERT(index == 0);
7442 mPipeSink = pipe;
7443 PipeReader *pipeReader = new PipeReader(*pipe);
7444 numCounterOffers = 0;
7445 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7446 ALOG_ASSERT(index == 0);
7447 mPipeSource = pipeReader;
7448 mPipeFramesP2 = pipeFramesP2;
7449 mPipeMemory = pipeMemory;
7450
7451 // create fast capture
7452 mFastCapture = new FastCapture();
7453 FastCaptureStateQueue *sq = mFastCapture->sq();
7454#ifdef STATE_QUEUE_DUMP
7455 // FIXME
7456#endif
7457 FastCaptureState *state = sq->begin();
7458 state->mCblk = NULL;
7459 state->mInputSource = mInputSource.get();
7460 state->mInputSourceGen++;
7461 state->mPipeSink = pipe;
7462 state->mPipeSinkGen++;
7463 state->mFrameCount = mFrameCount;
7464 state->mCommand = FastCaptureState::COLD_IDLE;
7465 // already done in constructor initialization list
7466 //mFastCaptureFutex = 0;
7467 state->mColdFutexAddr = &mFastCaptureFutex;
7468 state->mColdGen++;
7469 state->mDumpState = &mFastCaptureDumpState;
7470#ifdef TEE_SINK
7471 // FIXME
7472#endif
7473 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7474 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7475 sq->end();
7476 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7477
7478 // start the fast capture
7479 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7480 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007481 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007482 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007483#ifdef AUDIO_WATCHDOG
7484 // FIXME
7485#endif
7486
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007487 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007488 }
Andy Hung8946a282018-04-19 20:04:56 -07007489#ifdef TEE_SINK
7490 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7491 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7492#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007493failed: ;
7494
7495 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007496}
7497
Eric Laurent81784c32012-11-19 14:55:58 -08007498AudioFlinger::RecordThread::~RecordThread()
7499{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007500 if (mFastCapture != 0) {
7501 FastCaptureStateQueue *sq = mFastCapture->sq();
7502 FastCaptureState *state = sq->begin();
7503 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7504 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7505 if (old == -1) {
7506 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7507 }
7508 }
7509 state->mCommand = FastCaptureState::EXIT;
7510 sq->end();
7511 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7512 mFastCapture->join();
7513 mFastCapture.clear();
7514 }
7515 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007516 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007517 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007518}
7519
7520void AudioFlinger::RecordThread::onFirstRef()
7521{
Glenn Kastend7dca052015-03-05 16:05:54 -08007522 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007523}
7524
Eric Laurent555530a2017-02-07 18:17:24 -08007525void AudioFlinger::RecordThread::preExit()
7526{
7527 ALOGV(" preExit()");
7528 Mutex::Autolock _l(mLock);
7529 for (size_t i = 0; i < mTracks.size(); i++) {
7530 sp<RecordTrack> track = mTracks[i];
7531 track->invalidate();
7532 }
7533 mActiveTracks.clear();
7534 mStartStopCond.broadcast();
7535}
7536
Eric Laurent81784c32012-11-19 14:55:58 -08007537bool AudioFlinger::RecordThread::threadLoop()
7538{
Eric Laurent81784c32012-11-19 14:55:58 -08007539 nsecs_t lastWarning = 0;
7540
7541 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007542
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007543reacquire_wakelock:
7544 sp<RecordTrack> activeTrack;
7545 {
7546 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007547 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007548 }
7549
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007550 // used to request a deferred sleep, to be executed later while mutex is unlocked
7551 uint32_t sleepUs = 0;
7552
Andy Hung446f4df2019-02-21 12:26:41 -08007553 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7554
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007555 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007556 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007557 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007558
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007559 // activeTracks accumulates a copy of a subset of mActiveTracks
7560 Vector< sp<RecordTrack> > activeTracks;
7561
Glenn Kasten735f45f2014-08-18 15:51:59 -07007562 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007563 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007564
Glenn Kasten735f45f2014-08-18 15:51:59 -07007565 // reference to a fast track which is about to be removed
7566 sp<RecordTrack> fastTrackToRemove;
7567
Eric Laurent33403f02020-05-29 18:35:06 -07007568 bool silenceFastCapture = false;
7569
Eric Laurent81784c32012-11-19 14:55:58 -08007570 { // scope for mLock
7571 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007572
Eric Laurent021cf962014-05-13 10:18:14 -07007573 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007574
Eric Laurent000a4192014-01-29 15:17:32 -08007575 // check exitPending here because checkForNewParameters_l() and
7576 // checkForNewParameters_l() can temporarily release mLock
7577 if (exitPending()) {
7578 break;
7579 }
7580
Eric Laurent5c25d562016-07-13 17:17:45 -07007581 // sleep with mutex unlocked
7582 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007583 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007584 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7585 ATRACE_END();
7586 sleepUs = 0;
7587 continue;
7588 }
7589
Glenn Kasten2b806402013-11-20 16:37:38 -08007590 // if no active track(s), then standby and release wakelock
7591 size_t size = mActiveTracks.size();
7592 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007593 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007594 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007595 releaseWakeLock_l();
7596 ALOGV("RecordThread: loop stopping");
7597 // go to sleep
7598 mWaitWorkCV.wait(mLock);
7599 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007600 goto reacquire_wakelock;
7601 }
7602
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007603 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007604 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007605 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007606
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007607 activeTrack = mActiveTracks[i];
7608 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007609 if (activeTrack->isFastTrack()) {
7610 ALOG_ASSERT(fastTrackToRemove == 0);
7611 fastTrackToRemove = activeTrack;
7612 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007613 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007614 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007615 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007616 continue;
7617 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007618
7619 TrackBase::track_state activeTrackState = activeTrack->mState;
7620 switch (activeTrackState) {
7621
7622 case TrackBase::PAUSING:
7623 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007624 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007625 doBroadcast = true;
7626 size--;
7627 continue;
7628
7629 case TrackBase::STARTING_1:
7630 sleepUs = 10000;
7631 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007632 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007633 continue;
7634
7635 case TrackBase::STARTING_2:
7636 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007637 if (mStandby) {
7638 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007639 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007640 mStandby = false;
7641 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007642 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007643 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007644 break;
7645
7646 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007647 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007648 break;
7649
Andy Hungce685402018-10-05 17:23:27 -07007650 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7651 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7652 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007653 default:
Andy Hungce685402018-10-05 17:23:27 -07007654 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7655 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007656 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007657
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007658 if (activeTrack->isFastTrack()) {
7659 ALOG_ASSERT(!mFastTrackAvail);
7660 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007661 // if the active fast track is silenced either:
7662 // 1) silence the whole capture from fast capture buffer if this is
7663 // the only active track
7664 // 2) invalidate this track: this will cause the client to reconnect and possibly
7665 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007666 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07007667 if (activeTrack->isSilenced()) {
7668 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007669 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07007670 } else {
7671 silenceFastCapture = true;
7672 }
7673 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007674 // Invalidate fast tracks if access to audio history is required as this is not
7675 // possible with fast tracks. Once the fast track has been invalidated, no new
7676 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
7677 if (mMaxSharedAudioHistoryMs != 0) {
7678 invalidate = true;
7679 }
7680 if (invalidate) {
7681 activeTrack->invalidate();
7682 ALOG_ASSERT(fastTrackToRemove == 0);
7683 fastTrackToRemove = activeTrack;
7684 removeTrack_l(activeTrack);
7685 mActiveTracks.remove(activeTrack);
7686 size--;
7687 continue;
7688 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007689 fastTrack = activeTrack;
7690 }
Eric Laurent33403f02020-05-29 18:35:06 -07007691
7692 activeTracks.add(activeTrack);
7693 i++;
7694
Glenn Kasten9e982352013-08-14 14:39:50 -07007695 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007696
Andy Hungdae27702016-10-31 14:01:16 -07007697 mActiveTracks.updatePowerState(this);
7698
Kevin Rocard069c2712018-03-29 19:09:14 -07007699 updateMetadata_l();
7700
Eric Laurent5c25d562016-07-13 17:17:45 -07007701 if (allStopped) {
7702 standbyIfNotAlreadyInStandby();
7703 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007704 if (doBroadcast) {
7705 mStartStopCond.broadcast();
7706 }
7707
7708 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007709 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007710 if (sleepUs == 0) {
7711 sleepUs = kRecordThreadSleepUs;
7712 }
7713 continue;
7714 }
7715 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007716
Eric Laurent81784c32012-11-19 14:55:58 -08007717 lockEffectChains_l(effectChains);
7718 }
7719
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007720 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007721
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007722 size_t size = effectChains.size();
7723 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007724 // thread mutex is not locked, but effect chain is locked
7725 effectChains[i]->process_l();
7726 }
7727
Glenn Kasten735f45f2014-08-18 15:51:59 -07007728 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007729 if (mFastCapture != 0) {
7730 FastCaptureStateQueue *sq = mFastCapture->sq();
7731 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007732 bool didModify = false;
7733 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007734 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7735 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7736 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7737 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7738 if (old == -1) {
7739 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7740 }
7741 }
7742 state->mCommand = FastCaptureState::READ_WRITE;
7743#if 0 // FIXME
7744 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007745 FastThreadDumpState::kSamplingNforLowRamDevice :
7746 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007747#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007748 didModify = true;
7749 }
7750 audio_track_cblk_t *cblkOld = state->mCblk;
7751 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7752 if (cblkNew != cblkOld) {
7753 state->mCblk = cblkNew;
7754 // block until acked if removing a fast track
7755 if (cblkOld != NULL) {
7756 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7757 }
7758 didModify = true;
7759 }
jiabin01c8f562018-07-19 17:47:28 -07007760 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7761 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7762 if (state->mFastPatchRecordBufferProvider != abp) {
7763 state->mFastPatchRecordBufferProvider = abp;
7764 state->mFastPatchRecordFormat = fastTrack == 0 ?
7765 AUDIO_FORMAT_INVALID : fastTrack->format();
7766 didModify = true;
7767 }
Eric Laurent33403f02020-05-29 18:35:06 -07007768 if (state->mSilenceCapture != silenceFastCapture) {
7769 state->mSilenceCapture = silenceFastCapture;
7770 didModify = true;
7771 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007772 sq->end(didModify);
7773 if (didModify) {
7774 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007775#if 0
7776 if (kUseFastCapture == FastCapture_Dynamic) {
7777 mNormalSource = mPipeSource;
7778 }
7779#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007780 }
7781 }
7782
Glenn Kasten735f45f2014-08-18 15:51:59 -07007783 // now run the fast track destructor with thread mutex unlocked
7784 fastTrackToRemove.clear();
7785
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007786 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7787 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7788 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7789 // If destination is non-contiguous, first read past the nominal end of buffer, then
7790 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007791
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007792 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007793 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007794 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007795
7796 // If an NBAIO source is present, use it to read the normal capture's data
7797 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007798 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007799
7800 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7801 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7802 // we immediately retry the read() to get data and prevent another overflow.
7803 for (int retries = 0; retries <= 2; ++retries) {
7804 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7805 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7806 framesToRead);
7807 if (framesRead != OVERRUN) break;
7808 }
7809
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007810 const ssize_t availableToRead = mPipeSource->availableToRead();
7811 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00007812 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07007813 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007814 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7815 "more frames to read than fifo size, %zd > %zu",
7816 availableToRead, mPipeFramesP2);
7817 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7818 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7819 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7820 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007821 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7822 }
7823 if (framesRead < 0) {
7824 status_t status = (status_t) framesRead;
7825 switch (status) {
7826 case OVERRUN:
7827 ALOGW("overrun on read from pipe");
7828 framesRead = 0;
7829 break;
7830 case NEGOTIATE:
7831 ALOGE("re-negotiation is needed");
7832 framesRead = -1; // Will cause an attempt to recover.
7833 break;
7834 default:
7835 ALOGE("unknown error %d on read from pipe", status);
7836 break;
7837 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007838 }
7839 // otherwise use the HAL / AudioStreamIn directly
7840 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007841 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007842 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007843 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007844 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007845 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007846 if (result < 0) {
7847 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007848 } else {
7849 framesRead = bytesRead / mFrameSize;
7850 }
7851 }
7852
Andy Hung446f4df2019-02-21 12:26:41 -08007853 const int64_t lastIoEndNs = systemTime(); // end IO timing
7854
Andy Hung3f0c9022016-01-15 17:49:46 -08007855 // Update server timestamp with server stats
7856 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07007857 if (framesRead >= 0) {
7858 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7859 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7860 }
Andy Hung3f0c9022016-01-15 17:49:46 -08007861
7862 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007863 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007864 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007865 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11007866 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
7867 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
7868 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07007869 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007870 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7871
7872 mTimestampVerifier.add(position, time, mSampleRate);
7873
7874 // Correct timestamps
7875 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10007876 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007877 id(), (long long)time, (long long)position);
7878 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7879 position = correctedTimestamp.mFrames;
7880 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10007881 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007882 id(), (long long)time, (long long)position);
7883 }
7884
Andy Hung3f0c9022016-01-15 17:49:46 -08007885 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7886 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7887 // Note: In general record buffers should tend to be empty in
7888 // a properly running pipeline.
7889 //
7890 // Also, it is not advantageous to call get_presentation_position during the read
7891 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007892 } else {
7893 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007894 }
7895 }
Andy Hunge6c37112019-02-26 17:38:10 -08007896
7897 // From the timestamp, input read latency is negative output write latency.
7898 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7899 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7900 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7901 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7902 mLatencyMs.add(latencyMs);
7903 }
7904
Andy Hung3f0c9022016-01-15 17:49:46 -08007905 // Use this to track timestamp information
7906 // ALOGD("%s", mTimestamp.toString().c_str());
7907
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007908 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007909 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007910 // Force input into standby so that it tries to recover at next read attempt
7911 inputStandBy();
7912 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007913 }
7914 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007915 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007916 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007917 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007918 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007919
Andy Hung8946a282018-04-19 20:04:56 -07007920#ifdef TEE_SINK
7921 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7922#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007923 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007924 {
7925 size_t part1 = mRsmpInFramesP2 - rear;
7926 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007927 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007928 (framesRead - part1) * mFrameSize);
7929 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007930 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11007931 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007932
7933 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007934
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007935 // loop over each active track
7936 for (size_t i = 0; i < size; i++) {
7937 activeTrack = activeTracks[i];
7938
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007939 // skip fast tracks, as those are handled directly by FastCapture
7940 if (activeTrack->isFastTrack()) {
7941 continue;
7942 }
7943
Andy Hung73c02e42015-03-29 01:13:58 -07007944 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007945 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7946
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007947 enum {
7948 OVERRUN_UNKNOWN,
7949 OVERRUN_TRUE,
7950 OVERRUN_FALSE
7951 } overrun = OVERRUN_UNKNOWN;
7952
7953 // loop over getNextBuffer to handle circular sink
7954 for (;;) {
7955
7956 activeTrack->mSink.frameCount = ~0;
7957 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7958 size_t framesOut = activeTrack->mSink.frameCount;
7959 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7960
Andy Hung73c02e42015-03-29 01:13:58 -07007961 // check available frames and handle overrun conditions
7962 // if the record track isn't draining fast enough.
7963 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007964 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007965 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7966 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007967 overrun = OVERRUN_TRUE;
7968 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007969 if (framesOut == 0 || framesIn == 0) {
7970 break;
7971 }
7972
Andy Hung6770c6f2015-04-07 13:43:36 -07007973 // Don't allow framesOut to be larger than what is possible with resampling
7974 // from framesIn.
7975 // This isn't strictly necessary but helps limit buffer resizing in
7976 // RecordBufferConverter. TODO: remove when no longer needed.
7977 framesOut = min(framesOut,
7978 destinationFramesPossible(
7979 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007980
7981 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007982 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007983 // straight from RecordThread buffer to RecordTrack buffer.
7984 AudioBufferProvider::Buffer buffer;
7985 buffer.frameCount = framesOut;
7986 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7987 if (status == OK && buffer.frameCount != 0) {
7988 ALOGV_IF(buffer.frameCount != framesOut,
7989 "%s() read less than expected (%zu vs %zu)",
7990 __func__, buffer.frameCount, framesOut);
7991 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007992 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007993 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7994 } else {
7995 framesOut = 0;
7996 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7997 __func__, status, buffer.frameCount);
7998 }
7999 } else {
8000 // process frames from the RecordThread buffer provider to the RecordTrack
8001 // buffer
8002 framesOut = activeTrack->mRecordBufferConverter->convert(
8003 activeTrack->mSink.raw,
8004 activeTrack->mResamplerBufferProvider,
8005 framesOut);
8006 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008007
8008 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8009 overrun = OVERRUN_FALSE;
8010 }
8011
8012 if (activeTrack->mFramesToDrop == 0) {
8013 if (framesOut > 0) {
8014 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008015 // Sanitize before releasing if the track has no access to the source data
8016 // An idle UID receives silence from non virtual devices until active
8017 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07008018 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008019 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008020 activeTrack->releaseBuffer(&activeTrack->mSink);
8021 }
8022 } else {
8023 // FIXME could do a partial drop of framesOut
8024 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07008025 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008026 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008027 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008028 }
8029 } else {
8030 activeTrack->mFramesToDrop += framesOut;
8031 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
8032 activeTrack->mSyncStartEvent->isCancelled()) {
8033 ALOGW("Synced record %s, session %d, trigger session %d",
8034 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
8035 activeTrack->sessionId(),
8036 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08008037 activeTrack->mSyncStartEvent->triggerSession() :
8038 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008039 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008040 }
8041 }
8042 }
8043
8044 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008045 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008046 }
8047 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008048
8049 switch (overrun) {
8050 case OVERRUN_TRUE:
8051 // client isn't retrieving buffers fast enough
8052 if (!activeTrack->setOverflow()) {
8053 nsecs_t now = systemTime();
8054 // FIXME should lastWarning per track?
8055 if ((now - lastWarning) > kWarningThrottleNs) {
8056 ALOGW("RecordThread: buffer overflow");
8057 lastWarning = now;
8058 }
8059 }
8060 break;
8061 case OVERRUN_FALSE:
8062 activeTrack->clearOverflow();
8063 break;
8064 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008065 break;
8066 }
8067
Andy Hung3f0c9022016-01-15 17:49:46 -08008068 // update frame information and push timestamp out
8069 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08008070 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008071 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8072 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008073 }
8074
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008075unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008076 // enable changes in effect chain
8077 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008078 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008079 if (audio_has_proportional_frames(mFormat)
8080 && loopCount == lastLoopCountRead + 1) {
8081 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8082 const double jitterMs =
8083 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8084 {framesRead, readPeriodNs},
8085 {0, 0} /* lastTimestamp */, mSampleRate);
8086 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8087
8088 Mutex::Autolock _l(mLock);
8089 mIoJitterMs.add(jitterMs);
8090 mProcessTimeMs.add(processMs);
8091 }
8092 // update timing info.
8093 mLastIoBeginNs = lastIoBeginNs;
8094 mLastIoEndNs = lastIoEndNs;
8095 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008096 }
8097
Glenn Kasten93e471f2013-08-19 08:40:07 -07008098 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008099
8100 {
8101 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008102 for (size_t i = 0; i < mTracks.size(); i++) {
8103 sp<RecordTrack> track = mTracks[i];
8104 track->invalidate();
8105 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008106 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008107 mStartStopCond.broadcast();
8108 }
8109
8110 releaseWakeLock();
8111
8112 ALOGV("RecordThread %p exiting", this);
8113 return false;
8114}
8115
Glenn Kasten93e471f2013-08-19 08:40:07 -07008116void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008117{
8118 if (!mStandby) {
8119 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008120 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008121 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008122 mStandby = true;
8123 }
8124}
8125
8126void AudioFlinger::RecordThread::inputStandBy()
8127{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008128 // Idle the fast capture if it's currently running
8129 if (mFastCapture != 0) {
8130 FastCaptureStateQueue *sq = mFastCapture->sq();
8131 FastCaptureState *state = sq->begin();
8132 if (!(state->mCommand & FastCaptureState::IDLE)) {
8133 state->mCommand = FastCaptureState::COLD_IDLE;
8134 state->mColdFutexAddr = &mFastCaptureFutex;
8135 state->mColdGen++;
8136 mFastCaptureFutex = 0;
8137 sq->end();
8138 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8139 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8140#if 0
8141 if (kUseFastCapture == FastCapture_Dynamic) {
8142 // FIXME
8143 }
8144#endif
8145#ifdef AUDIO_WATCHDOG
8146 // FIXME
8147#endif
8148 } else {
8149 sq->end(false /*didModify*/);
8150 }
8151 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008152 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008153 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008154
8155 // If going into standby, flush the pipe source.
8156 if (mPipeSource.get() != nullptr) {
8157 const ssize_t flushed = mPipeSource->flush();
8158 if (flushed > 0) {
8159 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8160 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8161 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8162 }
8163 }
Eric Laurent81784c32012-11-19 14:55:58 -08008164}
8165
Glenn Kasten05997e22014-03-13 15:08:33 -07008166// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07008167sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08008168 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008169 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008170 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008171 audio_format_t format,
8172 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008173 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008174 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008175 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008176 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008177 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008178 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008179 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008180 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008181 audio_port_handle_t portId,
8182 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008183{
Glenn Kasten74935e42013-12-19 08:56:45 -08008184 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008185 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008186 sp<RecordTrack> track;
8187 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008188 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008189 audio_input_flags_t requestedFlags = *flags;
8190 uint32_t sampleRate;
Svet Ganov33761132021-05-13 22:51:08 +00008191 AttributionSourceState checkedAttributionSource = AudioFlinger::checkAttributionSourcePackage(
8192 attributionSource);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008193
8194 lStatus = initCheck();
8195 if (lStatus != NO_ERROR) {
8196 ALOGE("createRecordTrack_l() audio driver not initialized");
8197 goto Exit;
8198 }
8199
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008200 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8201 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8202 lStatus = BAD_VALUE;
8203 goto Exit;
8204 }
8205
Eric Laurentec376dc2021-04-08 20:41:22 +02008206 if (maxSharedAudioHistoryMs != 0) {
Svet Ganov33761132021-05-13 22:51:08 +00008207 if (!captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008208 lStatus = PERMISSION_DENIED;
8209 goto Exit;
8210 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008211 if (maxSharedAudioHistoryMs < 0
8212 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8213 lStatus = BAD_VALUE;
8214 goto Exit;
8215 }
8216 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008217 if (*pSampleRate == 0) {
8218 *pSampleRate = mSampleRate;
8219 }
8220 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008221
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008222 // special case for FAST flag considered OK if fast capture is present and access to
8223 // audio history is not required
8224 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008225 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8226 }
8227
Eric Laurentf14db3c2017-12-08 14:20:36 -08008228 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008229 if ((*flags & inputFlags) != *flags) {
8230 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8231 " input flags (%08x)",
8232 *flags, inputFlags);
8233 *flags = (audio_input_flags_t)(*flags & inputFlags);
8234 }
Eric Laurent81784c32012-11-19 14:55:58 -08008235
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008236 // client expresses a preference for FAST and no access to audio history,
8237 // but we get the final say
8238 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008239 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008240 // we formerly checked for a callback handler (non-0 tid),
8241 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008242 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008243 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008244 // Frame count is not specified (0), or is less than or equal the pipe depth.
8245 // It is OK to provide a higher capacity than requested.
8246 // We will force it to mPipeFramesP2 below.
8247 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008248 // PCM data
8249 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008250 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008251 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008252 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008253 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008254 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008255 hasFastCapture() &&
8256 // there are sufficient fast track slots available
8257 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008258 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008259 // check compatibility with audio effects.
8260 Mutex::Autolock _l(mLock);
8261 // Do not accept FAST flag if the session has software effects
8262 sp<EffectChain> chain = getEffectChain_l(sessionId);
8263 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008264 audio_input_flags_t old = *flags;
8265 chain->checkInputFlagCompatibility(flags);
8266 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008267 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8268 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008269 }
8270 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008271 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008272 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8273 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008274 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008275 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8276 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008277 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008278 this, frameCount, mFrameCount, mPipeFramesP2,
8279 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008280 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008281 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008282 }
8283 }
8284
Eric Laurentf14db3c2017-12-08 14:20:36 -08008285 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8286 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8287 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8288 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8289 lStatus = BAD_TYPE;
8290 goto Exit;
8291 }
8292
Glenn Kasten74105912014-07-03 12:28:53 -07008293 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008294 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008295 // fast track: frame count is exactly the pipe depth
8296 frameCount = mPipeFramesP2;
8297 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008298 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008299 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008300 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8301 // or 20 ms if there is a fast capture
8302 // TODO This could be a roundupRatio inline, and const
8303 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8304 * sampleRate + mSampleRate - 1) / mSampleRate;
8305 // minimum number of notification periods is at least kMinNotifications,
8306 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8307 static const size_t kMinNotifications = 3;
8308 static const uint32_t kMinMs = 30;
8309 // TODO This could be a roundupRatio inline
8310 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8311 // TODO This could be a roundupRatio inline
8312 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8313 maxNotificationFrames;
8314 const size_t minFrameCount = maxNotificationFrames *
8315 max(kMinNotifications, minNotificationsByMs);
8316 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008317 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8318 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008319 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008320 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008321 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008322 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008323
8324 { // scope for mLock
8325 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008326 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008327 if (!mSharedAudioPackageName.empty()
Svet Ganov33761132021-05-13 22:51:08 +00008328 && mSharedAudioPackageName == checkedAttributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008329 && mSharedAudioSessionId == sessionId
Svet Ganov33761132021-05-13 22:51:08 +00008330 && captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008331 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008332 }
Eric Laurent81784c32012-11-19 14:55:58 -08008333
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008334 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008335 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008336 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008337 checkedAttributionSource, *flags, TrackBase::TYPE_DEFAULT, portId,
8338 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008339
Glenn Kasten03003332013-08-06 15:40:54 -07008340 lStatus = track->initCheck();
8341 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008342 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008343 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008344 goto Exit;
8345 }
8346 mTracks.add(track);
8347
Eric Laurent05067782016-06-01 18:27:28 -07008348 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008349 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8350 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8351 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008352 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008353 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008354
8355 if (maxSharedAudioHistoryMs != 0) {
8356 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8357 }
Eric Laurent81784c32012-11-19 14:55:58 -08008358 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008359
Eric Laurent81784c32012-11-19 14:55:58 -08008360 lStatus = NO_ERROR;
8361
8362Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008363 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008364 return track;
8365}
8366
8367status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
8368 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008369 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008370{
8371 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8372 sp<ThreadBase> strongMe = this;
8373 status_t status = NO_ERROR;
8374
8375 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008376 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008377 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008378 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08008379 triggerSession,
8380 recordTrack->sessionId(),
8381 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008382 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08008383 // Sync event can be cancelled by the trigger session if the track is not in a
8384 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008385 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008386 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008387 } else {
8388 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08008389 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008390 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08008391 }
8392 }
8393
8394 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008395 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008396 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008397 if (recordTrack->isInvalid()) {
8398 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008399 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8400 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008401 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008402 if (mActiveTracks.indexOf(recordTrack) >= 0) {
8403 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008404 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8405 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008406 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008407 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008408 } else {
Andy Hung959b5b82021-09-24 10:46:20 -07008409 ALOGV("active record track state %d", (int)recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008410 }
8411 return status;
8412 }
8413
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008414 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8415 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8416 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008417 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08008418 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008419 status_t status = NO_ERROR;
8420 if (recordTrack->isExternalTrack()) {
8421 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008422 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008423 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008424 if (recordTrack->isInvalid()) {
8425 recordTrack->clearSyncStartEvent();
8426 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8427 recordTrack->mState = TrackBase::STARTING_2;
8428 // STARTING_2 forces destroy to call stopInput.
8429 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008430 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8431 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008432 }
8433 if (recordTrack->mState != TrackBase::STARTING_1) {
8434 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung959b5b82021-09-24 10:46:20 -07008435 __func__, recordTrack->id(), (int)recordTrack->mState);
Andy Hungce685402018-10-05 17:23:27 -07008436 // Someone else has changed state, let them take over,
8437 // leave mState in the new state.
8438 recordTrack->clearSyncStartEvent();
8439 return INVALID_OPERATION;
8440 }
8441 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008442 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008443 ALOGW("%s(%d): startInput failed, status %d",
8444 __func__, recordTrack->id(), status);
8445 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8446 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008447 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008448 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008449 return status;
8450 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008451 sendIoConfigEvent_l(
8452 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008453 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008454
8455 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8456
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008457 // Catch up with current buffer indices if thread is already running.
8458 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8459 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8460 // see previously buffered data before it called start(), but with greater risk of overrun.
8461
Andy Hung73c02e42015-03-29 01:13:58 -07008462 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008463 if (!recordTrack->isDirect()) {
8464 // clear any converter state as new data will be discontinuous
8465 recordTrack->mRecordBufferConverter->reset();
8466 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008467 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008468 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008469 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008470 return status;
8471 }
Eric Laurent81784c32012-11-19 14:55:58 -08008472}
8473
Eric Laurent81784c32012-11-19 14:55:58 -08008474void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8475{
8476 sp<SyncEvent> strongEvent = event.promote();
8477
8478 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008479 sp<RefBase> ptr = strongEvent->cookie().promote();
8480 if (ptr != 0) {
8481 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8482 recordTrack->handleSyncStartEvent(strongEvent);
8483 }
Eric Laurent81784c32012-11-19 14:55:58 -08008484 }
8485}
8486
Glenn Kastena8356f62013-07-25 14:37:52 -07008487bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008488 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008489 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008490 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008491 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008492 return false;
8493 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008494 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008495 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008496
Andy Hungabfab202019-03-07 19:45:54 -08008497 // NOTE: Waiting here is important to keep stop synchronous.
8498 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008499 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8500 mWaitWorkCV.broadcast(); // signal thread to stop
8501 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008502 }
Andy Hungce685402018-10-05 17:23:27 -07008503
8504 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008505 ALOGV("Record stopped OK");
8506 return true;
8507 }
Andy Hungce685402018-10-05 17:23:27 -07008508
8509 // don't handle anything - we've been invalidated or restarted and in a different state
8510 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8511 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008512 return false;
8513}
8514
Glenn Kasten0f11b512014-01-31 16:18:54 -08008515bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008516{
8517 return false;
8518}
8519
Glenn Kasten0f11b512014-01-31 16:18:54 -08008520status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008521{
8522#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8523 if (!isValidSyncEvent(event)) {
8524 return BAD_VALUE;
8525 }
8526
Glenn Kastend848eb42016-03-08 13:42:11 -08008527 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008528 status_t ret = NAME_NOT_FOUND;
8529
8530 Mutex::Autolock _l(mLock);
8531
8532 for (size_t i = 0; i < mTracks.size(); i++) {
8533 sp<RecordTrack> track = mTracks[i];
8534 if (eventSession == track->sessionId()) {
8535 (void) track->setSyncEvent(event);
8536 ret = NO_ERROR;
8537 }
8538 }
8539 return ret;
8540#else
8541 return BAD_VALUE;
8542#endif
8543}
8544
jiabin653cc0a2018-01-17 17:54:10 -08008545status_t AudioFlinger::RecordThread::getActiveMicrophones(
8546 std::vector<media::MicrophoneInfo>* activeMicrophones)
8547{
8548 ALOGV("RecordThread::getActiveMicrophones");
8549 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008550 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008551 return NO_INIT;
8552 }
jiabin9ff780e2018-03-19 18:19:52 -07008553 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8554 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008555}
8556
Paul McLean12340082019-03-19 09:35:05 -06008557status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8558 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008559{
Paul McLean12340082019-03-19 09:35:05 -06008560 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008561 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008562 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008563 return NO_INIT;
8564 }
Paul McLean12340082019-03-19 09:35:05 -06008565 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008566}
8567
Paul McLean12340082019-03-19 09:35:05 -06008568status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008569{
Paul McLean12340082019-03-19 09:35:05 -06008570 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008571 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008572 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008573 return NO_INIT;
8574 }
Paul McLean12340082019-03-19 09:35:05 -06008575 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008576}
8577
Eric Laurentec376dc2021-04-08 20:41:22 +02008578status_t AudioFlinger::RecordThread::shareAudioHistory(
8579 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8580 int64_t sharedAudioStartMs) {
8581 AutoMutex _l(mLock);
8582 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8583}
8584
8585status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8586 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8587 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008588
Eric Laurentec376dc2021-04-08 20:41:22 +02008589 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8590 return BAD_VALUE;
8591 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008592
8593 if (sharedAudioStartMs < 0
8594 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008595 return BAD_VALUE;
8596 }
8597
Eric Laurent2407ce32021-04-26 14:56:03 +02008598 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8599 // As we cannot detect more than one wraparound, only accept values up current write position
8600 // after one wraparound
8601 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8602 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02008603 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02008604 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8605 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02008606 // Bring the start frame position within the input buffer to match the documented
8607 // "best effort" behavior of the API.
8608 if (sharedOffset < 0) {
8609 sharedAudioStartFrames = mRsmpInRear;
8610 } else if (sharedOffset > mRsmpInFrames) {
8611 sharedAudioStartFrames =
8612 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02008613 }
8614
Eric Laurentec376dc2021-04-08 20:41:22 +02008615 mSharedAudioPackageName = sharedAudioPackageName;
8616 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008617 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02008618 } else {
8619 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02008620 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008621 }
8622 return NO_ERROR;
8623}
8624
Eric Laurent92d0a322021-07-16 15:32:33 +02008625void AudioFlinger::RecordThread::resetAudioHistory_l() {
8626 mSharedAudioSessionId = AUDIO_SESSION_NONE;
8627 mSharedAudioStartFrames = -1;
8628 mSharedAudioPackageName = "";
8629}
8630
Kevin Rocard069c2712018-03-29 19:09:14 -07008631void AudioFlinger::RecordThread::updateMetadata_l()
8632{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008633 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
8634 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07008635 }
8636 StreamInHalInterface::SinkMetadata metadata;
8637 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01008638 // Do not forward PatchRecord metadata to audio HAL
8639 if (track->isPatchTrack()) {
8640 continue;
8641 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008642 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01008643 record_track_metadata_v7_t trackMetadata;
8644 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07008645 .source = track->attributes().source,
8646 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +01008647 };
8648 trackMetadata.channel_mask = track->channelMask(),
8649 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8650
8651 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07008652 }
8653 mInput->stream->updateSinkMetadata(metadata);
8654}
8655
Eric Laurent81784c32012-11-19 14:55:58 -08008656// destroyTrack_l() must be called with ThreadBase::mLock held
8657void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8658{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008659 track->terminate();
8660 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008661
Eric Laurent81784c32012-11-19 14:55:58 -08008662 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008663 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008664 removeTrack_l(track);
8665 }
8666}
8667
8668void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8669{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008670 String8 result;
8671 track->appendDump(result, false /* active */);
8672 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8673
Eric Laurent81784c32012-11-19 14:55:58 -08008674 mTracks.remove(track);
8675 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008676 if (track->isFastTrack()) {
8677 ALOG_ASSERT(!mFastTrackAvail);
8678 mFastTrackAvail = true;
8679 }
Eric Laurent81784c32012-11-19 14:55:58 -08008680}
8681
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008682void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008683{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008684 AudioStreamIn *input = mInput;
8685 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8686 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008687 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008688 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008689 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008690 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008691 }
Andy Hungbfa64962017-06-12 14:43:19 -07008692
8693 if (input != nullptr) {
8694 dprintf(fd, " Hal stream dump:\n");
8695 (void)input->stream->dump(fd);
8696 }
8697
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008698 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008699 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008700
Glenn Kasten2f90c512015-12-02 11:40:09 -08008701 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8702 // while we are dumping it. It may be inconsistent, but it won't mutate!
8703 // This is a large object so we place it on the heap.
8704 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008705 const std::unique_ptr<FastCaptureDumpState> copy =
8706 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008707 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008708}
8709
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008710void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008711{
Eric Laurent81784c32012-11-19 14:55:58 -08008712 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008713 size_t numtracks = mTracks.size();
8714 size_t numactive = mActiveTracks.size();
8715 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008716 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008717 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008718 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008719 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008720 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008721 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008722 for (size_t i = 0; i < numtracks ; ++i) {
8723 sp<RecordTrack> track = mTracks[i];
8724 if (track != 0) {
8725 bool active = mActiveTracks.indexOf(track) >= 0;
8726 if (active) {
8727 numactiveseen++;
8728 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008729 result.append(prefix);
8730 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008731 }
Eric Laurent81784c32012-11-19 14:55:58 -08008732 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008733 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008734 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008735 }
8736
Marco Nelissenb2208842014-02-07 14:00:50 -08008737 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008738 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008739 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008740 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008741 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008742 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008743 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008744 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008745 result.append(prefix);
8746 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008747 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008748 }
Eric Laurent81784c32012-11-19 14:55:58 -08008749
8750 }
8751 write(fd, result.string(), result.size());
8752}
8753
Eric Laurent5ada82e2019-08-29 17:53:54 -07008754void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008755{
8756 Mutex::Autolock _l(mLock);
8757 for (size_t i = 0; i < mTracks.size() ; i++) {
8758 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008759 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008760 track->setSilenced(silenced);
8761 }
8762 }
8763}
Andy Hung73c02e42015-03-29 01:13:58 -07008764
8765void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8766{
8767 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8768 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008769 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008770 const int32_t rear = recordThread->mRsmpInRear;
8771 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008772 if (mRecordTrack->startFrames() >= 0) {
8773 int32_t startFrames = mRecordTrack->startFrames();
8774 // Accept a recent wraparound of mRsmpInRear
8775 if (startFrames <= rear) {
8776 deltaFrames = rear - startFrames;
8777 } else {
8778 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008779 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008780 // start frame cannot be further in the past than start of resampling buffer
8781 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8782 deltaFrames = recordThread->mRsmpInFrames;
8783 }
8784 }
8785 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008786}
8787
8788void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8789 size_t *framesAvailable, bool *hasOverrun)
8790{
8791 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8792 RecordThread *recordThread = (RecordThread *) threadBase.get();
8793 const int32_t rear = recordThread->mRsmpInRear;
8794 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008795 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008796
8797 size_t framesIn;
8798 bool overrun = false;
8799 if (filled < 0) {
8800 // should not happen, but treat like a massive overrun and re-sync
8801 framesIn = 0;
8802 mRsmpInFront = rear;
8803 overrun = true;
8804 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8805 framesIn = (size_t) filled;
8806 } else {
8807 // client is not keeping up with server, but give it latest data
8808 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008809 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8810 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008811 overrun = true;
8812 }
8813 if (framesAvailable != NULL) {
8814 *framesAvailable = framesIn;
8815 }
8816 if (hasOverrun != NULL) {
8817 *hasOverrun = overrun;
8818 }
8819}
8820
Eric Laurent81784c32012-11-19 14:55:58 -08008821// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008822status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008823 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008824{
Andy Hung73c02e42015-03-29 01:13:58 -07008825 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008826 if (threadBase == 0) {
8827 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008828 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008829 return NOT_ENOUGH_DATA;
8830 }
8831 RecordThread *recordThread = (RecordThread *) threadBase.get();
8832 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008833 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008834 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008835 // FIXME should not be P2 (don't want to increase latency)
8836 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008837 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008838 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008839
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008840 front &= recordThread->mRsmpInFramesP2 - 1;
8841 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008842 if (part1 > (size_t) filled) {
8843 part1 = filled;
8844 }
8845 size_t ask = buffer->frameCount;
8846 ALOG_ASSERT(ask > 0);
8847 if (part1 > ask) {
8848 part1 = ask;
8849 }
8850 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008851 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008852 buffer->raw = NULL;
8853 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008854 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008855 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008856 }
8857
Andy Hung57446612015-04-19 23:56:46 -07008858 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008859 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008860 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008861 return NO_ERROR;
8862}
8863
8864// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008865void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8866 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008867{
Hongwei Wang95e37682019-04-12 11:13:36 -07008868 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008869 if (stepCount == 0) {
8870 return;
8871 }
Andy Hung73c02e42015-03-29 01:13:58 -07008872 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8873 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008874 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008875 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008876 buffer->frameCount = 0;
8877}
8878
Eric Laurentd8365c52017-07-16 15:27:05 -07008879void AudioFlinger::RecordThread::checkBtNrec()
8880{
8881 Mutex::Autolock _l(mLock);
8882 checkBtNrec_l();
8883}
8884
8885void AudioFlinger::RecordThread::checkBtNrec_l()
8886{
8887 // disable AEC and NS if the device is a BT SCO headset supporting those
8888 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07008889 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008890 mAudioFlinger->btNrecIsOff();
8891 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8892 for (size_t i = 0; i < mEffectChains.size(); i++) {
8893 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8894 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8895 }
8896 }
8897}
8898
Andy Hung97a893e2015-03-29 01:03:07 -07008899
Eric Laurent10351942014-05-08 18:49:52 -07008900bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8901 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008902{
8903 bool reconfig = false;
8904
Eric Laurent10351942014-05-08 18:49:52 -07008905 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008906
Eric Laurent10351942014-05-08 18:49:52 -07008907 audio_format_t reqFormat = mFormat;
8908 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008909 // 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 -07008910 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8911
8912 AudioParameter param = AudioParameter(keyValuePair);
8913 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008914
8915 // scope for AutoPark extends to end of method
8916 AutoPark<FastCapture> park(mFastCapture);
8917
Eric Laurent10351942014-05-08 18:49:52 -07008918 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8919 // channel count change can be requested. Do we mandate the first client defines the
8920 // HAL sampling rate and channel count or do we allow changes on the fly?
8921 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8922 samplingRate = value;
8923 reconfig = true;
8924 }
8925 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008926 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008927 status = BAD_VALUE;
8928 } else {
8929 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008930 reconfig = true;
8931 }
Eric Laurent10351942014-05-08 18:49:52 -07008932 }
8933 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8934 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008935 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07008936 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07008937 status = BAD_VALUE;
8938 } else {
8939 channelMask = mask;
8940 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008941 }
Eric Laurent10351942014-05-08 18:49:52 -07008942 }
8943 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8944 // do not accept frame count changes if tracks are open as the track buffer
8945 // size depends on frame count and correct behavior would not be guaranteed
8946 // if frame count is changed after track creation
8947 if (mActiveTracks.size() > 0) {
8948 status = INVALID_OPERATION;
8949 } else {
8950 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008951 }
Eric Laurent10351942014-05-08 18:49:52 -07008952 }
8953 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008954 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008955 }
8956 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8957 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07008958 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008959 }
Glenn Kastene198c362013-08-13 09:13:36 -07008960
Eric Laurent10351942014-05-08 18:49:52 -07008961 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008962 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008963 if (status == INVALID_OPERATION) {
8964 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008965 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008966 }
8967 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008968 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00008969 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
8970 if (mInput->stream->getAudioProperties(&config) == OK &&
8971 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
8972 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07008973 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008974 status = NO_ERROR;
8975 }
Eric Laurent81784c32012-11-19 14:55:58 -08008976 }
Eric Laurent10351942014-05-08 18:49:52 -07008977 if (status == NO_ERROR) {
8978 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008979 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008980 }
8981 }
Eric Laurent81784c32012-11-19 14:55:58 -08008982 }
Eric Laurent10351942014-05-08 18:49:52 -07008983
Eric Laurent81784c32012-11-19 14:55:58 -08008984 return reconfig;
8985}
8986
8987String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8988{
Eric Laurent81784c32012-11-19 14:55:58 -08008989 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008990 if (initCheck() == NO_ERROR) {
8991 String8 out_s8;
8992 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8993 return out_s8;
8994 }
Eric Laurent81784c32012-11-19 14:55:58 -08008995 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008996 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008997}
8998
Mikhail Naganov88536df2021-07-26 17:30:29 -07008999void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009000 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009001 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009002 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009003 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009004 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009005 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009006 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9007 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009008 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009009 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009010 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009011 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009012 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009013 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009014 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009015 break;
9016 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07009017 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009018}
9019
Glenn Kastendeca2ae2014-02-07 10:25:56 -08009020void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009021{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009022 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9023 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009024 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009025 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9026 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009027 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9028 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009029 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009030 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009031 ALOGI("HAL format %#x is not linear pcm", mFormat);
9032 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009033 result = mInput->stream->getFrameSize(&mFrameSize);
9034 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009035 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9036 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009037 result = mInput->stream->getBufferSize(&mBufferSize);
9038 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009039 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009040 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9041 "mBufferSize=%zu, mFrameCount=%zu",
9042 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009043
Eric Laurentec376dc2021-04-08 20:41:22 +02009044 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9045 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009046 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009047
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009048 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9049 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009050
9051 audio_input_flags_t flags = mInput->flags;
9052 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9053 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9054 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9055 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9056 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9057 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9058 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9059 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9060 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009061}
9062
Glenn Kasten5f972c02014-01-13 09:59:31 -08009063uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08009064{
9065 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009066 uint32_t result;
9067 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9068 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009069 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009070 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009071}
9072
Glenn Kastend848eb42016-03-08 13:42:11 -08009073KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009074{
Glenn Kastend848eb42016-03-08 13:42:11 -08009075 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009076 Mutex::Autolock _l(mLock);
9077 for (size_t j = 0; j < mTracks.size(); ++j) {
9078 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009079 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009080 if (ids.indexOfKey(sessionId) < 0) {
9081 ids.add(sessionId, true);
9082 }
9083 }
9084 return ids;
9085}
9086
9087AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
9088{
9089 Mutex::Autolock _l(mLock);
9090 AudioStreamIn *input = mInput;
9091 mInput = NULL;
9092 return input;
9093}
9094
9095// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009096sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009097{
9098 if (mInput == NULL) {
9099 return NULL;
9100 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009101 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009102}
9103
9104status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
9105{
Eric Laurent81784c32012-11-19 14:55:58 -08009106 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009107 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009108 chain->setInBuffer(NULL);
9109 chain->setOutBuffer(NULL);
9110
9111 checkSuspendOnAddEffectChain_l(chain);
9112
Eric Laurent1b928682014-10-02 19:41:47 -07009113 // make sure enabled pre processing effects state is communicated to the HAL as we
9114 // just moved them to a new input stream.
9115 chain->syncHalEffectsState();
9116
Eric Laurent81784c32012-11-19 14:55:58 -08009117 mEffectChains.add(chain);
9118
9119 return NO_ERROR;
9120}
9121
9122size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
9123{
9124 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009125
9126 for (size_t i = 0; i < mEffectChains.size(); i++) {
9127 if (chain == mEffectChains[i]) {
9128 mEffectChains.removeAt(i);
9129 break;
9130 }
Eric Laurent81784c32012-11-19 14:55:58 -08009131 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009132 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009133}
9134
Eric Laurent1c333e22014-05-20 10:48:17 -07009135status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
9136 audio_patch_handle_t *handle)
9137{
9138 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009139
9140 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009141 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009142 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009143 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009144 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009145 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009146 }
9147
Eric Laurentd8365c52017-07-16 15:27:05 -07009148 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009149
9150 // store new source and send to effects
9151 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9152 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009153 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009154 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009155 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009156 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009157
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009158 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009159 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9160 status = hwDevice->createAudioPatch(patch->num_sources,
9161 patch->sources,
9162 patch->num_sinks,
9163 patch->sinks,
9164 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009165 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009166 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9167 patch->sinks[0].ext.mix.usecase.source,
9168 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009169 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009170 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009171
jiabinc52b1ff2019-10-31 17:20:42 -07009172 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009173 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009174 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009175 }
Eric Laurent296fb132015-05-01 11:38:42 -07009176
Andy Hungc2b11cb2020-04-22 09:04:01 -07009177 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009178 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009179 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009180 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009181 // also dispatch to active AudioRecords
9182 for (const auto &track : mActiveTracks) {
9183 track->logEndInterval();
9184 track->logBeginInterval(pathSourcesAsString);
9185 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009186 return status;
9187}
9188
9189status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9190{
9191 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009192
jiabinc52b1ff2019-10-31 17:20:42 -07009193 mPatch = audio_patch{};
9194 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009195
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009196 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009197 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9198 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009199 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009200 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009201 }
9202 return status;
9203}
9204
jiabinc52b1ff2019-10-31 17:20:42 -07009205void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
9206{
wendy lin56aa82b2020-12-02 15:19:55 +08009207 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009208 mOutDevices = outDevices;
9209 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9210 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009211 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009212 }
9213}
9214
Eric Laurentec376dc2021-04-08 20:41:22 +02009215int32_t AudioFlinger::RecordThread::getOldestFront_l()
9216{
9217 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009218 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009219 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009220 int32_t oldestFront = mRsmpInRear;
9221 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009222 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009223 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9224 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009225 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009226 if (filled > maxFilled) {
9227 oldestFront = front;
9228 maxFilled = filled;
9229 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009230 }
Eric Laurent92d0a322021-07-16 15:32:33 +02009231 if (maxFilled > mRsmpInFrames) {
9232 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9233 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009234 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009235}
9236
9237void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
9238{
9239 if (offset == 0) {
9240 return;
9241 }
9242 for (size_t i = 0; i < mTracks.size(); i++) {
9243 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9244 front = audio_utils::safe_sub_overflow(front, offset);
9245 mTracks[i]->mResamplerBufferProvider->setFront(front);
9246 }
9247}
9248
9249void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
9250{
9251 // This is the formula for calculating the temporary buffer size.
9252 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9253 // 1 full output buffer, regardless of the alignment of the available input.
9254 // The value is somewhat arbitrary, and could probably be even larger.
9255 // A larger value should allow more old data to be read after a track calls start(),
9256 // without increasing latency.
9257 //
9258 // Note this is independent of the maximum downsampling ratio permitted for capture.
9259 size_t minRsmpInFrames = mFrameCount * 7;
9260
9261 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9262 // capture history available to another client using the same session ID:
9263 // dimension the resampler input buffer accordingly.
9264
9265 // Get oldest client read position: getOldestFront_l() must be called before altering
9266 // mRsmpInRear, or mRsmpInFrames
9267 int32_t previousFront = getOldestFront_l();
9268 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9269 int32_t previousRear = mRsmpInRear;
9270 mRsmpInRear = 0;
9271
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009272 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
9273 && maxSharedAudioHistoryMs <= AudioFlinger::kMaxSharedAudioHistoryMs,
9274 "resizeInputBuffer_l() called with invalid max shared history %d",
9275 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009276 if (maxSharedAudioHistoryMs != 0) {
9277 // resizeInputBuffer_l should never be called with a non zero shared history if the
9278 // buffer was not already allocated
9279 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9280 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9281 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9282 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009283 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009284 return;
9285 }
9286 mRsmpInFrames = rsmpInFrames;
9287 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009288 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009289 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9290 // initialized
9291 if (mRsmpInFrames < minRsmpInFrames) {
9292 mRsmpInFrames = minRsmpInFrames;
9293 }
9294 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9295
9296 // TODO optimize audio capture buffer sizes ...
9297 // Here we calculate the size of the sliding buffer used as a source
9298 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9299 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9300 // be better to have it derived from the pipe depth in the long term.
9301 // The current value is higher than necessary. However it should not add to latency.
9302
9303 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9304 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9305
9306 void *rsmpInBuffer;
9307 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9308 // if posix_memalign fails, will segv here.
9309 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9310
9311 // Copy audio history if any from old buffer before freeing it
9312 if (previousRear != 0) {
9313 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9314 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9315
9316 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9317 previousFront &= previousRsmpInFramesP2 - 1;
9318 size_t part1 = previousRsmpInFramesP2 - previousFront;
9319 if (part1 > (size_t) unread) {
9320 part1 = unread;
9321 }
9322 if (part1 != 0) {
9323 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9324 part1 * mFrameSize);
9325 mRsmpInRear = part1;
9326 part1 = unread - part1;
9327 if (part1 != 0) {
9328 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9329 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9330 mRsmpInRear += part1;
9331 }
9332 }
9333 // Update front for all clients according to new rear
9334 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9335 } else {
9336 mRsmpInRear = 0;
9337 }
9338 free(mRsmpInBuffer);
9339 mRsmpInBuffer = rsmpInBuffer;
9340}
9341
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009342void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009343{
9344 Mutex::Autolock _l(mLock);
9345 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009346 if (record->getSource()) {
9347 mSource = record->getSource();
9348 }
Eric Laurent83b88082014-06-20 18:31:16 -07009349}
9350
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009351void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009352{
9353 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009354 if (mSource == record->getSource()) {
9355 mSource = mInput;
9356 }
Eric Laurent83b88082014-06-20 18:31:16 -07009357 destroyTrack_l(record);
9358}
9359
Mikhail Naganovdc769682018-05-04 15:34:08 -07009360void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07009361{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009362 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009363 config->role = AUDIO_PORT_ROLE_SINK;
9364 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9365 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009366 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9367 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9368 config->flags.input = mInput->flags;
9369 }
Eric Laurent83b88082014-06-20 18:31:16 -07009370}
Eric Laurent1c333e22014-05-20 10:48:17 -07009371
Eric Laurent6acd1d42017-01-04 14:23:29 -08009372// ----------------------------------------------------------------------------
9373// Mmap
9374// ----------------------------------------------------------------------------
9375
9376AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
9377 : mThread(thread)
9378{
Phil Burk9fabbf82017-08-03 12:02:00 -07009379 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009380}
9381
9382AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9383{
Phil Burk9fabbf82017-08-03 12:02:00 -07009384 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009385}
9386
9387status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9388 struct audio_mmap_buffer_info *info)
9389{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009390 return mThread->createMmapBuffer(minSizeFrames, info);
9391}
9392
9393status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9394{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009395 return mThread->getMmapPosition(position);
9396}
9397
jiabinb7d8c5a2020-08-26 17:24:52 -07009398status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9399 int64_t *timeNanos) {
9400 return mThread->getExternalPosition(position, timeNanos);
9401}
9402
Eric Laurenta54f1282017-07-01 19:39:32 -07009403status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009404 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009405
9406{
jiabind1f1cb62020-03-24 11:57:57 -07009407 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009408}
9409
9410status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9411{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009412 return mThread->stop(handle);
9413}
9414
Eric Laurent18b57012017-02-13 16:23:52 -08009415status_t AudioFlinger::MmapThreadHandle::standby()
9416{
Eric Laurent18b57012017-02-13 16:23:52 -08009417 return mThread->standby();
9418}
9419
Eric Laurent6acd1d42017-01-04 14:23:29 -08009420
9421AudioFlinger::MmapThread::MmapThread(
9422 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07009423 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009424 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009425 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009426 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009427 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009428 mActiveTracks(&this->mLocalLog),
9429 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9430 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009431{
Eric Laurent18b57012017-02-13 16:23:52 -08009432 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009433 readHalParameters_l();
9434}
9435
9436AudioFlinger::MmapThread::~MmapThread()
9437{
9438}
9439
9440void AudioFlinger::MmapThread::onFirstRef()
9441{
9442 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9443}
9444
9445void AudioFlinger::MmapThread::disconnect()
9446{
Eric Laurent331679c2018-04-16 17:03:16 -07009447 ActiveTracks<MmapTrack> activeTracks;
9448 {
9449 Mutex::Autolock _l(mLock);
9450 for (const sp<MmapTrack> &t : mActiveTracks) {
9451 activeTracks.add(t);
9452 }
9453 }
9454 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009455 stop(t->portId());
9456 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009457 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009458 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009459 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009460 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009461 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009462 }
9463}
9464
9465
9466void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9467 audio_stream_type_t streamType __unused,
9468 audio_session_t sessionId,
9469 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009470 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009471 audio_port_handle_t portId)
9472{
9473 mAttr = *attr;
9474 mSessionId = sessionId;
9475 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009476 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009477 mPortId = portId;
9478}
9479
9480status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9481 struct audio_mmap_buffer_info *info)
9482{
9483 if (mHalStream == 0) {
9484 return NO_INIT;
9485 }
Eric Laurent18b57012017-02-13 16:23:52 -08009486 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009487 return mHalStream->createMmapBuffer(minSizeFrames, info);
9488}
9489
9490status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9491{
9492 if (mHalStream == 0) {
9493 return NO_INIT;
9494 }
9495 return mHalStream->getMmapPosition(position);
9496}
9497
Eric Laurent331679c2018-04-16 17:03:16 -07009498status_t AudioFlinger::MmapThread::exitStandby()
9499{
9500 status_t ret = mHalStream->start();
9501 if (ret != NO_ERROR) {
9502 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9503 return ret;
9504 }
Andy Hungcf10d742020-04-28 15:38:24 -07009505 if (mStandby) {
9506 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009507 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07009508 mStandby = false;
9509 }
Eric Laurent331679c2018-04-16 17:03:16 -07009510 return NO_ERROR;
9511}
9512
Eric Laurenta54f1282017-07-01 19:39:32 -07009513status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009514 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009515 audio_port_handle_t *handle)
9516{
Eric Laurenta54f1282017-07-01 19:39:32 -07009517 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009518 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009519 if (mHalStream == 0) {
9520 return NO_INIT;
9521 }
9522
9523 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009524
Eric Laurenta54f1282017-07-01 19:39:32 -07009525 if (*handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009526 // For the first track, reuse portId and session allocated when the stream was opened.
9527 ret = exitStandby();
9528 if (ret == NO_ERROR) {
9529 acquireWakeLock();
9530 }
9531 return ret;
Eric Laurenta54f1282017-07-01 19:39:32 -07009532 }
9533
9534 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9535
9536 audio_io_handle_t io = mId;
9537 if (isOutput()) {
9538 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9539 config.sample_rate = mSampleRate;
9540 config.channel_mask = mChannelMask;
9541 config.format = mFormat;
9542 audio_stream_type_t stream = streamType();
9543 audio_output_flags_t flags =
9544 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009545 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009546 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02009547 bool isSpatialized;
Eric Laurenta54f1282017-07-01 19:39:32 -07009548 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9549 mSessionId,
9550 &stream,
Svet Ganov33761132021-05-13 22:51:08 +00009551 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009552 &config,
9553 flags,
9554 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009555 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02009556 &secondaryOutputs,
9557 &isSpatialized);
Kevin Rocard153f92d2018-12-18 18:33:28 -08009558 ALOGD_IF(!secondaryOutputs.empty(),
9559 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009560 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009561 audio_config_base_t config;
9562 config.sample_rate = mSampleRate;
9563 config.channel_mask = mChannelMask;
9564 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009565 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009566 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009567 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009568 mSessionId,
Svet Ganov33761132021-05-13 22:51:08 +00009569 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009570 &config,
9571 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9572 &deviceId,
9573 &portId);
9574 }
9575 // APM should not chose a different input or output stream for the same set of attributes
9576 // and audo configuration
9577 if (ret != NO_ERROR || io != mId) {
9578 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9579 __FUNCTION__, ret, io, mId);
9580 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009581 }
9582
9583 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009584 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009585 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08009586 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009587 }
9588
Eric Laurent331679c2018-04-16 17:03:16 -07009589 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009590 // abort if start is rejected by audio policy manager
9591 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009592 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009593 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009594 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009595 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009596 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009597 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009598 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009599 }
Eric Laurent331679c2018-04-16 17:03:16 -07009600 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009601 } else {
9602 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009603 }
9604 return PERMISSION_DENIED;
9605 }
9606
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009607 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009608 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +00009609 mChannelMask, mSessionId, isOutput(),
9610 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009611 IPCThreadState::self()->getCallingPid(), portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009612
Eric Laurent4eb58f12018-12-07 16:41:02 -08009613 if (isOutput()) {
9614 // force volume update when a new track is added
9615 mHalVolFloat = -1.0f;
9616 } else if (!track->isSilenced_l()) {
9617 for (const sp<MmapTrack> &t : mActiveTracks) {
Svet Ganov33761132021-05-13 22:51:08 +00009618 if (t->isSilenced_l() && t->uid() != client.attributionSource.uid)
Eric Laurent4eb58f12018-12-07 16:41:02 -08009619 t->invalidate();
9620 }
9621 }
9622
9623
Eric Laurent6acd1d42017-01-04 14:23:29 -08009624 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009625 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009626 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02009627 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009628 chain->incTrackCnt();
9629 chain->incActiveTrackCnt();
9630 }
9631
Andy Hungc2b11cb2020-04-22 09:04:01 -07009632 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009633 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009634 broadcast_l();
9635
Eric Laurenta54f1282017-07-01 19:39:32 -07009636 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009637
9638 return NO_ERROR;
9639}
9640
9641status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9642{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009643 ALOGV("%s handle %d", __FUNCTION__, handle);
9644
9645 if (mHalStream == 0) {
9646 return NO_INIT;
9647 }
9648
Eric Laurenta54f1282017-07-01 19:39:32 -07009649 if (handle == mPortId) {
9650 mHalStream->stop();
Phil Burk98ab4082020-09-25 21:46:34 +00009651 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009652 return NO_ERROR;
9653 }
9654
Eric Laurent331679c2018-04-16 17:03:16 -07009655 Mutex::Autolock _l(mLock);
9656
Eric Laurent6acd1d42017-01-04 14:23:29 -08009657 sp<MmapTrack> track;
9658 for (const sp<MmapTrack> &t : mActiveTracks) {
9659 if (handle == t->portId()) {
9660 track = t;
9661 break;
9662 }
9663 }
9664 if (track == 0) {
9665 return BAD_VALUE;
9666 }
9667
9668 mActiveTracks.remove(track);
9669
Eric Laurent331679c2018-04-16 17:03:16 -07009670 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009671 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009672 AudioSystem::stopOutput(track->portId());
9673 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009674 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009675 AudioSystem::stopInput(track->portId());
9676 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009677 }
Eric Laurent331679c2018-04-16 17:03:16 -07009678 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009679
9680 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9681 if (chain != 0) {
9682 chain->decActiveTrackCnt();
9683 chain->decTrackCnt();
9684 }
9685
9686 broadcast_l();
9687
Eric Laurent6acd1d42017-01-04 14:23:29 -08009688 return NO_ERROR;
9689}
9690
Eric Laurent18b57012017-02-13 16:23:52 -08009691status_t AudioFlinger::MmapThread::standby()
9692{
9693 ALOGV("%s", __FUNCTION__);
9694
9695 if (mHalStream == 0) {
9696 return NO_INIT;
9697 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009698 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009699 return INVALID_OPERATION;
9700 }
9701 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009702 if (!mStandby) {
9703 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009704 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07009705 mStandby = true;
9706 }
Eric Laurent18b57012017-02-13 16:23:52 -08009707 releaseWakeLock();
9708 return NO_ERROR;
9709}
9710
Eric Laurent6acd1d42017-01-04 14:23:29 -08009711
9712void AudioFlinger::MmapThread::readHalParameters_l()
9713{
9714 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9715 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9716 mFormat = mHALFormat;
9717 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9718 result = mHalStream->getFrameSize(&mFrameSize);
9719 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009720 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9721 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009722 result = mHalStream->getBufferSize(&mBufferSize);
9723 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9724 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009725
Andy Hungcf10d742020-04-28 15:38:24 -07009726 // TODO: make a readHalParameters call?
9727 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009728 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9729 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9730 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9731 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9732 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9733 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9734 /*
9735 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9736 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9737 (int32_t)mHapticChannelMask)
9738 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9739 (int32_t)mHapticChannelCount)
9740 */
9741 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9742 formatToString(mHALFormat).c_str())
9743 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9744 (int32_t)mFrameCount) // sic - added HAL
9745 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009746}
9747
9748bool AudioFlinger::MmapThread::threadLoop()
9749{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009750 checkSilentMode_l();
9751
9752 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9753
9754 while (!exitPending())
9755 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009756 Vector< sp<EffectChain> > effectChains;
9757
Andy Hung13850be2019-03-14 11:33:09 -07009758 { // under Thread lock
9759 Mutex::Autolock _l(mLock);
9760
Eric Laurent6acd1d42017-01-04 14:23:29 -08009761 if (mSignalPending) {
9762 // A signal was raised while we were unlocked
9763 mSignalPending = false;
9764 } else {
9765 if (mConfigEvents.isEmpty()) {
9766 // we're about to wait, flush the binder command buffer
9767 IPCThreadState::self()->flushCommands();
9768
9769 if (exitPending()) {
9770 break;
9771 }
9772
Eric Laurent6acd1d42017-01-04 14:23:29 -08009773 // wait until we have something to do...
9774 ALOGV("%s going to sleep", myName.string());
9775 mWaitWorkCV.wait(mLock);
9776 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009777
9778 checkSilentMode_l();
9779
9780 continue;
9781 }
9782 }
9783
9784 processConfigEvents_l();
9785
9786 processVolume_l();
9787
9788 checkInvalidTracks_l();
9789
9790 mActiveTracks.updatePowerState(this);
9791
Kevin Rocard069c2712018-03-29 19:09:14 -07009792 updateMetadata_l();
9793
Eric Laurent6acd1d42017-01-04 14:23:29 -08009794 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009795 } // release Thread lock
9796
Eric Laurent6acd1d42017-01-04 14:23:29 -08009797 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009798 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009799 }
Andy Hung13850be2019-03-14 11:33:09 -07009800
9801 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009802 unlockEffectChains(effectChains);
9803 // Effect chains will be actually deleted here if they were removed from
9804 // mEffectChains list during mixing or effects processing
9805 }
9806
9807 threadLoop_exit();
9808
9809 if (!mStandby) {
9810 threadLoop_standby();
9811 mStandby = true;
9812 }
9813
Eric Laurent6acd1d42017-01-04 14:23:29 -08009814 ALOGV("Thread %p type %d exiting", this, mType);
9815 return false;
9816}
9817
9818// checkForNewParameter_l() must be called with ThreadBase::mLock held
9819bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9820 status_t& status)
9821{
9822 AudioParameter param = AudioParameter(keyValuePair);
9823 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009824 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009825 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009826 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009827 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009828 if (sendToHal) {
9829 status = mHalStream->setParameters(keyValuePair);
9830 } else {
9831 status = NO_ERROR;
9832 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009833
9834 return false;
9835}
9836
9837String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9838{
9839 Mutex::Autolock _l(mLock);
9840 String8 out_s8;
9841 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
9842 return out_s8;
9843 }
9844 return String8();
9845}
9846
Mikhail Naganov88536df2021-07-26 17:30:29 -07009847void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009848 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009849 sp<AudioIoDescriptor> desc;
9850 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009851 switch (event) {
9852 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009853 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009854 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009855 isInput = true;
9856 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009857 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009858 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009859 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009860 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
9861 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009862 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009863 case AUDIO_INPUT_CLOSED:
9864 case AUDIO_OUTPUT_CLOSED:
9865 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009866 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009867 break;
9868 }
9869 mAudioFlinger->ioConfigChanged(event, desc, pid);
9870}
9871
9872status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
9873 audio_patch_handle_t *handle)
9874{
9875 status_t status = NO_ERROR;
9876
9877 // store new device and send to effects
9878 audio_devices_t type = AUDIO_DEVICE_NONE;
9879 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -07009880 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
9881 AudioDeviceTypeAddr sourceDeviceTypeAddr;
9882 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009883 if (isOutput()) {
9884 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07009885 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
9886 && !mAudioHwDev->supportsAudioPatches(),
9887 "Enumerated device type(%#x) must not be used "
9888 "as it does not support audio patches",
9889 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07009890 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07009891 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
9892 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009893 }
9894 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009895 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009896 } else {
9897 type = patch->sources[0].ext.device.type;
9898 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009899 numDevices = mPatch.num_sources;
9900 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009901 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009902 }
9903
9904 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009905 if (isOutput()) {
9906 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
9907 } else {
9908 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
9909 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009910 }
9911
jiabinc52b1ff2019-10-31 17:20:42 -07009912 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009913 // store new source and send to effects
9914 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9915 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
9916 for (size_t i = 0; i < mEffectChains.size(); i++) {
9917 mEffectChains[i]->setAudioSource_l(mAudioSource);
9918 }
9919 }
9920 }
9921
9922 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009923 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
9924 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009925 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009926 audio_port_config port;
9927 std::optional<audio_source_t> source;
9928 if (isOutput()) {
9929 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -08009930 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009931 port = patch->sources[0];
9932 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009933 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009934 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009935 *handle = AUDIO_PATCH_HANDLE_NONE;
9936 }
9937
jiabinc52b1ff2019-10-31 17:20:42 -07009938 if (numDevices == 0 || mDeviceId != deviceId) {
9939 if (isOutput()) {
9940 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
9941 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07009942 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -07009943 } else {
9944 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
9945 mInDeviceTypeAddr = sourceDeviceTypeAddr;
9946 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08009947 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009948 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009949 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08009950 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07009951 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009952 }
jiabinc52b1ff2019-10-31 17:20:42 -07009953 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009954 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009955 }
9956 return status;
9957}
9958
9959status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9960{
9961 status_t status = NO_ERROR;
9962
jiabinc52b1ff2019-10-31 17:20:42 -07009963 mPatch = audio_patch{};
9964 mOutDeviceTypeAddrs.clear();
9965 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009966
9967 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9968 supportsAudioPatches : false;
9969
9970 if (supportsAudioPatches) {
9971 status = mHalDevice->releaseAudioPatch(handle);
9972 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009973 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009974 }
9975 return status;
9976}
9977
Mikhail Naganovdc769682018-05-04 15:34:08 -07009978void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009979{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009980 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009981 if (isOutput()) {
9982 config->role = AUDIO_PORT_ROLE_SOURCE;
9983 config->ext.mix.hw_module = mAudioHwDev->handle();
9984 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9985 } else {
9986 config->role = AUDIO_PORT_ROLE_SINK;
9987 config->ext.mix.hw_module = mAudioHwDev->handle();
9988 config->ext.mix.usecase.source = mAudioSource;
9989 }
9990}
9991
9992status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9993{
9994 audio_session_t session = chain->sessionId();
9995
9996 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9997 // Attach all tracks with same session ID to this chain.
9998 // indicate all active tracks in the chain
9999 for (const sp<MmapTrack> &track : mActiveTracks) {
10000 if (session == track->sessionId()) {
10001 chain->incTrackCnt();
10002 chain->incActiveTrackCnt();
10003 }
10004 }
10005
10006 chain->setThread(this);
10007 chain->setInBuffer(nullptr);
10008 chain->setOutBuffer(nullptr);
10009 chain->syncHalEffectsState();
10010
10011 mEffectChains.add(chain);
10012 checkSuspendOnAddEffectChain_l(chain);
10013 return NO_ERROR;
10014}
10015
10016size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
10017{
10018 audio_session_t session = chain->sessionId();
10019
10020 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10021
10022 for (size_t i = 0; i < mEffectChains.size(); i++) {
10023 if (chain == mEffectChains[i]) {
10024 mEffectChains.removeAt(i);
10025 // detach all active tracks from the chain
10026 // detach all tracks with same session ID from this chain
10027 for (const sp<MmapTrack> &track : mActiveTracks) {
10028 if (session == track->sessionId()) {
10029 chain->decActiveTrackCnt();
10030 chain->decTrackCnt();
10031 }
10032 }
10033 break;
10034 }
10035 }
10036 return mEffectChains.size();
10037}
10038
Eric Laurent6acd1d42017-01-04 14:23:29 -080010039void AudioFlinger::MmapThread::threadLoop_standby()
10040{
10041 mHalStream->standby();
10042}
10043
10044void AudioFlinger::MmapThread::threadLoop_exit()
10045{
Phil Burk7dce7282017-09-27 13:51:41 -070010046 // Do not call callback->onTearDown() because it is redundant for thread exit
10047 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010048}
10049
10050status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
10051{
10052 return BAD_VALUE;
10053}
10054
10055bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
10056{
10057 return false;
10058}
10059
10060status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
10061 const effect_descriptor_t *desc, audio_session_t sessionId)
10062{
10063 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010064 if (audio_is_global_session(sessionId)) {
10065 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010066 desc->name, mThreadName);
10067 return BAD_VALUE;
10068 }
10069
10070 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10071 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10072 desc->name);
10073 return BAD_VALUE;
10074 }
10075 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010076 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10077 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010078 return BAD_VALUE;
10079 }
10080
10081 // Only allow effects without processing load or latency
10082 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10083 return BAD_VALUE;
10084 }
10085
jiabineb3bda02020-06-30 14:07:03 -070010086 if (EffectModule::isHapticGenerator(&desc->type)) {
10087 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10088 return BAD_VALUE;
10089 }
10090
Eric Laurent6acd1d42017-01-04 14:23:29 -080010091 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010092}
10093
10094void AudioFlinger::MmapThread::checkInvalidTracks_l()
10095{
10096 for (const sp<MmapTrack> &track : mActiveTracks) {
10097 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010098 sp<MmapStreamCallback> callback = mCallback.promote();
10099 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010100 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -070010101 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -070010102 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -070010103 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10104 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
10105 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010106 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010107 }
10108 }
10109}
10110
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010111void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010112{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010113 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10114 mAttr.content_type, mAttr.usage, mAttr.source);
10115 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010116 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010117 dprintf(fd, " No active clients\n");
10118 }
10119}
10120
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010121void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010122{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010123 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010124 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010125 dprintf(fd, " %zu Tracks\n", numtracks);
10126 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010127 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010128 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010129 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010130 for (size_t i = 0; i < numtracks ; ++i) {
10131 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010132 result.append(prefix);
10133 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010134 }
10135 } else {
10136 dprintf(fd, "\n");
10137 }
10138 write(fd, result.string(), result.size());
10139}
10140
10141AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
10142 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010143 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010144 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010145 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010146 mStreamVolume(1.0),
10147 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010148 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010149{
10150 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10151 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
10152 mMasterVolume = audioFlinger->masterVolume_l();
10153 mMasterMute = audioFlinger->masterMute_l();
10154 if (mAudioHwDev) {
10155 if (mAudioHwDev->canSetMasterVolume()) {
10156 mMasterVolume = 1.0;
10157 }
10158
10159 if (mAudioHwDev->canSetMasterMute()) {
10160 mMasterMute = false;
10161 }
10162 }
10163}
10164
10165void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
10166 audio_stream_type_t streamType,
10167 audio_session_t sessionId,
10168 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010169 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010170 audio_port_handle_t portId)
10171{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010172 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010173 mStreamType = streamType;
10174}
10175
10176AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
10177{
10178 Mutex::Autolock _l(mLock);
10179 AudioStreamOut *output = mOutput;
10180 mOutput = NULL;
10181 return output;
10182}
10183
10184void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
10185{
10186 Mutex::Autolock _l(mLock);
10187 // Don't apply master volume in SW if our HAL can do it for us.
10188 if (mAudioHwDev &&
10189 mAudioHwDev->canSetMasterVolume()) {
10190 mMasterVolume = 1.0;
10191 } else {
10192 mMasterVolume = value;
10193 }
10194}
10195
10196void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
10197{
10198 Mutex::Autolock _l(mLock);
10199 // Don't apply master mute in SW if our HAL can do it for us.
10200 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10201 mMasterMute = false;
10202 } else {
10203 mMasterMute = muted;
10204 }
10205}
10206
10207void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
10208{
10209 Mutex::Autolock _l(mLock);
10210 if (stream == mStreamType) {
10211 mStreamVolume = value;
10212 broadcast_l();
10213 }
10214}
10215
10216float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
10217{
10218 Mutex::Autolock _l(mLock);
10219 if (stream == mStreamType) {
10220 return mStreamVolume;
10221 }
10222 return 0.0f;
10223}
10224
10225void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
10226{
10227 Mutex::Autolock _l(mLock);
10228 if (stream == mStreamType) {
10229 mStreamMute= muted;
10230 broadcast_l();
10231 }
10232}
10233
10234void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
10235{
10236 Mutex::Autolock _l(mLock);
10237 if (streamType == mStreamType) {
10238 for (const sp<MmapTrack> &track : mActiveTracks) {
10239 track->invalidate();
10240 }
10241 broadcast_l();
10242 }
10243}
10244
10245void AudioFlinger::MmapPlaybackThread::processVolume_l()
10246{
10247 float volume;
10248
10249 if (mMasterMute || mStreamMute) {
10250 volume = 0;
10251 } else {
10252 volume = mMasterVolume * mStreamVolume;
10253 }
10254
10255 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010256
10257 // Convert volumes from float to 8.24
10258 uint32_t vol = (uint32_t)(volume * (1 << 24));
10259
10260 // Delegate volume control to effect in track effect chain if needed
10261 // only one effect chain can be present on DirectOutputThread, so if
10262 // there is one, the track is connected to it
10263 if (!mEffectChains.isEmpty()) {
10264 mEffectChains[0]->setVolume_l(&vol, &vol);
10265 volume = (float)vol / (1 << 24);
10266 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010267 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010268 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10269 mHalVolFloat = volume; // HW volume control worked, so update value.
10270 mNoCallbackWarningCount = 0;
10271 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010272 sp<MmapStreamCallback> callback = mCallback.promote();
10273 if (callback != 0) {
10274 int channelCount;
10275 if (isOutput()) {
10276 channelCount = audio_channel_count_from_out_mask(mChannelMask);
10277 } else {
10278 channelCount = audio_channel_count_from_in_mask(mChannelMask);
10279 }
10280 Vector<float> values;
10281 for (int i = 0; i < channelCount; i++) {
10282 values.add(volume);
10283 }
Phil Burk56ecf3e2018-03-12 15:38:17 -070010284 mHalVolFloat = volume; // SW volume control worked, so update value.
10285 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010286 mLock.unlock();
10287 callback->onVolumeChanged(mChannelMask, values);
10288 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010289 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010290 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10291 ALOGW("Could not set MMAP stream volume: no volume callback!");
10292 mNoCallbackWarningCount++;
10293 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010294 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010295 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010296 for (const sp<MmapTrack> &track : mActiveTracks) {
10297 track->setMetadataHasChanged();
10298 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010299 }
10300}
10301
Kevin Rocard069c2712018-03-29 19:09:14 -070010302void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
10303{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010304 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10305 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010306 }
10307 StreamOutHalInterface::SourceMetadata metadata;
10308 for (const sp<MmapTrack> &track : mActiveTracks) {
10309 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010310 playback_track_metadata_v7_t trackMetadata;
10311 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010312 .usage = track->attributes().usage,
10313 .content_type = track->attributes().content_type,
10314 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010315 };
10316 trackMetadata.channel_mask = track->channelMask(),
10317 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10318 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010319 }
10320 mOutput->stream->updateSourceMetadata(metadata);
10321}
10322
Eric Laurent6acd1d42017-01-04 14:23:29 -080010323void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
10324{
10325 if (!mMasterMute) {
10326 char value[PROPERTY_VALUE_MAX];
10327 if (property_get("ro.audio.silent", value, "0") > 0) {
10328 char *endptr;
10329 unsigned long ul = strtoul(value, &endptr, 0);
10330 if (*endptr == '\0' && ul != 0) {
10331 ALOGD("Silence is golden");
10332 // The setprop command will not allow a property to be changed after
10333 // the first time it is set, so we don't have to worry about un-muting.
10334 setMasterMute_l(true);
10335 }
10336 }
10337 }
10338}
10339
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010340void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
10341{
10342 MmapThread::toAudioPortConfig(config);
10343 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10344 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10345 config->flags.output = mOutput->flags;
10346 }
10347}
10348
jiabinb7d8c5a2020-08-26 17:24:52 -070010349status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
10350 int64_t *timeNanos)
10351{
10352 if (mOutput == nullptr) {
10353 return NO_INIT;
10354 }
10355 struct timespec timestamp;
10356 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10357 if (status == NO_ERROR) {
10358 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10359 }
10360 return status;
10361}
10362
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010363void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010364{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010365 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010366
Glenn Kastend3bb6452016-12-05 18:14:37 -080010367 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10368 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010369 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10370}
10371
10372AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10373 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010374 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010375 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010376 mInput(input)
10377{
10378 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10379 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10380}
10381
Eric Laurent331679c2018-04-16 17:03:16 -070010382status_t AudioFlinger::MmapCaptureThread::exitStandby()
10383{
Phil Burkf054fc32018-12-06 09:45:59 -080010384 {
10385 // mInput might have been cleared by clearInput()
10386 Mutex::Autolock _l(mLock);
10387 if (mInput != nullptr && mInput->stream != nullptr) {
10388 mInput->stream->setGain(1.0f);
10389 }
10390 }
Eric Laurent331679c2018-04-16 17:03:16 -070010391 return MmapThread::exitStandby();
10392}
10393
Eric Laurent6acd1d42017-01-04 14:23:29 -080010394AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10395{
10396 Mutex::Autolock _l(mLock);
10397 AudioStreamIn *input = mInput;
10398 mInput = NULL;
10399 return input;
10400}
Kevin Rocard069c2712018-03-29 19:09:14 -070010401
Eric Laurent331679c2018-04-16 17:03:16 -070010402
10403void AudioFlinger::MmapCaptureThread::processVolume_l()
10404{
10405 bool changed = false;
10406 bool silenced = false;
10407
10408 sp<MmapStreamCallback> callback = mCallback.promote();
10409 if (callback == 0) {
10410 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10411 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10412 mNoCallbackWarningCount++;
10413 }
10414 }
10415
10416 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10417 // track is silenced and unmute otherwise
10418 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10419 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10420 changed = true;
10421 silenced = mActiveTracks[i]->isSilenced_l();
10422 }
10423 }
10424
10425 if (changed) {
10426 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10427 }
10428}
10429
Kevin Rocard069c2712018-03-29 19:09:14 -070010430void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10431{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010432 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10433 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010434 }
10435 StreamInHalInterface::SinkMetadata metadata;
10436 for (const sp<MmapTrack> &track : mActiveTracks) {
10437 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010438 record_track_metadata_v7_t trackMetadata;
10439 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010440 .source = track->attributes().source,
10441 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010442 };
10443 trackMetadata.channel_mask = track->channelMask(),
10444 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10445 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010446 }
10447 mInput->stream->updateSinkMetadata(metadata);
10448}
10449
Eric Laurent5ada82e2019-08-29 17:53:54 -070010450void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010451{
10452 Mutex::Autolock _l(mLock);
10453 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010454 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010455 mActiveTracks[i]->setSilenced_l(silenced);
10456 broadcast_l();
10457 }
10458 }
10459}
10460
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010461void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10462{
10463 MmapThread::toAudioPortConfig(config);
10464 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10465 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10466 config->flags.input = mInput->flags;
10467 }
10468}
10469
jiabinb7d8c5a2020-08-26 17:24:52 -070010470status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10471 uint64_t *position, int64_t *timeNanos)
10472{
10473 if (mInput == nullptr) {
10474 return NO_INIT;
10475 }
10476 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10477}
10478
Glenn Kasten63238ef2015-03-02 15:50:29 -080010479} // namespace android