blob: 0965aa2d955a268fcc2dd0176e831b006ad22b55 [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"
Vlad Popab042ee62022-10-20 18:05:00 +020020// #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>
Vlad Popae8d99472022-06-30 16:02:48 +020034#include <binder/PersistableBundle.h>
jiabinc52b1ff2019-10-31 17:20:42 -070035#include <media/AudioContainers.h>
36#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070037#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070038#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080039#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070040#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080041#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080042#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043
44#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070045#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010046#include <audio_utils/Balance.h>
Vlad Popab042ee62022-10-20 18:05:00 +020047#include <audio_utils/MelProcessor.h>
jiabinf6eb4c32020-02-25 14:06:25 -080048#include <audio_utils/Metadata.h>
jiabin245cdd92018-12-07 17:55:15 -080049#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080050#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080051#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080052#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070053#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070054#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070055#include <system/audio_effects/effect_aec.h>
Eric Laurentb3f315a2021-07-13 15:09:05 +020056#include <system/audio_effects/effect_downmix.h>
57#include <system/audio_effects/effect_ns.h>
Eric Laurent1c5e2e32021-08-18 18:50:28 +020058#include <system/audio_effects/effect_spatializer.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070059#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080060
61// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070062#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080063#include <media/nbaio/AudioStreamOutSink.h>
64#include <media/nbaio/MonoPipe.h>
65#include <media/nbaio/MonoPipeReader.h>
66#include <media/nbaio/Pipe.h>
67#include <media/nbaio/PipeReader.h>
68#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080069#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070070#include <mediautils/Process.h>
Eric Laurent81784c32012-11-19 14:55:58 -080071
Mikhail Naganov2996f672019-04-18 12:29:59 -070072#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080073#include <powermanager/PowerManager.h>
74
Kevin Rocard7588ff42018-01-08 11:11:30 -080075#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070076#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080077
Eric Laurent81784c32012-11-19 14:55:58 -080078#include "AudioFlinger.h"
Andy Hung71742ab2023-07-07 13:47:37 -070079#include "Threads.h"
80
Andy Hungab7ef302018-05-15 19:35:29 -070081#include <mediautils/SchedulingPolicyService.h>
82#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080083
Eric Laurent81784c32012-11-19 14:55:58 -080084#ifdef ADD_BATTERY_DATA
85#include <media/IMediaPlayerService.h>
86#include <media/IMediaDeathNotifier.h>
87#endif
88
Eric Laurent81784c32012-11-19 14:55:58 -080089#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070090#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080091#include <cpustats/ThreadCpuUsage.h>
92#endif
93
Andy Hungbef3a1e2023-05-23 17:36:46 -070094#include <fastpath/AutoPark.h>
Glenn Kastenc05b8d72016-03-24 09:48:17 -070095
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080096#include <pthread.h>
Andy Hungb776e372023-05-24 11:53:47 -070097#include <afutils/TypedLogger.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080098
Eric Laurent81784c32012-11-19 14:55:58 -080099// ----------------------------------------------------------------------------
100
101// Note: the following macro is used for extremely verbose logging message. In
102// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
103// 0; but one side effect of this is to turn all LOGV's as well. Some messages
104// are so verbose that we want to suppress them even when we have ALOG_ASSERT
105// turned on. Do not uncomment the #def below unless you really know what you
106// are doing and want to see all of the extremely verbose messages.
107//#define VERY_VERY_VERBOSE_LOGGING
108#ifdef VERY_VERY_VERBOSE_LOGGING
109#define ALOGVV ALOGV
110#else
111#define ALOGVV(a...) do { } while(0)
112#endif
113
Andy Hung6770c6f2015-04-07 13:43:36 -0700114// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700115#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700116
Andy Hung6770c6f2015-04-07 13:43:36 -0700117template <typename T>
118static inline T min(const T& a, const T& b)
119{
120 return a < b ? a : b;
121}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700122
Eric Laurent81784c32012-11-19 14:55:58 -0800123namespace android {
124
Andy Hung71742ab2023-07-07 13:47:37 -0700125using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700126using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000127using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700128
Eric Laurent81784c32012-11-19 14:55:58 -0800129// retry counts for buffer fill timeout
130// 50 * ~20msecs = 1 second
131static const int8_t kMaxTrackRetries = 50;
132static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700133
Eric Laurent81784c32012-11-19 14:55:58 -0800134// allow less retry attempts on direct output thread.
135// direct outputs can be a scarce resource in audio hardware and should
136// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700137// Notes:
138// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
139// in case the data write is bursty for the AudioTrack. The application
140// should endeavor to write at least once every kMaxTrackRetriesDirectMs
141// to prevent an underrun situation. If the data is bursty, then
142// the application can also throttle the data sent to be even.
143// 2) For compressed audio data, any data present in the AudioTrack buffer
144// will be sent and reset the retry count. This delivers data as
145// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
146// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
147// of data to be available, then any remaining data is delivered.
148// This is required to ensure the last bit of data is delivered before underrun.
149//
150// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
151// or the size of the HAL period for proportional / linear PCM tracks.
152static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800153
154// don't warn about blocked writes or record buffer overflows more often than this
155static const nsecs_t kWarningThrottleNs = seconds(5);
156
157// RecordThread loop sleep time upon application overrun or audio HAL read error
158static const int kRecordThreadSleepUs = 5000;
159
Eric Laurent10351942014-05-08 18:49:52 -0700160// maximum time to wait in sendConfigEvent_l() for a status to be received
161static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800162
163// minimum sleep time for the mixer thread loop when tracks are active but in underrun
164static const uint32_t kMinThreadSleepTimeUs = 5000;
165// maximum divider applied to the active sleep time in the mixer thread loop
166static const uint32_t kMaxThreadSleepTimeShift = 2;
167
Andy Hung09a50072014-02-27 14:30:47 -0800168// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700169// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800170static const uint32_t kMinNormalSinkBufferSizeMs = 20;
171// maximum normal sink buffer size
172static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800173
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700174// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
175// FIXME This should be based on experimentally observed scheduling jitter
176static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
177
Eric Laurent972a1732013-09-04 09:42:59 -0700178// Offloaded output thread standby delay: allows track transition without going to standby
179static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
180
Eric Laurent51716182016-02-29 18:00:56 -0800181// Direct output thread minimum sleep time in idle or active(underrun) state
182static const nsecs_t kDirectMinSleepTimeUs = 10000;
183
Brian Lindahl9e661ad2022-07-27 18:01:07 +0200184// Minimum amount of time between checking to see if the timestamp is advancing
185// for underrun detection. If we check too frequently, we may not detect a
186// timestamp update and will falsely detect underrun.
187static const nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1000;
188
Glenn Kasten1b291842016-07-18 14:55:21 -0700189// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
190// balance between power consumption and latency, and allows threads to be scheduled reliably
191// by the CFS scheduler.
192// FIXME Express other hardcoded references to 20ms with references to this constant and move
193// it appropriately.
194#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800195
Eric Laurent81784c32012-11-19 14:55:58 -0800196// Whether to use fast mixer
197static const enum {
198 FastMixer_Never, // never initialize or use: for debugging only
199 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
200 // normal mixer multiplier is 1
201 FastMixer_Static, // initialize if needed, then use all the time if initialized,
202 // multiplier is calculated based on min & max normal mixer buffer size
203 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
204 // multiplier is calculated based on min & max normal mixer buffer size
205 // FIXME for FastMixer_Dynamic:
206 // Supporting this option will require fixing HALs that can't handle large writes.
207 // For example, one HAL implementation returns an error from a large write,
208 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
209 // We could either fix the HAL implementations, or provide a wrapper that breaks
210 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
211} kUseFastMixer = FastMixer_Static;
212
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700213// Whether to use fast capture
214static const enum {
215 FastCapture_Never, // never initialize or use: for debugging only
216 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
217 FastCapture_Static, // initialize if needed, then use all the time if initialized
218} kUseFastCapture = FastCapture_Static;
219
Eric Laurent81784c32012-11-19 14:55:58 -0800220// Priorities for requestPriority
221static const int kPriorityAudioApp = 2;
222static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700223static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800224
Glenn Kastenea38ee72016-04-18 11:08:01 -0700225// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
226// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
227// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700228
229// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800230static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800231
Glenn Kasten03490092014-05-27 12:30:54 -0700232// The minimum and maximum allowed values
233static const int kFastTrackMultiplierMin = 1;
234static const int kFastTrackMultiplierMax = 2;
235
236// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
237static int sFastTrackMultiplier = kFastTrackMultiplier;
238
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700239// See Thread::readOnlyHeap().
240// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
241// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
242// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700243static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700244
Eric Laurent81784c32012-11-19 14:55:58 -0800245// ----------------------------------------------------------------------------
246
Andy Hungb68f5eb2019-12-03 16:49:17 -0800247// TODO: move all toString helpers to audio.h
248// under #ifdef __cplusplus #endif
249static std::string patchSinksToString(const struct audio_patch *patch)
250{
251 std::stringstream ss;
252 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700253 if (i > 0) {
254 ss << "|";
255 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800256 ss << "(" << toString(patch->sinks[i].ext.device.type)
257 << ", " << patch->sinks[i].ext.device.address << ")";
258 }
259 return ss.str();
260}
261
262static std::string patchSourcesToString(const struct audio_patch *patch)
263{
264 std::stringstream ss;
265 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700266 if (i > 0) {
267 ss << "|";
268 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800269 ss << "(" << toString(patch->sources[i].ext.device.type)
270 << ", " << patch->sources[i].ext.device.address << ")";
271 }
272 return ss.str();
273}
274
Andy Hung4bd53e72022-11-17 17:21:45 -0800275static std::string toString(audio_latency_mode_t mode) {
276 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganova77d5552022-12-18 02:48:14 +0000277 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
278 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800279}
280
281// Could be made a template, but other toString overloads for std::vector are confused.
282static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
283 std::string s("{ ");
284 for (const auto& e : elements) {
285 s.append(toString(e));
286 s.append(" ");
287 }
288 s.append("}");
289 return s;
290}
291
Glenn Kasten03490092014-05-27 12:30:54 -0700292static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
293
294static void sFastTrackMultiplierInit()
295{
296 char value[PROPERTY_VALUE_MAX];
297 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
298 char *endptr;
299 unsigned long ul = strtoul(value, &endptr, 0);
300 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
301 sFastTrackMultiplier = (int) ul;
302 }
303 }
304}
305
306// ----------------------------------------------------------------------------
307
Eric Laurent81784c32012-11-19 14:55:58 -0800308#ifdef ADD_BATTERY_DATA
309// To collect the amplifier usage
310static void addBatteryData(uint32_t params) {
311 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
312 if (service == NULL) {
313 // it already logged
314 return;
315 }
316
317 service->addBatteryData(params);
318}
319#endif
320
Andy Hung3f0c9022016-01-15 17:49:46 -0800321// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
322struct {
323 // call when you acquire a partial wakelock
324 void acquire(const sp<IBinder> &wakeLockToken) {
325 pthread_mutex_lock(&mLock);
326 if (wakeLockToken.get() == nullptr) {
327 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
328 } else {
329 if (mCount == 0) {
330 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
331 }
332 ++mCount;
333 }
334 pthread_mutex_unlock(&mLock);
335 }
336
337 // call when you release a partial wakelock.
338 void release(const sp<IBinder> &wakeLockToken) {
339 if (wakeLockToken.get() == nullptr) {
340 return;
341 }
342 pthread_mutex_lock(&mLock);
343 if (--mCount < 0) {
344 ALOGE("negative wakelock count");
345 mCount = 0;
346 }
347 pthread_mutex_unlock(&mLock);
348 }
349
350 // retrieves the boottime timebase offset from monotonic.
351 int64_t getBoottimeOffset() {
352 pthread_mutex_lock(&mLock);
353 int64_t boottimeOffset = mBoottimeOffset;
354 pthread_mutex_unlock(&mLock);
355 return boottimeOffset;
356 }
357
358 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
359 // and the selected timebase.
360 // Currently only TIMEBASE_BOOTTIME is allowed.
361 //
362 // This only needs to be called upon acquiring the first partial wakelock
363 // after all other partial wakelocks are released.
364 //
365 // We do an empirical measurement of the offset rather than parsing
366 // /proc/timer_list since the latter is not a formal kernel ABI.
367 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
368 int clockbase;
369 switch (timebase) {
370 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
371 clockbase = SYSTEM_TIME_BOOTTIME;
372 break;
373 default:
374 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
375 break;
376 }
377 // try three times to get the clock offset, choose the one
378 // with the minimum gap in measurements.
379 const int tries = 3;
Andy Hung71ba4b32022-10-06 12:09:49 -0700380 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800381 for (int i = 0; i < tries; ++i) {
382 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
383 const nsecs_t tbase = systemTime(clockbase);
384 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
385 const nsecs_t gap = tmono2 - tmono;
386 if (i == 0 || gap < bestGap) {
387 bestGap = gap;
388 measured = tbase - ((tmono + tmono2) >> 1);
389 }
390 }
391
392 // to avoid micro-adjusting, we don't change the timebase
393 // unless it is significantly different.
394 //
395 // Assumption: It probably takes more than toleranceNs to
396 // suspend and resume the device.
397 static int64_t toleranceNs = 10000; // 10 us
398 if (llabs(*offset - measured) > toleranceNs) {
399 ALOGV("Adjusting timebase offset old: %lld new: %lld",
400 (long long)*offset, (long long)measured);
401 *offset = measured;
402 }
403 }
404
405 pthread_mutex_t mLock;
406 int32_t mCount;
407 int64_t mBoottimeOffset;
408} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800409
410// ----------------------------------------------------------------------------
411// CPU Stats
412// ----------------------------------------------------------------------------
413
414class CpuStats {
415public:
416 CpuStats();
417 void sample(const String8 &title);
418#ifdef DEBUG_CPU_USAGE
419private:
420 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700421 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800422
Andy Hung16698b82018-08-01 10:48:38 -0700423 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800424
425 int mCpuNum; // thread's current CPU number
426 int mCpukHz; // frequency of thread's current CPU in kHz
427#endif
428};
429
430CpuStats::CpuStats()
431#ifdef DEBUG_CPU_USAGE
432 : mCpuNum(-1), mCpukHz(-1)
433#endif
434{
435}
436
Glenn Kasten0f11b512014-01-31 16:18:54 -0800437void CpuStats::sample(const String8 &title
438#ifndef DEBUG_CPU_USAGE
439 __unused
440#endif
441 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800442#ifdef DEBUG_CPU_USAGE
443 // get current thread's delta CPU time in wall clock ns
444 double wcNs;
445 bool valid = mCpuUsage.sampleAndEnable(wcNs);
446
447 // record sample for wall clock statistics
448 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700449 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800450 }
451
452 // get the current CPU number
453 int cpuNum = sched_getcpu();
454
455 // get the current CPU frequency in kHz
456 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
457
458 // check if either CPU number or frequency changed
459 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
460 mCpuNum = cpuNum;
461 mCpukHz = cpukHz;
462 // ignore sample for purposes of cycles
463 valid = false;
464 }
465
466 // if no change in CPU number or frequency, then record sample for cycle statistics
467 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700468 const double cycles = wcNs * cpukHz * 0.000001;
469 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800470 }
471
Eric Tan5b13ff82018-07-27 11:20:17 -0700472 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800473 // mCpuUsage.elapsed() is expensive, so don't call it every loop
474 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700475 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800476 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700477 const double perLoop = elapsed / (double) n;
478 const double perLoop100 = perLoop * 0.01;
479 const double perLoop1k = perLoop * 0.001;
480 const double mean = mWcStats.getMean();
481 const double stddev = mWcStats.getStdDev();
482 const double minimum = mWcStats.getMin();
483 const double maximum = mWcStats.getMax();
484 const double meanCycles = mHzStats.getMean();
485 const double stddevCycles = mHzStats.getStdDev();
486 const double minCycles = mHzStats.getMin();
487 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800488 mCpuUsage.resetElapsed();
489 mWcStats.reset();
490 mHzStats.reset();
491 ALOGD("CPU usage for %s over past %.1f secs\n"
492 " (%u mixer loops at %.1f mean ms per loop):\n"
493 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
494 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
495 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000496 title.c_str(),
Eric Laurent81784c32012-11-19 14:55:58 -0800497 elapsed * .000000001, n, perLoop * .000001,
498 mean * .001,
499 stddev * .001,
500 minimum * .001,
501 maximum * .001,
502 mean / perLoop100,
503 stddev / perLoop100,
504 minimum / perLoop100,
505 maximum / perLoop100,
506 meanCycles / perLoop1k,
507 stddevCycles / perLoop1k,
508 minCycles / perLoop1k,
509 maxCycles / perLoop1k);
510
511 }
512 }
513#endif
514};
515
516// ----------------------------------------------------------------------------
517// ThreadBase
518// ----------------------------------------------------------------------------
519
Glenn Kasten97b7b752014-09-28 13:04:24 -0700520// static
Andy Hung71742ab2023-07-07 13:47:37 -0700521const char* ThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700522{
523 switch (type) {
524 case MIXER:
525 return "MIXER";
526 case DIRECT:
527 return "DIRECT";
528 case DUPLICATING:
529 return "DUPLICATING";
530 case RECORD:
531 return "RECORD";
532 case OFFLOAD:
533 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700534 case MMAP_PLAYBACK:
535 return "MMAP_PLAYBACK";
536 case MMAP_CAPTURE:
537 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200538 case SPATIALIZER:
539 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000540 case BIT_PERFECT:
541 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700542 default:
543 return "unknown";
544 }
545}
546
Andy Hung2cbc2722023-07-17 17:05:00 -0700547ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700548 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800549 : Thread(false /*canCallJava*/),
550 mType(type),
Andy Hung2cbc2722023-07-17 17:05:00 -0700551 mAfThreadCallback(afThreadCallback),
Andy Hungcf10d742020-04-28 15:38:24 -0700552 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
553 isOut),
554 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700555 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800556 // are set by PlaybackThread::readOutputParameters_l() or
557 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700558 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700559 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700560 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800561 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700562 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800563 mSystemReady(systemReady),
564 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800565{
Andy Hungcf10d742020-04-28 15:38:24 -0700566 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700567 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800568}
569
Andy Hung71742ab2023-07-07 13:47:37 -0700570ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800571{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700572 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700573 mConfigEvents.clear();
574
Eric Laurent81784c32012-11-19 14:55:58 -0800575 // do not lock the mutex in destructor
576 releaseWakeLock_l();
577 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800578 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800579 binder->unlinkToDeath(mDeathRecipient);
580 }
Andy Hungd0979812019-02-21 15:51:44 -0800581
582 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800583}
584
Andy Hung71742ab2023-07-07 13:47:37 -0700585status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700586{
587 status_t status = initCheck();
588 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800589 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700590 } else {
591 ALOGE("No working audio driver found.");
592 }
593 return status;
594}
595
Andy Hung71742ab2023-07-07 13:47:37 -0700596void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800597{
598 ALOGV("ThreadBase::exit");
599 // do any cleanup required for exit to succeed
600 preExit();
601 {
602 // This lock prevents the following race in thread (uniprocessor for illustration):
603 // if (!exitPending()) {
604 // // context switch from here to exit()
605 // // exit() calls requestExit(), what exitPending() observes
606 // // exit() calls signal(), which is dropped since no waiters
607 // // context switch back from exit() to here
608 // mWaitWorkCV.wait(...);
609 // // now thread is hung
610 // }
611 AutoMutex lock(mLock);
612 requestExit();
613 mWaitWorkCV.broadcast();
614 }
615 // When Thread::requestExitAndWait is made virtual and this method is renamed to
616 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
617 requestExitAndWait();
618}
619
Andy Hung71742ab2023-07-07 13:47:37 -0700620status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800621{
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000622 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800623 Mutex::Autolock _l(mLock);
624
Eric Laurent10351942014-05-08 18:49:52 -0700625 return sendSetParameterConfigEvent_l(keyValuePairs);
626}
627
628// sendConfigEvent_l() must be called with ThreadBase::mLock held
629// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hung71742ab2023-07-07 13:47:37 -0700630status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung71ba4b32022-10-06 12:09:49 -0700631NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700632{
633 status_t status = NO_ERROR;
634
Eric Laurent72e3f392015-05-20 14:43:50 -0700635 if (event->mRequiresSystemReady && !mSystemReady) {
636 event->mWaitStatus = false;
637 mPendingConfigEvents.add(event);
638 return status;
639 }
Eric Laurent10351942014-05-08 18:49:52 -0700640 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700641 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800642 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700643 mLock.unlock();
644 {
645 Mutex::Autolock _l(event->mLock);
646 while (event->mWaitStatus) {
647 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
648 event->mStatus = TIMED_OUT;
649 event->mWaitStatus = false;
650 }
651 }
652 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800653 }
Eric Laurent10351942014-05-08 18:49:52 -0700654 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800655 return status;
656}
657
Andy Hung71742ab2023-07-07 13:47:37 -0700658void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700659 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800660{
661 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700662 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800663}
664
665// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -0700666void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700667 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800668{
Andy Hungd0979812019-02-21 15:51:44 -0800669 // The audio statistics history is exponentially weighted to forget events
670 // about five or more seconds in the past. In order to have
671 // crisper statistics for mediametrics, we reset the statistics on
672 // an IoConfigEvent, to reflect different properties for a new device.
673 mIoJitterMs.reset();
674 mLatencyMs.reset();
675 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000676 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100677 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800678
Eric Laurent09f1ed22019-04-24 17:45:17 -0700679 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700680 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800681}
682
Andy Hung71742ab2023-07-07 13:47:37 -0700683void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700684{
685 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800686 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700687}
688
Eric Laurent81784c32012-11-19 14:55:58 -0800689// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -0700690void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800691 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800692{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800693 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700694 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800695}
696
Eric Laurent10351942014-05-08 18:49:52 -0700697// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -0700698status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800699{
Andy Hung2ddee192015-12-18 17:34:44 -0800700 sp<ConfigEvent> configEvent;
701 AudioParameter param(keyValuePair);
702 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700703 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800704 setMasterMono_l(value != 0);
705 if (param.size() == 1) {
706 return NO_ERROR; // should be a solo parameter - we don't pass down
707 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700708 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800709 configEvent = new SetParameterConfigEvent(param.toString());
710 } else {
711 configEvent = new SetParameterConfigEvent(keyValuePair);
712 }
Eric Laurent10351942014-05-08 18:49:52 -0700713 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700714}
715
Andy Hung71742ab2023-07-07 13:47:37 -0700716status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700717 const struct audio_patch *patch,
718 audio_patch_handle_t *handle)
719{
720 Mutex::Autolock _l(mLock);
721 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
722 status_t status = sendConfigEvent_l(configEvent);
723 if (status == NO_ERROR) {
724 CreateAudioPatchConfigEventData *data =
725 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
726 *handle = data->mHandle;
727 }
728 return status;
729}
730
Andy Hung71742ab2023-07-07 13:47:37 -0700731status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700732 const audio_patch_handle_t handle)
733{
734 Mutex::Autolock _l(mLock);
735 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
736 return sendConfigEvent_l(configEvent);
737}
738
Andy Hung71742ab2023-07-07 13:47:37 -0700739status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700740 const DeviceDescriptorBaseVector& outDevices)
741{
742 if (type() != RECORD) {
743 // The update out device operation is only for record thread.
744 return INVALID_OPERATION;
745 }
746 Mutex::Autolock _l(mLock);
747 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
748 return sendConfigEvent_l(configEvent);
749}
750
Andy Hung71742ab2023-07-07 13:47:37 -0700751void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200752{
753 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
754 sp<ConfigEvent> configEvent =
755 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
756 sendConfigEvent_l(configEvent);
757}
Eric Laurent1c333e22014-05-20 10:48:17 -0700758
Andy Hung71742ab2023-07-07 13:47:37 -0700759void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200760{
761 Mutex::Autolock _l(mLock);
762 sendCheckOutputStageEffectsEvent_l();
763}
764
Andy Hung71742ab2023-07-07 13:47:37 -0700765void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200766{
767 sp<ConfigEvent> configEvent =
768 (ConfigEvent *)new CheckOutputStageEffectsEvent();
769 sendConfigEvent_l(configEvent);
770}
771
Andy Hung71742ab2023-07-07 13:47:37 -0700772void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent6f9534f2022-05-03 18:15:04 +0200773{
774 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
775 sendConfigEvent_l(configEvent);
776}
777
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700778// post condition: mConfigEvents.isEmpty()
Andy Hung71742ab2023-07-07 13:47:37 -0700779void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700780{
Eric Laurent10351942014-05-08 18:49:52 -0700781 bool configChanged = false;
782
Eric Laurent81784c32012-11-19 14:55:58 -0800783 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700784 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700785 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800786 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700787 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700788 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700789 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
790 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800791 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700792 true /*asynchronous*/);
793 if (err != 0) {
794 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700795 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700796 }
797 } break;
798 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700799 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700800 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700801 } break;
802 case CFG_EVENT_SET_PARAMETER: {
803 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
804 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
805 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700806 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000807 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700808 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700809 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700810 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700811 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700812 CreateAudioPatchConfigEventData *data =
813 (CreateAudioPatchConfigEventData *)event->mData.get();
814 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700815 const DeviceTypeSet newDevices = getDeviceTypes();
Eric Laurent52568142022-10-28 11:23:28 +0200816 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700817 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
818 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
819 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700820 } break;
821 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700822 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700823 ReleaseAudioPatchConfigEventData *data =
824 (ReleaseAudioPatchConfigEventData *)event->mData.get();
825 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700826 const DeviceTypeSet newDevices = getDeviceTypes();
Eric Laurent52568142022-10-28 11:23:28 +0200827 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700828 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
829 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
830 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
831 } break;
832 case CFG_EVENT_UPDATE_OUT_DEVICE: {
833 UpdateOutDevicesConfigEventData *data =
834 (UpdateOutDevicesConfigEventData *)event->mData.get();
835 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700836 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200837 case CFG_EVENT_RESIZE_BUFFER: {
838 ResizeBufferConfigEventData *data =
839 (ResizeBufferConfigEventData *)event->mData.get();
840 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
841 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200842
843 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
844 setCheckOutputStageEffects();
845 } break;
846
Eric Laurent6f9534f2022-05-03 18:15:04 +0200847 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
848 onHalLatencyModesChanged_l();
849 } break;
850
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700851 default:
Eric Laurent10351942014-05-08 18:49:52 -0700852 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700853 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800854 }
Eric Laurent10351942014-05-08 18:49:52 -0700855 {
856 Mutex::Autolock _l(event->mLock);
857 if (event->mWaitStatus) {
858 event->mWaitStatus = false;
859 event->mCond.signal();
860 }
861 }
862 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
863 }
864
865 if (configChanged) {
866 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800867 }
Eric Laurent81784c32012-11-19 14:55:58 -0800868}
869
Marco Nelissenb2208842014-02-07 14:00:50 -0800870String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
871 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700872 const audio_channel_representation_t representation =
873 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700874
875 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800876 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700877 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
878 if (output) {
879 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
880 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
881 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700882 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700883 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
884 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
885 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
886 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
887 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
888 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
889 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
890 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
891 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
892 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
893 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
894 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700895 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
896 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
897 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
898 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
899 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
900 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
901 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700902 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700903 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
904 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700905 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
906 } else {
907 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
908 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
909 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
910 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
911 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
912 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
913 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
914 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
915 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
916 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
917 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
918 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700919 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
920 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
921 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700922 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700923 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
924 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700925 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
926 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
927 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
928 }
929 const int len = s.length();
930 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700931 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700932 s.unlockBuffer(len - 2); // remove trailing ", "
933 }
934 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800935 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700936 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
937 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
938 return s;
939 default:
940 s.appendFormat("unknown mask, representation:%d bits:%#x",
941 representation, audio_channel_mask_get_bits(mask));
942 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800943 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800944}
945
Andy Hung71742ab2023-07-07 13:47:37 -0700946void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung71ba4b32022-10-06 12:09:49 -0700947NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -0800948{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800949 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
950 this, mThreadName, getTid(), type(), threadTypeToString(type()));
951
Eric Laurent81784c32012-11-19 14:55:58 -0800952 bool locked = AudioFlinger::dumpTryLock(mLock);
953 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800954 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800955 }
956
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700957 dumpBase_l(fd, args);
958 dumpInternals_l(fd, args);
959 dumpTracks_l(fd, args);
960 dumpEffectChains_l(fd, args);
961
962 if (locked) {
963 mLock.unlock();
964 }
965
966 dprintf(fd, " Local log:\n");
967 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -0700968
969 // --all does the statistics
970 bool dumpAll = false;
971 for (const auto &arg : args) {
972 if (arg == String16("--all")) {
973 dumpAll = true;
974 }
975 }
976 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -0700977 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -0700978 if (!sched.empty()) {
979 (void)write(fd, sched.c_str(), sched.size());
980 }
981 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700982}
983
Andy Hung71742ab2023-07-07 13:47:37 -0700984void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700985{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700986 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700987 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700988 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700989 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700990 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700991 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700992 dprintf(fd, " Channel count: %u\n", mChannelCount);
993 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000994 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700995 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700996 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700997 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800998 size_t numConfig = mConfigEvents.size();
999 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001000 const size_t SIZE = 256;
1001 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001002 for (size_t i = 0; i < numConfig; i++) {
1003 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001004 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001005 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001006 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001007 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001008 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001009 }
Andy Hung293558a2017-03-21 12:19:20 -07001010 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001011 dprintf(fd, " Output devices: %s (%s)\n",
1012 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
1013 dprintf(fd, " Input device: %#x (%s)\n",
1014 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001015 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001016
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001017 // Dump timestamp statistics for the Thread types that support it.
1018 if (mType == RECORD
1019 || mType == MIXER
1020 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001021 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001022 || mType == OFFLOAD
1023 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001024 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -07001025 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001026 }
1027
Andy Hung446f4df2019-02-21 12:26:41 -08001028 if (mLastIoBeginNs > 0) { // MMAP may not set this
1029 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1030 isOutput() ? "write" : "read",
1031 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1032 }
1033
1034 if (mProcessTimeMs.getN() > 0) {
1035 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1036 }
1037
1038 if (mIoJitterMs.getN() > 0) {
1039 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1040 isOutput() ? "write" : "read",
1041 mIoJitterMs.toString().c_str());
1042 }
1043
Andy Hunge6c37112019-02-26 17:38:10 -08001044 if (mLatencyMs.getN() > 0) {
1045 dprintf(fd, " Threadloop %s latency stats: %s\n",
1046 isOutput() ? "write" : "read",
1047 mLatencyMs.toString().c_str());
1048 }
Robert Wu06db0a32021-08-10 19:05:34 +00001049
1050 if (mMonopipePipeDepthStats.getN() > 0) {
1051 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1052 isOutput() ? "write" : "read",
1053 mMonopipePipeDepthStats.toString().c_str());
1054 }
Eric Laurent81784c32012-11-19 14:55:58 -08001055}
1056
Andy Hung71742ab2023-07-07 13:47:37 -07001057void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001058{
1059 const size_t SIZE = 256;
1060 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001061
Marco Nelissenb2208842014-02-07 14:00:50 -08001062 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001063 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001064 write(fd, buffer, strlen(buffer));
1065
Marco Nelissenb2208842014-02-07 14:00:50 -08001066 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hungbd72c542023-06-20 18:56:17 -07001067 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001068 if (chain != 0) {
1069 chain->dump(fd, args);
1070 }
1071 }
1072}
1073
Andy Hung71742ab2023-07-07 13:47:37 -07001074void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001075{
1076 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07001077 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001078}
1079
Andy Hung71742ab2023-07-07 13:47:37 -07001080String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001081{
1082 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001083 case MIXER:
1084 return String16("AudioMix");
1085 case DIRECT:
1086 return String16("AudioDirectOut");
1087 case DUPLICATING:
1088 return String16("AudioDup");
1089 case RECORD:
1090 return String16("AudioIn");
1091 case OFFLOAD:
1092 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001093 case MMAP_PLAYBACK:
1094 return String16("MmapPlayback");
1095 case MMAP_CAPTURE:
1096 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001097 case SPATIALIZER:
1098 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001099 default:
1100 ALOG_ASSERT(false);
1101 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001102 }
1103}
1104
Andy Hung71742ab2023-07-07 13:47:37 -07001105void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001106{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001107 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001108 if (mPowerManager != 0) {
1109 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001110 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001111 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1112 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001113 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001114 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001115 {} /* workSource */,
1116 {} /* historyTag */);
1117 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001118 mWakeLockToken = binder;
1119 }
Chris Ye6597d732020-02-28 22:38:25 -08001120 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001121 }
Wei Jia3f273d12015-11-24 09:06:49 -08001122
Andy Hung3f0c9022016-01-15 17:49:46 -08001123 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001124 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1125 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001126}
1127
Andy Hung71742ab2023-07-07 13:47:37 -07001128void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001129{
1130 Mutex::Autolock _l(mLock);
1131 releaseWakeLock_l();
1132}
1133
Andy Hung71742ab2023-07-07 13:47:37 -07001134void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001135{
Andy Hung3f0c9022016-01-15 17:49:46 -08001136 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001137 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001138 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001139 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001140 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001141 }
1142 mWakeLockToken.clear();
1143 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001144}
1145
Andy Hung71742ab2023-07-07 13:47:37 -07001146void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001147 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001148 // use checkService() to avoid blocking if power service is not up yet
1149 sp<IBinder> binder =
1150 defaultServiceManager()->checkService(String16("power"));
1151 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001152 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001153 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001154 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001155 binder->linkToDeath(mDeathRecipient);
1156 }
1157 }
1158}
1159
Andy Hung71742ab2023-07-07 13:47:37 -07001160void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001161 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001162
1163#if !LOG_NDEBUG
1164 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001165 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001166 s << uid << " ";
1167 }
1168 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1169#endif
1170
Andy Hung438e7572015-12-14 15:51:17 -08001171 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1172 if (mSystemReady) {
1173 ALOGE("no wake lock to update, but system ready!");
1174 } else {
1175 ALOGW("no wake lock to update, system not ready yet");
1176 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001177 return;
1178 }
1179 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001180 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001181 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1182 mWakeLockToken, uidsAsInt);
1183 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001184 }
1185}
1186
Andy Hung71742ab2023-07-07 13:47:37 -07001187void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001188{
1189 Mutex::Autolock _l(mLock);
1190 releaseWakeLock_l();
1191 mPowerManager.clear();
1192}
1193
Andy Hung71742ab2023-07-07 13:47:37 -07001194void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001195 const DeviceDescriptorBaseVector& outDevices __unused)
1196{
1197 ALOGE("%s should only be called in RecordThread", __func__);
1198}
1199
Andy Hung71742ab2023-07-07 13:47:37 -07001200void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001201{
1202 ALOGE("%s should only be called in RecordThread", __func__);
1203}
1204
Andy Hung71742ab2023-07-07 13:47:37 -07001205void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001206{
1207 sp<ThreadBase> thread = mThread.promote();
1208 if (thread != 0) {
1209 thread->clearPowerManager();
1210 }
1211 ALOGW("power manager service died !!!");
1212}
1213
Andy Hung71742ab2023-07-07 13:47:37 -07001214void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001215 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001216{
Andy Hungbd72c542023-06-20 18:56:17 -07001217 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001218 if (chain != 0) {
1219 if (type != NULL) {
1220 chain->setEffectSuspended_l(type, suspend);
1221 } else {
1222 chain->setEffectSuspendedAll_l(suspend);
1223 }
1224 }
1225
1226 updateSuspendedSessions_l(type, suspend, sessionId);
1227}
1228
Andy Hung71742ab2023-07-07 13:47:37 -07001229void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001230{
1231 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1232 if (index < 0) {
1233 return;
1234 }
1235
1236 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1237 mSuspendedSessions.valueAt(index);
1238
1239 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001240 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001241 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hungbd72c542023-06-20 18:56:17 -07001242 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001243 chain->setEffectSuspendedAll_l(true);
1244 } else {
1245 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1246 desc->mType.timeLow);
1247 chain->setEffectSuspended_l(&desc->mType, true);
1248 }
1249 }
1250 }
1251}
1252
Andy Hung71742ab2023-07-07 13:47:37 -07001253void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001254 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001255 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001256{
1257 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1258
1259 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1260
1261 if (suspend) {
1262 if (index >= 0) {
1263 sessionEffects = mSuspendedSessions.valueAt(index);
1264 } else {
1265 mSuspendedSessions.add(sessionId, sessionEffects);
1266 }
1267 } else {
1268 if (index < 0) {
1269 return;
1270 }
1271 sessionEffects = mSuspendedSessions.valueAt(index);
1272 }
1273
1274
Andy Hungbd72c542023-06-20 18:56:17 -07001275 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001276 if (type != NULL) {
1277 key = type->timeLow;
1278 }
1279 index = sessionEffects.indexOfKey(key);
1280
1281 sp<SuspendedSessionDesc> desc;
1282 if (suspend) {
1283 if (index >= 0) {
1284 desc = sessionEffects.valueAt(index);
1285 } else {
1286 desc = new SuspendedSessionDesc();
1287 if (type != NULL) {
1288 desc->mType = *type;
1289 }
1290 sessionEffects.add(key, desc);
1291 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1292 }
1293 desc->mRefCount++;
1294 } else {
1295 if (index < 0) {
1296 return;
1297 }
1298 desc = sessionEffects.valueAt(index);
1299 if (--desc->mRefCount == 0) {
1300 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1301 sessionEffects.removeItemsAt(index);
1302 if (sessionEffects.isEmpty()) {
1303 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1304 sessionId);
1305 mSuspendedSessions.removeItem(sessionId);
1306 }
1307 }
1308 }
1309 if (!sessionEffects.isEmpty()) {
1310 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1311 }
1312}
1313
Andy Hung71742ab2023-07-07 13:47:37 -07001314void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001315 audio_session_t sessionId,
Andy Hung71ba4b32022-10-06 12:09:49 -07001316 bool threadLocked)
1317NO_THREAD_SAFETY_ANALYSIS // manual locking
1318{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001319 if (!threadLocked) {
1320 mLock.lock();
1321 }
Eric Laurent81784c32012-11-19 14:55:58 -08001322
Eric Laurent81784c32012-11-19 14:55:58 -08001323 if (mType != RECORD) {
1324 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1325 // another session. This gives the priority to well behaved effect control panels
1326 // and applications not using global effects.
1327 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1328 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001329 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001330 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1331 }
1332 }
1333
Eric Laurent6b446ce2019-12-13 10:56:31 -08001334 if (!threadLocked) {
1335 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001336 }
1337}
1338
Eric Laurent4c415062016-06-17 16:14:16 -07001339// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07001340status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001341 const effect_descriptor_t *desc, audio_session_t sessionId)
1342{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001343 // No global output effect sessions on record threads
1344 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1345 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001346 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1347 desc->name, mThreadName);
1348 return BAD_VALUE;
1349 }
1350 // only pre processing effects on record thread
1351 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1352 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1353 desc->name, mThreadName);
1354 return BAD_VALUE;
1355 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001356
1357 // always allow effects without processing load or latency
1358 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1359 return NO_ERROR;
1360 }
1361
Eric Laurent4c415062016-06-17 16:14:16 -07001362 audio_input_flags_t flags = mInput->flags;
1363 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1364 if (flags & AUDIO_INPUT_FLAG_RAW) {
1365 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1366 desc->name, mThreadName);
1367 return BAD_VALUE;
1368 }
1369 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1370 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1371 desc->name, mThreadName);
1372 return BAD_VALUE;
1373 }
1374 }
jiabineb3bda02020-06-30 14:07:03 -07001375
Andy Hungbd72c542023-06-20 18:56:17 -07001376 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001377 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1378 return BAD_VALUE;
1379 }
Eric Laurent4c415062016-06-17 16:14:16 -07001380 return NO_ERROR;
1381}
1382
1383// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07001384status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001385 const effect_descriptor_t *desc, audio_session_t sessionId)
1386{
1387 // no preprocessing on playback threads
1388 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001389 ALOGW("%s: pre processing effect %s created on playback"
1390 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001391 return BAD_VALUE;
1392 }
1393
Eric Laurent3e4de772017-07-16 16:55:08 -07001394 // always allow effects without processing load or latency
1395 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1396 return NO_ERROR;
1397 }
1398
Andy Hungbd72c542023-06-20 18:56:17 -07001399 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
jiabineb3bda02020-06-30 14:07:03 -07001400 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1401 __func__);
1402 return BAD_VALUE;
1403 }
1404
Eric Laurentf690c462021-09-17 14:47:03 +02001405 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1406 && mType != SPATIALIZER) {
1407 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1408 __func__, mType);
1409 return BAD_VALUE;
1410 }
1411
Eric Laurent4c415062016-06-17 16:14:16 -07001412 switch (mType) {
1413 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001414 audio_output_flags_t flags = mOutput->flags;
1415 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1416 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1417 // global effects are applied only to non fast tracks if they are SW
1418 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1419 break;
1420 }
1421 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1422 // only post processing on output stage session
1423 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001424 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1425 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001426 return BAD_VALUE;
1427 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001428 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1429 // only post processing on output stage session
1430 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001431 ALOGW("%s: non post processing effect %s not allowed on device session",
1432 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001433 return BAD_VALUE;
1434 }
Eric Laurent4c415062016-06-17 16:14:16 -07001435 } else {
1436 // no restriction on effects applied on non fast tracks
1437 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1438 break;
1439 }
1440 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001441
Eric Laurent4c415062016-06-17 16:14:16 -07001442 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001443 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001444 return BAD_VALUE;
1445 }
1446 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001447 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1448 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001449 return BAD_VALUE;
1450 }
1451 }
1452 } break;
1453 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001454 // nothing actionable on offload threads, if the effect:
1455 // - is offloadable: the effect can be created
1456 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1457 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001458 break;
1459 case DIRECT:
1460 // Reject any effect on Direct output threads for now, since the format of
1461 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001462 ALOGW("%s: effect %s on DIRECT output thread %s",
1463 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001464 return BAD_VALUE;
1465 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001466 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001467 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1468 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001469 return BAD_VALUE;
1470 }
1471 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001472 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1473 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001474 return BAD_VALUE;
1475 }
1476 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001477 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1478 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001479 return BAD_VALUE;
1480 }
1481 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001482 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001483 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1484 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1485 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1486 // are supported and added after the spatializer.
1487 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1488 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1489 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001490 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001491 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1492 // only post processing , downmixer or spatializer effects on output stage session
1493 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1494 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1495 break;
1496 }
1497 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1498 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1499 __func__, desc->name);
1500 return BAD_VALUE;
1501 }
1502 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1503 // only post processing on output stage session
1504 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1505 ALOGW("%s: non post processing effect %s not allowed on device session",
1506 __func__, desc->name);
1507 return BAD_VALUE;
1508 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001509 }
1510 break;
jiabinc658e452022-10-21 20:52:21 +00001511 case BIT_PERFECT:
1512 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1513 // Allow HW accelerated effects of tunnel type
1514 break;
1515 }
1516 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1517 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1518 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1519 // 3) there is any bit-perfect track with the given session id.
1520 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1521 sessionId == AUDIO_SESSION_DEVICE) {
1522 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1523 __func__, desc->name, mThreadName);
1524 return BAD_VALUE;
1525 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1526 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1527 __func__, desc->name, sessionId);
1528 return BAD_VALUE;
1529 }
1530 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001531 default:
1532 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1533 }
1534
1535 return NO_ERROR;
1536}
1537
Eric Laurent81784c32012-11-19 14:55:58 -08001538// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07001539sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hungd65869f2023-06-27 17:05:02 -07001540 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001541 const sp<IEffectClient>& effectClient,
1542 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001543 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001544 effect_descriptor_t *desc,
1545 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001546 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001547 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001548 bool probe,
1549 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001550{
Andy Hungbd72c542023-06-20 18:56:17 -07001551 sp<IAfEffectModule> effect;
1552 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001553 status_t lStatus;
Andy Hungbd72c542023-06-20 18:56:17 -07001554 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001555 bool chainCreated = false;
1556 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001557 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001558
1559 lStatus = initCheck();
1560 if (lStatus != NO_ERROR) {
1561 ALOGW("createEffect_l() Audio driver not initialized.");
1562 goto Exit;
1563 }
1564
Eric Laurent81784c32012-11-19 14:55:58 -08001565 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1566
1567 { // scope for mLock
1568 Mutex::Autolock _l(mLock);
1569
Eric Laurent4c415062016-06-17 16:14:16 -07001570 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001571 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001572 goto Exit;
1573 }
1574
Eric Laurent81784c32012-11-19 14:55:58 -08001575 // check for existing effect chain with the requested audio session
1576 chain = getEffectChain_l(sessionId);
1577 if (chain == 0) {
1578 // create a new chain for this session
1579 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Andy Hungbd72c542023-06-20 18:56:17 -07001580 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001581 addEffectChain_l(chain);
1582 chain->setStrategy(getStrategyForSession_l(sessionId));
1583 chainCreated = true;
1584 } else {
1585 effect = chain->getEffectFromDesc_l(desc);
1586 }
1587
1588 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1589
1590 if (effect == 0) {
Andy Hung2cbc2722023-07-17 17:05:00 -07001591 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001592 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001593 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001594 if (lStatus != NO_ERROR) {
1595 goto Exit;
1596 }
1597 effectCreated = true;
1598
jiabinc52b1ff2019-10-31 17:20:42 -07001599 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001600 effect->setDevices(outDeviceTypeAddrs());
1601 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung2cbc2722023-07-17 17:05:00 -07001602 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001603 effect->setAudioSource(mAudioSource);
1604 }
jiabin1319f5a2021-03-30 22:21:24 +00001605 if (effect->isHapticGenerator()) {
1606 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1607 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001608 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung2cbc2722023-07-17 17:05:00 -07001609 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001610 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001611 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001612 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001613 }
1614 }
Eric Laurent81784c32012-11-19 14:55:58 -08001615 // create effect handle and connect it to effect module
Andy Hungbd72c542023-06-20 18:56:17 -07001616 handle = IAfEffectHandle::create(
1617 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001618 lStatus = handle->initCheck();
1619 if (lStatus == OK) {
1620 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001621 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001622 }
Eric Laurent81784c32012-11-19 14:55:58 -08001623 if (enabled != NULL) {
1624 *enabled = (int)effect->isEnabled();
1625 }
1626 }
1627
1628Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001629 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001630 Mutex::Autolock _l(mLock);
1631 if (effectCreated) {
1632 chain->removeEffect_l(effect);
1633 }
Eric Laurent81784c32012-11-19 14:55:58 -08001634 if (chainCreated) {
1635 removeEffectChain_l(chain);
1636 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001637 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001638 }
1639
Glenn Kasten9156ef32013-08-06 15:39:08 -07001640 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001641 return handle;
1642}
1643
Andy Hung71742ab2023-07-07 13:47:37 -07001644void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001645 bool unpinIfLast)
1646{
1647 bool remove = false;
Andy Hungbd72c542023-06-20 18:56:17 -07001648 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001649 {
1650 Mutex::Autolock _l(mLock);
Andy Hungbd72c542023-06-20 18:56:17 -07001651 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001652 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001653 return;
1654 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001655 effect = effectBase->asEffectModule();
1656 if (effect == nullptr) {
1657 return;
1658 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001659 // restore suspended effects if the disconnected handle was enabled and the last one.
1660 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1661 if (remove) {
1662 removeEffect_l(effect, true);
1663 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001664 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001665 }
1666 if (remove) {
Andy Hung2cbc2722023-07-17 17:05:00 -07001667 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001668 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001669 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001670 }
1671 }
1672}
1673
Andy Hung71742ab2023-07-07 13:47:37 -07001674void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001675 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001676 Mutex::Autolock _l(mLock);
1677 broadcast_l();
1678 }
1679 if (!effect->isOffloadable()) {
1680 if (mType == ThreadBase::OFFLOAD) {
1681 PlaybackThread *t = (PlaybackThread *)this;
1682 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1683 }
1684 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung2cbc2722023-07-17 17:05:00 -07001685 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001686 }
1687 }
1688}
1689
Andy Hung71742ab2023-07-07 13:47:37 -07001690void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001691 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001692 Mutex::Autolock _l(mLock);
1693 broadcast_l();
1694 }
1695}
1696
Andy Hung71742ab2023-07-07 13:47:37 -07001697sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung4989d312023-06-29 21:19:25 -07001698 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001699{
1700 Mutex::Autolock _l(mLock);
1701 return getEffect_l(sessionId, effectId);
1702}
1703
Andy Hung71742ab2023-07-07 13:47:37 -07001704sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung4989d312023-06-29 21:19:25 -07001705 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001706{
Andy Hungbd72c542023-06-20 18:56:17 -07001707 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001708 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1709}
1710
Andy Hung71742ab2023-07-07 13:47:37 -07001711std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001712{
Andy Hungbd72c542023-06-20 18:56:17 -07001713 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent6c796322019-04-09 14:13:17 -07001714 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1715}
1716
Eric Laurent81784c32012-11-19 14:55:58 -08001717// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1718// PlaybackThread::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07001719status_t ThreadBase::addEffect_l(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001720{
1721 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001722 audio_session_t sessionId = effect->sessionId();
Andy Hungbd72c542023-06-20 18:56:17 -07001723 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001724 bool chainCreated = false;
1725
Eric Laurent5baf2af2013-09-12 17:37:00 -07001726 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001727 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001728 this, effect->desc().name, effect->desc().flags);
1729
Eric Laurent81784c32012-11-19 14:55:58 -08001730 if (chain == 0) {
1731 // create a new chain for this session
1732 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Andy Hungbd72c542023-06-20 18:56:17 -07001733 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001734 addEffectChain_l(chain);
1735 chain->setStrategy(getStrategyForSession_l(sessionId));
1736 chainCreated = true;
1737 }
1738 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1739
1740 if (chain->getEffectFromId_l(effect->id()) != 0) {
1741 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1742 this, effect->desc().name, chain.get());
1743 return BAD_VALUE;
1744 }
1745
Eric Laurent5baf2af2013-09-12 17:37:00 -07001746 effect->setOffloaded(mType == OFFLOAD, mId);
1747
Eric Laurent81784c32012-11-19 14:55:58 -08001748 status_t status = chain->addEffect_l(effect);
1749 if (status != NO_ERROR) {
1750 if (chainCreated) {
1751 removeEffectChain_l(chain);
1752 }
1753 return status;
1754 }
1755
jiabin8f278ee2019-11-11 12:16:27 -08001756 effect->setDevices(outDeviceTypeAddrs());
1757 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung2cbc2722023-07-17 17:05:00 -07001758 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001759 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001760
Eric Laurent81784c32012-11-19 14:55:58 -08001761 return NO_ERROR;
1762}
1763
Andy Hung71742ab2023-07-07 13:47:37 -07001764void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001765
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001766 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001767 effect_descriptor_t desc = effect->desc();
1768 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1769 detachAuxEffect_l(effect->id());
1770 }
1771
Andy Hungbd72c542023-06-20 18:56:17 -07001772 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001773 if (chain != 0) {
1774 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001775 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001776 removeEffectChain_l(chain);
1777 }
1778 } else {
1779 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1780 }
1781}
1782
Andy Hung71742ab2023-07-07 13:47:37 -07001783void ThreadBase::lockEffectChains_l(
Andy Hungbd72c542023-06-20 18:56:17 -07001784 Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung71ba4b32022-10-06 12:09:49 -07001785NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001786{
1787 effectChains = mEffectChains;
1788 for (size_t i = 0; i < mEffectChains.size(); i++) {
1789 mEffectChains[i]->lock();
1790 }
1791}
1792
Andy Hung71742ab2023-07-07 13:47:37 -07001793void ThreadBase::unlockEffectChains(
Andy Hungbd72c542023-06-20 18:56:17 -07001794 const Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung71ba4b32022-10-06 12:09:49 -07001795NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001796{
1797 for (size_t i = 0; i < effectChains.size(); i++) {
1798 effectChains[i]->unlock();
1799 }
1800}
1801
Andy Hung71742ab2023-07-07 13:47:37 -07001802sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001803{
1804 Mutex::Autolock _l(mLock);
1805 return getEffectChain_l(sessionId);
1806}
1807
Andy Hung71742ab2023-07-07 13:47:37 -07001808sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001809 const
Eric Laurent81784c32012-11-19 14:55:58 -08001810{
1811 size_t size = mEffectChains.size();
1812 for (size_t i = 0; i < size; i++) {
1813 if (mEffectChains[i]->sessionId() == sessionId) {
1814 return mEffectChains[i];
1815 }
1816 }
1817 return 0;
1818}
1819
Andy Hung71742ab2023-07-07 13:47:37 -07001820void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001821{
1822 Mutex::Autolock _l(mLock);
1823 size_t size = mEffectChains.size();
1824 for (size_t i = 0; i < size; i++) {
1825 mEffectChains[i]->setMode_l(mode);
1826 }
1827}
1828
Andy Hung71742ab2023-07-07 13:47:37 -07001829void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001830{
1831 config->type = AUDIO_PORT_TYPE_MIX;
1832 config->ext.mix.handle = mId;
1833 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001834 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001835 config->channel_mask = mChannelMask;
1836 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1837 AUDIO_PORT_CONFIG_FORMAT;
1838}
1839
Andy Hung71742ab2023-07-07 13:47:37 -07001840void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001841{
1842 Mutex::Autolock _l(mLock);
1843 if (mSystemReady) {
1844 return;
1845 }
1846 mSystemReady = true;
1847
1848 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1849 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1850 }
1851 mPendingConfigEvents.clear();
1852}
1853
Andy Hungdae27702016-10-31 14:01:16 -07001854template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001855ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001856 ssize_t index = mActiveTracks.indexOf(track);
1857 if (index >= 0) {
1858 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1859 return index;
1860 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001861 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001862 mActiveTracksGeneration++;
1863 mLatestActiveTrack = track;
1864 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001865 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001866 return mActiveTracks.add(track);
1867}
1868
1869template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001870ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001871 ssize_t index = mActiveTracks.remove(track);
1872 if (index < 0) {
1873 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1874 return index;
1875 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001876 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001877 mActiveTracksGeneration++;
1878 --mBatteryCounter[track->uid()].second;
1879 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001880 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001881#ifdef TEE_SINK
1882 track->dumpTee(-1 /* fd */, "_REMOVE");
1883#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001884 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001885 return index;
1886}
1887
1888template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001889void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001890 for (const sp<T> &track : mActiveTracks) {
1891 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001892 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001893 }
1894 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001895 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001896 mActiveTracks.clear();
1897 mLatestActiveTrack.clear();
1898 mBatteryCounter.clear();
1899}
1900
1901template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001902void ThreadBase::ActiveTracks<T>::updatePowerState(
Andy Hung71ba4b32022-10-06 12:09:49 -07001903 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001904 // Updates ActiveTracks client uids to the thread wakelock.
1905 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1906 thread->updateWakeLockUids_l(getWakeLockUids());
1907 mLastActiveTracksGeneration = mActiveTracksGeneration;
1908 }
1909
1910 // Updates BatteryNotifier uids
1911 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1912 const uid_t uid = it->first;
1913 ssize_t &previous = it->second.first;
1914 ssize_t &current = it->second.second;
1915 if (current > 0) {
1916 if (previous == 0) {
1917 BatteryNotifier::getInstance().noteStartAudio(uid);
1918 }
1919 previous = current;
1920 ++it;
1921 } else if (current == 0) {
1922 if (previous > 0) {
1923 BatteryNotifier::getInstance().noteStopAudio(uid);
1924 }
1925 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1926 } else /* (current < 0) */ {
1927 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1928 }
1929 }
1930}
Eric Laurent83b88082014-06-20 18:31:16 -07001931
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001932template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001933bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001934 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001935 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001936
1937 for (const sp<T> &track : mActiveTracks) {
1938 // Do not short-circuit as all hasChanged states must be reset
1939 // as all the metadata are going to be sent
1940 hasChanged |= track->readAndClearHasChanged();
1941 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001942 return hasChanged;
1943}
1944
1945template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001946void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001947 const char *funcName, const sp<T> &track) const {
1948 if (mLocalLog != nullptr) {
1949 String8 result;
1950 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00001951 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001952 }
1953}
1954
Andy Hung71742ab2023-07-07 13:47:37 -07001955void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08001956{
1957 // Thread could be blocked waiting for async
1958 // so signal it to handle state changes immediately
1959 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1960 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1961 mSignalPending = true;
1962 mWaitWorkCV.broadcast();
1963}
1964
Andy Hungd0979812019-02-21 15:51:44 -08001965// Call only from threadLoop() or when it is idle.
1966// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hung71742ab2023-07-07 13:47:37 -07001967void ThreadBase::sendStatistics(bool force)
Andy Hungd0979812019-02-21 15:51:44 -08001968{
1969 // Do not log if we have no stats.
1970 // We choose the timestamp verifier because it is the most likely item to be present.
1971 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1972 if (nstats == 0) {
1973 return;
1974 }
1975
1976 // Don't log more frequently than once per 12 hours.
1977 // We use BOOTTIME to include suspend time.
1978 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1979 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1980 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1981 return;
1982 }
1983
1984 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1985 mLastRecordedTimeNs = timeNs;
1986
Ray Essickf27e9872019-12-07 06:28:46 -08001987 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001988
1989#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1990
1991 // thread configuration
1992 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1993 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1994 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1995 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1996 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1997 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1998 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001999 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
2000 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002001
2002 // thread statistics
2003 if (mIoJitterMs.getN() > 0) {
2004 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2005 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2006 }
2007 if (mProcessTimeMs.getN() > 0) {
2008 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2009 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2010 }
2011 const auto tsjitter = mTimestampVerifier.getJitterMs();
2012 if (tsjitter.getN() > 0) {
2013 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2014 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2015 }
2016 if (mLatencyMs.getN() > 0) {
2017 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2018 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2019 }
Robert Wu06db0a32021-08-10 19:05:34 +00002020 if (mMonopipePipeDepthStats.getN() > 0) {
2021 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2022 mMonopipePipeDepthStats.getMean());
2023 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2024 mMonopipePipeDepthStats.getStdDev());
2025 }
Andy Hungd0979812019-02-21 15:51:44 -08002026
2027 item->selfrecord();
2028}
2029
Andy Hung71742ab2023-07-07 13:47:37 -07002030product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002031{
Andy Hung2cbc2722023-07-17 17:05:00 -07002032 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002033 return PRODUCT_STRATEGY_NONE;
2034 }
2035 return AudioSystem::getStrategyForStream(stream);
2036}
2037
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002038// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002039void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002040 const sp<audio_utils::MelProcessor>& /*processor*/)
2041{
2042 // Do nothing
2043 ALOGW("%s: ThreadBase does not support CSD", __func__);
2044}
2045
2046// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002047void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002048{
2049 // Do nothing
2050 ALOGW("%s: ThreadBase does not support CSD", __func__);
2051}
2052
Eric Laurent81784c32012-11-19 14:55:58 -08002053// ----------------------------------------------------------------------------
2054// Playback
2055// ----------------------------------------------------------------------------
2056
Andy Hung2cbc2722023-07-17 17:05:00 -07002057PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002058 AudioStreamOut* output,
2059 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002060 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002061 bool systemReady,
2062 audio_config_base_t *mixerConfig)
Andy Hung2cbc2722023-07-17 17:05:00 -07002063 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002064 mNormalFrameCount(0), mSinkBuffer(NULL),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002065 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002066 mMixerBuffer(NULL),
2067 mMixerBufferSize(0),
2068 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2069 mMixerBufferValid(false),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002070 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002071 mEffectBuffer(NULL),
2072 mEffectBufferSize(0),
2073 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2074 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002075 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002076 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002077 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002078 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002079 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002080 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002081 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002082 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002083 mMixerStatus(MIXER_IDLE),
2084 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002085 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002086 mBytesRemaining(0),
2087 mCurrentWriteLength(0),
2088 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002089 mWriteAckSequence(0),
2090 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08002091 mScreenState(AudioFlinger::mScreenState),
2092 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002093 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002094 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002095 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl9e661ad2022-07-27 18:01:07 +02002096 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002097 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002098{
Glenn Kastend7dca052015-03-05 16:05:54 -08002099 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung2cbc2722023-07-17 17:05:00 -07002100 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002101
2102 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2103 // it would be safer to explicitly pass initial masterVolume/masterMute as
2104 // parameter.
2105 //
2106 // If the HAL we are using has support for master volume or master mute,
2107 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2108 // and the mute set to false).
Andy Hung2cbc2722023-07-17 17:05:00 -07002109 mMasterVolume = afThreadCallback->masterVolume_l();
2110 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002111 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002112 if (mOutput->audioHwDev->canSetMasterVolume()) {
2113 mMasterVolume = 1.0;
2114 }
2115
2116 if (mOutput->audioHwDev->canSetMasterMute()) {
2117 mMasterMute = false;
2118 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002119 mIsMsdDevice = strcmp(
2120 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002121 }
2122
Eric Laurentf1f22e72021-07-13 14:04:14 +02002123 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2124 mMixerChannelMask = mixerConfig->channel_mask;
2125 }
2126
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002127 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002128
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002129 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002130 && mMixerChannelMask != mChannelMask) {
2131 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2132 mChannelMask, mMixerChannelMask);
2133 }
2134
Andy Hungc8fddf32018-08-08 18:32:37 -07002135 // TODO: We may also match on address as well as device type for
2136 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002137 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002138 // TODO: This property should be ensure that only contains one single device type.
2139 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2140 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002141 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2142 : AUDIO_DEVICE_NONE));
2143 }
2144
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002145 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2146 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002147 mStreamTypes[stream].volume = 0.0f;
Andy Hung2cbc2722023-07-17 17:05:00 -07002148 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002149 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002150 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002151 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2152 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002153 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2154 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002155}
2156
Andy Hung71742ab2023-07-07 13:47:37 -07002157PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002158{
Andy Hung2cbc2722023-07-17 17:05:00 -07002159 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002160 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002161 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002162 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002163 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002164}
2165
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002166// Thread virtuals
2167
Andy Hung71742ab2023-07-07 13:47:37 -07002168void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002169{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002170 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002171 ALOGE("The stream is not open yet"); // This should not happen.
2172 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002173 // Callbacks take strong or weak pointers as a parameter.
2174 // Since PlaybackThread passes itself as a callback handler, it can only
2175 // be done outside of the constructor. Creating weak and especially strong
2176 // pointers to a refcounted object in its own constructor is strongly
2177 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2178 // Even if a function takes a weak pointer, it is possible that it will
2179 // need to convert it to a strong pointer down the line.
2180 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2181 mOutput->stream->setCallback(this) == OK) {
2182 mUseAsyncWrite = true;
Andy Hung71742ab2023-07-07 13:47:37 -07002183 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002184 }
2185
jiabinf6eb4c32020-02-25 14:06:25 -08002186 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002187 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002188 }
2189 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002190 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002191 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002192}
2193
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002194// ThreadBase virtuals
Andy Hung71742ab2023-07-07 13:47:37 -07002195void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002196{
2197 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002198 status_t result = mOutput->stream->exit();
2199 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002200}
2201
Andy Hung71742ab2023-07-07 13:47:37 -07002202void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002203{
Eric Laurent81784c32012-11-19 14:55:58 -08002204 String8 result;
2205
Marco Nelissenb2208842014-02-07 14:00:50 -08002206 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002207 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2208 const stream_type_t *st = &mStreamTypes[i];
2209 if (i > 0) {
2210 result.appendFormat(", ");
2211 }
2212 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2213 if (st->mute) {
2214 result.append("M");
2215 }
2216 }
2217 result.append("\n");
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002218 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002219 result.clear();
2220
Eric Laurent81784c32012-11-19 14:55:58 -08002221 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2222 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002223 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002224 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002225
2226 size_t numtracks = mTracks.size();
2227 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002228 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002229 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002230 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002231 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002232 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002233 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002234 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002235 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002236 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002237 if (track != 0) {
2238 bool active = mActiveTracks.indexOf(track) >= 0;
2239 if (active) {
2240 numactiveseen++;
2241 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002242 result.append(prefix);
2243 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002244 }
2245 }
2246 } else {
2247 result.append("\n");
2248 }
2249 if (numactiveseen != numactive) {
2250 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002251 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002252 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002253 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002254 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002255 for (size_t i = 0; i < numactive; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002256 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002257 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002258 result.append(prefix);
2259 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002260 }
2261 }
2262 }
2263
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002264 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002265}
2266
Andy Hung71742ab2023-07-07 13:47:37 -07002267void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002268{
Andy Hung04cb8f72020-03-20 13:44:33 -07002269 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002270 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002271 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2272 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002273 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2274 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2275 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2276 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002277 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002278 dprintf(fd, " Total writes: %d\n", mNumWrites);
2279 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2280 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2281 dprintf(fd, " Suspend count: %d\n", mSuspended);
2282 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2283 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2284 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2285 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002286 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002287 AudioStreamOut *output = mOutput;
2288 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002289 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002290 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002291 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2292 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2293 if (mPipeSink.get() != nullptr) {
2294 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2295 }
2296 if (output != nullptr) {
2297 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002298 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002299 }
Eric Laurent81784c32012-11-19 14:55:58 -08002300}
2301
Eric Laurent81784c32012-11-19 14:55:58 -08002302// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002303sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hungd65869f2023-06-27 17:05:02 -07002304 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002305 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002306 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002307 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002308 audio_format_t format,
2309 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002310 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002311 size_t *pNotificationFrameCount,
2312 uint32_t notificationsPerBuffer,
2313 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002314 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002315 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002316 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002317 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002318 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002319 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002320 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002321 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002322 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002323 bool isSpatialized,
2324 bool isBitPerfect)
Eric Laurent81784c32012-11-19 14:55:58 -08002325{
Glenn Kasten74935e42013-12-19 08:56:45 -08002326 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002327 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung3ff4b552023-06-26 19:20:57 -07002328 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002329 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002330 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002331 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002332 uint32_t sampleRate;
2333
2334 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2335 lStatus = BAD_VALUE;
2336 goto Exit;
2337 }
Eric Laurent21da6472017-11-09 16:29:26 -08002338
2339 if (*pSampleRate == 0) {
2340 *pSampleRate = mSampleRate;
2341 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002342 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002343
2344 // special case for FAST flag considered OK if fast mixer is present
2345 if (hasFastMixer()) {
2346 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2347 }
2348
2349 // Check if requested flags are compatible with output stream flags
2350 if ((*flags & outputFlags) != *flags) {
2351 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2352 *flags, outputFlags);
2353 *flags = (audio_output_flags_t)(*flags & outputFlags);
2354 }
Eric Laurent81784c32012-11-19 14:55:58 -08002355
jiabinc658e452022-10-21 20:52:21 +00002356 if (isBitPerfect) {
Andy Hungbd72c542023-06-20 18:56:17 -07002357 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002358 if (chain.get() != nullptr) {
2359 // Bit-perfect is required according to the configuration and preferred mixer
2360 // attributes, but it is not in the output flag from the client's request. Explicitly
2361 // adding bit-perfect flag to check the compatibility
2362 audio_output_flags_t flagsToCheck =
2363 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2364 chain->checkOutputFlagCompatibility(&flagsToCheck);
2365 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2366 ALOGE("%s cannot create track as there is data-processing effect attached to "
2367 "given session id(%d)", __func__, sessionId);
2368 lStatus = BAD_VALUE;
2369 goto Exit;
2370 }
2371 *flags = flagsToCheck;
2372 }
2373 }
2374
Eric Laurent81784c32012-11-19 14:55:58 -08002375 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002376 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002377 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002378 // PCM data
2379 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002380 // TODO: extract as a data library function that checks that a computationally
2381 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002382 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002383 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2384 (channelMask == AUDIO_CHANNEL_OUT_MONO
2385 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002386 // hardware sample rate
2387 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002388 // normal mixer has an associated fast mixer
2389 hasFastMixer() &&
2390 // there are sufficient fast track slots available
2391 (mFastTrackAvailMask != 0)
2392 // FIXME test that MixerThread for this fast track has a capable output HAL
2393 // FIXME add a permission test also?
2394 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002395 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2396 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002397 // read the fast track multiplier property the first time it is needed
2398 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2399 if (ok != 0) {
2400 ALOGE("%s pthread_once failed: %d", __func__, ok);
2401 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002402 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002403 }
Eric Laurent4c415062016-06-17 16:14:16 -07002404
2405 // check compatibility with audio effects.
2406 { // scope for mLock
2407 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002408 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002409 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002410 AUDIO_SESSION_OUTPUT_STAGE,
2411 AUDIO_SESSION_OUTPUT_MIX,
2412 sessionId,
2413 }) {
Andy Hungbd72c542023-06-20 18:56:17 -07002414 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002415 if (chain.get() != nullptr) {
2416 audio_output_flags_t old = *flags;
2417 chain->checkOutputFlagCompatibility(flags);
2418 if (old != *flags) {
2419 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2420 (int)session, (int)old, (int)*flags);
2421 }
Eric Laurent4c415062016-06-17 16:14:16 -07002422 }
2423 }
2424 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002425 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002426 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2427 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002428 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002429 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002430 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002431 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002432 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002433 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002434 audio_is_linear_pcm(format), channelMask, sampleRate,
2435 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002436 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002437 }
2438 }
Eric Laurent21da6472017-11-09 16:29:26 -08002439
2440 if (!audio_has_proportional_frames(format)) {
2441 if (sharedBuffer != 0) {
2442 // Same comment as below about ignoring frameCount parameter for set()
2443 frameCount = sharedBuffer->size();
2444 } else if (frameCount == 0) {
2445 frameCount = mNormalFrameCount;
2446 }
2447 if (notificationFrameCount != frameCount) {
2448 notificationFrameCount = frameCount;
2449 }
2450 } else if (sharedBuffer != 0) {
2451 // FIXME: Ensure client side memory buffers need
2452 // not have additional alignment beyond sample
2453 // (e.g. 16 bit stereo accessed as 32 bit frame).
2454 size_t alignment = audio_bytes_per_sample(format);
2455 if (alignment & 1) {
2456 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2457 alignment = 1;
2458 }
2459 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2460 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2461 if (channelCount > 1) {
2462 // More than 2 channels does not require stronger alignment than stereo
2463 alignment <<= 1;
2464 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002465 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002466 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002467 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002468 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002469 goto Exit;
2470 }
Eric Laurent21da6472017-11-09 16:29:26 -08002471
2472 // When initializing a shared buffer AudioTrack via constructors,
2473 // there's no frameCount parameter.
2474 // But when initializing a shared buffer AudioTrack via set(),
2475 // there _is_ a frameCount parameter. We silently ignore it.
2476 frameCount = sharedBuffer->size() / frameSize;
2477 } else {
2478 size_t minFrameCount = 0;
2479 // For fast tracks we try to respect the application's request for notifications per buffer.
2480 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2481 if (notificationsPerBuffer > 0) {
2482 // Avoid possible arithmetic overflow during multiplication.
2483 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2484 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2485 notificationsPerBuffer, mFrameCount);
2486 } else {
2487 minFrameCount = mFrameCount * notificationsPerBuffer;
2488 }
2489 }
2490 } else {
2491 // For normal PCM streaming tracks, update minimum frame count.
2492 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2493 // cover audio hardware latency.
2494 // This is probably too conservative, but legacy application code may depend on it.
2495 // If you change this calculation, also review the start threshold which is related.
2496 uint32_t latencyMs = latency_l();
2497 if (latencyMs == 0) {
2498 ALOGE("Error when retrieving output stream latency");
2499 lStatus = UNKNOWN_ERROR;
2500 goto Exit;
2501 }
2502
2503 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2504 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2505
Eric Laurent81784c32012-11-19 14:55:58 -08002506 }
Eric Laurent21da6472017-11-09 16:29:26 -08002507 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002508 frameCount = minFrameCount;
2509 }
Eric Laurent81784c32012-11-19 14:55:58 -08002510 }
Eric Laurent21da6472017-11-09 16:29:26 -08002511
2512 // Make sure that application is notified with sufficient margin before underrun.
2513 // The client can divide the AudioTrack buffer into sub-buffers,
2514 // and expresses its desire to server as the notification frame count.
2515 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2516 size_t maxNotificationFrames;
2517 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2518 // notify every HAL buffer, regardless of the size of the track buffer
2519 maxNotificationFrames = mFrameCount;
2520 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002521 // Triple buffer the notification period for a triple buffered mixer period;
2522 // otherwise, double buffering for the notification period is fine.
2523 //
2524 // TODO: This should be moved to AudioTrack to modify the notification period
2525 // on AudioTrack::setBufferSizeInFrames() changes.
2526 const int nBuffering =
2527 (uint64_t{frameCount} * mSampleRate)
2528 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2529
Eric Laurent21da6472017-11-09 16:29:26 -08002530 maxNotificationFrames = frameCount / nBuffering;
2531 // If client requested a fast track but this was denied, then use the smaller maximum.
2532 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2533 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2534 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2535 maxNotificationFrames = maxNotificationFramesFastDenied;
2536 }
2537 }
2538 }
2539 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2540 if (notificationFrameCount == 0) {
2541 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2542 maxNotificationFrames, frameCount);
2543 } else {
2544 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2545 notificationFrameCount, maxNotificationFrames, frameCount);
2546 }
2547 notificationFrameCount = maxNotificationFrames;
2548 }
2549 }
2550
Glenn Kasten74935e42013-12-19 08:56:45 -08002551 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002552 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002553
Glenn Kastenc3df8382014-03-13 15:05:25 -07002554 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002555 case BIT_PERFECT:
2556 if (isBitPerfect) {
2557 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2558 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2559 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2560 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2561 mChannelMask);
2562 lStatus = BAD_VALUE;
2563 goto Exit;
2564 }
2565 }
2566 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002567
2568 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002569 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002570 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002571 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2572 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002573 sampleRate, format, channelMask, mOutput, mFormat);
2574 lStatus = BAD_VALUE;
2575 goto Exit;
2576 }
2577 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002578 break;
2579
2580 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002581 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002582 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2583 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002584 sampleRate, format, channelMask, mOutput, mFormat);
2585 lStatus = BAD_VALUE;
2586 goto Exit;
2587 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002588 break;
2589
2590 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002591 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002592 ALOGE("createTrack_l() Bad parameter: format %#x \""
2593 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002594 format, mOutput, mFormat);
2595 lStatus = BAD_VALUE;
2596 goto Exit;
2597 }
Andy Hungcd044842014-08-07 11:04:34 -07002598 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002599 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2600 lStatus = BAD_VALUE;
2601 goto Exit;
2602 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002603 break;
2604
Eric Laurent81784c32012-11-19 14:55:58 -08002605 }
2606
2607 lStatus = initCheck();
2608 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002609 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002610 goto Exit;
2611 }
2612
2613 { // scope for mLock
2614 Mutex::Autolock _l(mLock);
2615
2616 // all tracks in same audio session must share the same routing strategy otherwise
2617 // conflicts will happen when tracks are moved from one output to another by audio policy
2618 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002619 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002620 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002621 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002622 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002623 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002624 if (sessionId == t->sessionId() && strategy != actual) {
2625 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2626 strategy, actual);
2627 lStatus = BAD_VALUE;
2628 goto Exit;
2629 }
2630 }
2631 }
2632
yucliuc9c49cd2020-07-13 16:25:21 -07002633 // Set DIRECT flag if current thread is DirectOutputThread. This can
2634 // happen when the playback is rerouted to direct output thread by
2635 // dynamic audio policy.
2636 // Do NOT report the flag changes back to client, since the client
2637 // doesn't explicitly request a direct flag.
2638 audio_output_flags_t trackFlags = *flags;
2639 if (mType == DIRECT) {
2640 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2641 }
2642
Andy Hung3ff4b552023-06-26 19:20:57 -07002643 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002644 channelMask, frameCount,
2645 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002646 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung3ff4b552023-06-26 19:20:57 -07002647 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002648 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002649
Glenn Kasten03003332013-08-06 15:40:54 -07002650 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2651 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002652 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002653 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002654 goto Exit;
2655 }
2656 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002657 {
2658 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2659 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002660 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002661 }
2662 }
Eric Laurent81784c32012-11-19 14:55:58 -08002663
Andy Hungbd72c542023-06-20 18:56:17 -07002664 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002665 if (chain != 0) {
2666 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2667 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002668 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002669 chain->incTrackCnt();
2670 }
2671
Eric Laurent05067782016-06-01 18:27:28 -07002672 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002673 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2674 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2675 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002676 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002677 }
2678 }
2679
2680 lStatus = NO_ERROR;
2681
2682Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002683 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002684 return track;
2685}
2686
Andy Hung1bc088a2018-02-09 15:57:31 -08002687template<typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07002688ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002689{
Andy Hungc0691382018-09-12 18:01:57 -07002690 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002691 const ssize_t index = mTracks.remove(track);
2692 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002693 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002694 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002695 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002696 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002697 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002698 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002699 }
2700 return index;
2701}
2702
Andy Hung71742ab2023-07-07 13:47:37 -07002703uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002704{
2705 return latency;
2706}
2707
Andy Hung71742ab2023-07-07 13:47:37 -07002708uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002709{
2710 Mutex::Autolock _l(mLock);
2711 return latency_l();
2712}
Andy Hung71742ab2023-07-07 13:47:37 -07002713uint32_t PlaybackThread::latency_l() const
Eric Laurent81784c32012-11-19 14:55:58 -08002714{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002715 uint32_t latency;
2716 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2717 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002718 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002719 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002720}
2721
Andy Hung71742ab2023-07-07 13:47:37 -07002722void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002723{
2724 Mutex::Autolock _l(mLock);
2725 // Don't apply master volume in SW if our HAL can do it for us.
2726 if (mOutput && mOutput->audioHwDev &&
2727 mOutput->audioHwDev->canSetMasterVolume()) {
2728 mMasterVolume = 1.0;
2729 } else {
2730 mMasterVolume = value;
2731 }
2732}
2733
Andy Hung71742ab2023-07-07 13:47:37 -07002734void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002735{
2736 mMasterBalance.store(balance);
2737}
2738
Andy Hung71742ab2023-07-07 13:47:37 -07002739void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002740{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002741 if (isDuplicating()) {
2742 return;
2743 }
Eric Laurent81784c32012-11-19 14:55:58 -08002744 Mutex::Autolock _l(mLock);
2745 // Don't apply master mute in SW if our HAL can do it for us.
2746 if (mOutput && mOutput->audioHwDev &&
2747 mOutput->audioHwDev->canSetMasterMute()) {
2748 mMasterMute = false;
2749 } else {
2750 mMasterMute = muted;
2751 }
2752}
2753
Andy Hung71742ab2023-07-07 13:47:37 -07002754void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002755{
2756 Mutex::Autolock _l(mLock);
2757 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002758 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002759}
2760
Andy Hung71742ab2023-07-07 13:47:37 -07002761void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002762{
2763 Mutex::Autolock _l(mLock);
2764 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002765 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002766}
2767
Andy Hung71742ab2023-07-07 13:47:37 -07002768float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002769{
2770 Mutex::Autolock _l(mLock);
2771 return mStreamTypes[stream].volume;
2772}
2773
Andy Hung71742ab2023-07-07 13:47:37 -07002774void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002775{
2776 mOutput->stream->setVolume(left, right);
2777}
2778
Eric Laurent81784c32012-11-19 14:55:58 -08002779// addTrack_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002780status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Andy Hung71ba4b32022-10-06 12:09:49 -07002781NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent81784c32012-11-19 14:55:58 -08002782{
2783 status_t status = ALREADY_EXISTS;
2784
Eric Laurent81784c32012-11-19 14:55:58 -08002785 if (mActiveTracks.indexOf(track) < 0) {
2786 // the track is newly added, make sure it fills up all its
2787 // buffers before playing. This is to ensure the client will
2788 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002789 if (track->isExternalTrack()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002790 IAfTrackBase::track_state state = track->state();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002791 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002792 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002793 mLock.lock();
2794 // abort track was stopped/paused while we released the lock
Andy Hung3ff4b552023-06-26 19:20:57 -07002795 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002796 if (status == NO_ERROR) {
2797 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002798 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002799 mLock.lock();
2800 }
2801 return INVALID_OPERATION;
2802 }
2803 // abort if start is rejected by audio policy manager
2804 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002805 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2806 // current playback thread is reopened, which may happen when clients set preferred
2807 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2808 // immediately.
2809 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002810 }
2811#ifdef ADD_BATTERY_DATA
2812 // to track the speaker usage
2813 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2814#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002815 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002816 }
2817
Eric Laurent51716182016-02-29 18:00:56 -08002818 // set retry count for buffer fill
2819 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002820 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002821 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002822 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07002823 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002824 }
Andy Hung3ff4b552023-06-26 19:20:57 -07002825 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002826 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07002827 track->retryCount() = kMaxTrackStartupRetries;
2828 track->fillingStatus() =
2829 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002830 }
2831
Andy Hungbd72c542023-06-20 18:56:17 -07002832 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002833 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2834 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2835 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002836 // Unlock due to VibratorService will lock for this call and will
2837 // call Tracks.mute/unmute which also require thread's lock.
2838 mLock.unlock();
Simon Bowden62823412022-10-17 14:52:26 +00002839 const os::HapticScale intensity = AudioFlinger::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002840 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002841 std::optional<media::AudioVibratorInfo> vibratorInfo;
2842 {
2843 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2844 // used to play this track.
Andy Hung2cbc2722023-07-17 17:05:00 -07002845 Mutex::Autolock _l(mAfThreadCallback->mutex());
2846 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002847 }
jiabin57303cc2018-12-18 15:45:57 -08002848 mLock.lock();
Simon Bowden62823412022-10-17 14:52:26 +00002849 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002850 if (vibratorInfo) {
2851 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2852 }
2853
jiabin57303cc2018-12-18 15:45:57 -08002854 // Haptic playback should be enabled by vibrator service.
2855 if (track->getHapticPlaybackEnabled()) {
2856 // Disable haptic playback of all active track to ensure only
2857 // one track playing haptic if current track should play haptic.
2858 for (const auto &t : mActiveTracks) {
2859 t->setHapticPlaybackEnabled(false);
2860 }
jiabin245cdd92018-12-07 17:55:15 -08002861 }
jiabine70bc7f2020-06-30 22:07:55 -07002862
2863 // Set haptic intensity for effect
2864 if (chain != nullptr) {
2865 chain->setHapticIntensity_l(track->id(), intensity);
2866 }
jiabin245cdd92018-12-07 17:55:15 -08002867 }
2868
Andy Hung3ff4b552023-06-26 19:20:57 -07002869 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002870 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002871 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002872 if (chain != 0) {
2873 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2874 track->sessionId());
2875 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002876 }
2877
Andy Hungc2b11cb2020-04-22 09:04:01 -07002878 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002879 status = NO_ERROR;
2880 }
2881
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002882 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002883 return status;
2884}
2885
Andy Hung71742ab2023-07-07 13:47:37 -07002886bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002887{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002888 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002889 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002890 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung3ff4b552023-06-26 19:20:57 -07002891 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002892 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002893 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002894 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002895 if (track->isPausePending()) {
2896 track->pauseAck();
2897 }
Andy Hung3ff4b552023-06-26 19:20:57 -07002898 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002899 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002900
2901 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002902}
2903
Andy Hung71742ab2023-07-07 13:47:37 -07002904void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002905{
2906 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002907
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002908 String8 result;
2909 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002910 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002911
Eric Laurent81784c32012-11-19 14:55:58 -08002912 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002913 {
2914 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2915 mAudioTrackCallbacks.erase(track);
2916 }
Eric Laurent81784c32012-11-19 14:55:58 -08002917 if (track->isFastTrack()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002918 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002919 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002920 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2921 mFastTrackAvailMask |= 1 << index;
2922 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung3ff4b552023-06-26 19:20:57 -07002923 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002924 }
Andy Hungbd72c542023-06-20 18:56:17 -07002925 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002926 if (chain != 0) {
2927 chain->decTrackCnt();
2928 }
2929}
2930
Andy Hung71742ab2023-07-07 13:47:37 -07002931String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08002932{
Eric Laurent81784c32012-11-19 14:55:58 -08002933 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002934 String8 out_s8;
2935 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2936 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002937 }
Andy Hung71ba4b32022-10-06 12:09:49 -07002938 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08002939}
2940
Andy Hung71742ab2023-07-07 13:47:37 -07002941status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002942 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002943 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002944 return NO_INIT;
2945 }
2946 return mOutput->stream->selectPresentation(presentationId, programId);
2947}
2948
Andy Hung71742ab2023-07-07 13:47:37 -07002949void PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002950 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002951 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07002952 sp<AudioIoDescriptor> desc;
2953 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002954 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002955 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002956 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002957 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002958 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
2959 mSampleRate, mFormat, mChannelMask,
2960 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
2961 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08002962 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002963 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002964 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07002965 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002966 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002967 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002968 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08002969 break;
2970 }
Andy Hung2cbc2722023-07-17 17:05:00 -07002971 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002972}
2973
Andy Hung71742ab2023-07-07 13:47:37 -07002974void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002975{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002976 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002977}
2978
Andy Hung71742ab2023-07-07 13:47:37 -07002979void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002980{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002981 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002982}
2983
Andy Hung71742ab2023-07-07 13:47:37 -07002984void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002985{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002986 mCallbackThread->setAsyncError();
2987}
2988
Andy Hung71742ab2023-07-07 13:47:37 -07002989void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08002990 const std::basic_string<uint8_t>& metadataBs)
2991{
Andy Hung71742ab2023-07-07 13:47:37 -07002992 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08002993 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hung71742ab2023-07-07 13:47:37 -07002994 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08002995 if (playbackThread == nullptr) {
2996 ALOGW("PlaybackThread was destroyed, skip codec format change event");
2997 return;
2998 }
2999
jiabinf6eb4c32020-02-25 14:06:25 -08003000 audio_utils::metadata::Data metadata =
3001 audio_utils::metadata::dataFromByteString(metadataBs);
3002 if (metadata.empty()) {
3003 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3004 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3005 (int)metadataBs.size());
3006 return;
3007 }
3008
3009 audio_utils::metadata::ByteString metaDataStr =
3010 audio_utils::metadata::byteStringFromData(metadata);
3011 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
3012 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07003013 for (const auto& callbackPair : mAudioTrackCallbacks) {
3014 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003015 }
3016 }).detach();
3017}
3018
Andy Hung71742ab2023-07-07 13:47:37 -07003019void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003020{
3021 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003022 // reject out of sequence requests
3023 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3024 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003025 mWaitWorkCV.signal();
3026 }
3027}
3028
Andy Hung71742ab2023-07-07 13:47:37 -07003029void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003030{
3031 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003032 // reject out of sequence requests
3033 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003034 // Register discontinuity when HW drain is completed because that can cause
3035 // the timestamp frame position to reset to 0 for direct and offload threads.
3036 // (Out of sequence requests are ignored, since the discontinuity would be handled
3037 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003038 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003039 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003040 mWaitWorkCV.signal();
3041 }
3042}
3043
Andy Hung71742ab2023-07-07 13:47:37 -07003044void PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003045{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003046 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003047 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3048 mSampleRate = audioConfig.sample_rate;
3049 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003050 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003051 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003052 }
Andy Hung71742ab2023-07-07 13:47:37 -07003053 if (hasMixer() && !AudioFlinger::isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003054 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3055 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003056 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003057
3058 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3059 mMixerChannelMask = mChannelMask;
3060 }
3061
Andy Hunge5412692014-05-16 11:25:07 -07003062 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003063 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003064
Eric Laurentf1f22e72021-07-13 14:04:14 +02003065 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3066
Phil Burkca5e6142015-07-14 09:42:29 -07003067 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003068 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003069 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003070 // Get format from the shim, which will be different than the HAL format
3071 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003072 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003073 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003074 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003075 }
Andy Hung71742ab2023-07-07 13:47:37 -07003076 if (hasMixer() && !AudioFlinger::isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003077 LOG_FATAL("HAL format %#x not supported for mixed output",
3078 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003079 }
Phil Burk062e67a2015-02-11 13:40:50 -08003080 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003081 result = mOutput->stream->getBufferSize(&mBufferSize);
3082 LOG_ALWAYS_FATAL_IF(result != OK,
3083 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003084 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003085 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003086 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003087 mFrameCount);
3088 }
3089
Eric Laurentd1f69b02014-12-15 14:33:13 -08003090 mHwSupportsPause = false;
3091 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003092 bool supportsPause = false, supportsResume = false;
3093 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3094 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003095 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003096 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003097 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003098 } else if (supportsResume) {
3099 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003100 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003101 }
3102 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003103 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3104 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3105 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003106
Andy Hungfbfc3952015-01-15 13:33:51 -08003107 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3108 // For best precision, we use float instead of the associated output
3109 // device format (typically PCM 16 bit).
3110
3111 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3112 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3113 mBufferSize = mFrameSize * mFrameCount;
3114
3115 // TODO: We currently use the associated output device channel mask and sample rate.
3116 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3117 // (if a valid mask) to avoid premature downmix.
3118 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3119 // instead of the output device sample rate to avoid loss of high frequency information.
3120 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3121 }
3122
Andy Hung09a50072014-02-27 14:30:47 -08003123 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003124 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003125 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003126 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3127 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003128 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3129 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003130
Eric Laurent81784c32012-11-19 14:55:58 -08003131 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3132 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3133 maxNormalFrameCount = maxNormalFrameCount & ~15;
3134 if (maxNormalFrameCount < minNormalFrameCount) {
3135 maxNormalFrameCount = minNormalFrameCount;
3136 }
3137 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3138 if (multiplier <= 1.0) {
3139 multiplier = 1.0;
3140 } else if (multiplier <= 2.0) {
3141 if (2 * mFrameCount <= maxNormalFrameCount) {
3142 multiplier = 2.0;
3143 } else {
3144 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3145 }
3146 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003147 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003148 }
3149 }
3150 mNormalFrameCount = multiplier * mFrameCount;
3151 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003152 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003153 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3154 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003155 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003156 mNormalFrameCount);
3157
Andy Hung08fb1742015-05-31 23:22:10 -07003158 // Check if we want to throttle the processing to no more than 2x normal rate
3159 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003160 mThreadThrottleTimeMs = 0;
3161 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003162 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3163
Andy Hung010a1a12014-03-13 13:57:33 -07003164 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3165 // Originally this was int16_t[] array, need to remove legacy implications.
3166 free(mSinkBuffer);
3167 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003168
Andy Hung5b10a202014-03-13 13:59:29 -07003169 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3170 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3171 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003172 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003173
Andy Hung69aed5f2014-02-25 17:24:40 -08003174 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3175 // drives the output.
3176 free(mMixerBuffer);
3177 mMixerBuffer = NULL;
3178 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003179 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003180 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003181 * audio_bytes_per_sample(mMixerBufferFormat);
3182 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3183 }
Andy Hung98ef9782014-03-04 14:46:50 -08003184 free(mEffectBuffer);
3185 mEffectBuffer = NULL;
3186 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003187 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003188 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003189 * audio_bytes_per_sample(mEffectBufferFormat);
3190 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3191 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003192
Eric Laurentb62d0362021-10-26 17:40:18 +02003193 if (mType == SPATIALIZER) {
3194 free(mPostSpatializerBuffer);
3195 mPostSpatializerBuffer = nullptr;
3196 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3197 * audio_bytes_per_sample(mEffectBufferFormat);
3198 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3199 }
3200
Mikhail Naganov55773032020-10-01 15:08:13 -07003201 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3202 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003203 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3204 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003205 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003206
Eric Laurent81784c32012-11-19 14:55:58 -08003207 // force reconfiguration of effect chains and engines to take new buffer size and audio
3208 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003209 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003210 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3211 // matter.
3212 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
Andy Hungbd72c542023-06-20 18:56:17 -07003213 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003214 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung2cbc2722023-07-17 17:05:00 -07003215 mAfThreadCallback->moveEffectChain_l(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003216 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003217 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003218
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003219 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003220 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003221 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3222 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3223 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3224 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3225 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3226 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3227 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3228 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3229 (int32_t)mHapticChannelMask)
3230 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3231 (int32_t)mHapticChannelCount)
3232 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3233 formatToString(mHALFormat).c_str())
3234 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3235 (int32_t)mFrameCount) // sic - added HAL
3236 ;
3237 uint32_t latencyMs;
3238 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3239 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3240 }
3241 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003242}
3243
Andy Hung71742ab2023-07-07 13:47:37 -07003244ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003245{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003246 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003247 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003248 }
3249 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003250 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung3ff4b552023-06-26 19:20:57 -07003251 for (const sp<IAfTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -07003252 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003253 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003254 }
Kevin Rocard12381092018-04-11 09:19:59 -07003255 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003256 MetadataUpdate change;
3257 change.playbackMetadataUpdate = metadata.tracks;
3258 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003259}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003260
Andy Hung71742ab2023-07-07 13:47:37 -07003261void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003262 const StreamOutHalInterface::SourceMetadata& metadata)
3263{
3264 mOutput->stream->updateSourceMetadata(metadata);
3265};
3266
Andy Hung71742ab2023-07-07 13:47:37 -07003267status_t PlaybackThread::getRenderPosition(
Andy Hung4989d312023-06-29 21:19:25 -07003268 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003269{
3270 if (halFrames == NULL || dspFrames == NULL) {
3271 return BAD_VALUE;
3272 }
3273 Mutex::Autolock _l(mLock);
3274 if (initCheck() != NO_ERROR) {
3275 return INVALID_OPERATION;
3276 }
Andy Hung818e7a32016-02-16 18:08:07 -08003277 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003278 *halFrames = framesWritten;
3279
3280 if (isSuspended()) {
3281 // return an estimation of rendered frames when the output is suspended
3282 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003283 *dspFrames = (uint32_t)
3284 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003285 return NO_ERROR;
3286 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003287 status_t status;
3288 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003289 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003290 *dspFrames = (size_t)frames;
3291 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003292 }
3293}
3294
Andy Hung71742ab2023-07-07 13:47:37 -07003295product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003296{
3297 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3298 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3299 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003300 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003301 }
3302 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003303 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003304 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003305 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003306 }
3307 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003308 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003309}
3310
3311
Andy Hung71742ab2023-07-07 13:47:37 -07003312AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003313{
3314 Mutex::Autolock _l(mLock);
3315 return mOutput;
3316}
3317
Andy Hung71742ab2023-07-07 13:47:37 -07003318AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003319{
3320 Mutex::Autolock _l(mLock);
3321 AudioStreamOut *output = mOutput;
3322 mOutput = NULL;
3323 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3324 // must push a NULL and wait for ack
3325 mOutputSink.clear();
3326 mPipeSink.clear();
3327 mNormalSink.clear();
3328 return output;
3329}
3330
3331// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hung71742ab2023-07-07 13:47:37 -07003332sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003333{
3334 if (mOutput == NULL) {
3335 return NULL;
3336 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003337 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003338}
3339
Andy Hung71742ab2023-07-07 13:47:37 -07003340uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003341{
3342 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3343}
3344
Andy Hung71742ab2023-07-07 13:47:37 -07003345status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003346{
3347 if (!isValidSyncEvent(event)) {
3348 return BAD_VALUE;
3349 }
3350
3351 Mutex::Autolock _l(mLock);
3352
3353 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003354 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003355 if (event->triggerSession() == track->sessionId()) {
3356 (void) track->setSyncEvent(event);
3357 return NO_ERROR;
3358 }
3359 }
3360
3361 return NAME_NOT_FOUND;
3362}
3363
Andy Hung71742ab2023-07-07 13:47:37 -07003364bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003365{
3366 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3367}
3368
Andy Hung71742ab2023-07-07 13:47:37 -07003369void PlaybackThread::threadLoop_removeTracks(
Andy Hung3ff4b552023-06-26 19:20:57 -07003370 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003371{
Andy Hungfe726a62018-09-27 15:17:25 -07003372 // Miscellaneous track cleanup when removed from the active list,
3373 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003374#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003375 for (const auto& track : tracksToRemove) {
3376 if (track->isExternalTrack()) {
3377 // to track the speaker usage
3378 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003379 }
3380 }
Andy Hungfe726a62018-09-27 15:17:25 -07003381#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003382}
3383
Andy Hung71742ab2023-07-07 13:47:37 -07003384void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003385{
3386 if (!mMasterMute) {
3387 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003388 if (mOutDeviceTypeAddrs.empty()) {
3389 ALOGD("ro.audio.silent is ignored since no output device is set");
3390 return;
3391 }
jiabinc52b1ff2019-10-31 17:20:42 -07003392 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003393 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3394 return;
3395 }
Eric Laurent81784c32012-11-19 14:55:58 -08003396 if (property_get("ro.audio.silent", value, "0") > 0) {
3397 char *endptr;
3398 unsigned long ul = strtoul(value, &endptr, 0);
3399 if (*endptr == '\0' && ul != 0) {
3400 ALOGD("Silence is golden");
3401 // The setprop command will not allow a property to be changed after
3402 // the first time it is set, so we don't have to worry about un-muting.
3403 setMasterMute_l(true);
3404 }
3405 }
3406 }
3407}
3408
3409// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung71742ab2023-07-07 13:47:37 -07003410ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003411{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003412 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003413 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003414 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003415 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003416
3417 // If an NBAIO sink is present, use it to write the normal mixer's submix
3418 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003419
Andy Hung010a1a12014-03-13 13:57:33 -07003420 const size_t count = mBytesRemaining / mFrameSize;
3421
Simon Wilson2d590962012-11-29 15:18:50 -08003422 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003423 // update the setpoint when AudioFlinger::mScreenState changes
3424 uint32_t screenState = AudioFlinger::mScreenState;
3425 if (screenState != mScreenState) {
3426 mScreenState = screenState;
3427 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3428 if (pipe != NULL) {
3429 pipe->setAvgFrames((mScreenState & 1) ?
3430 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3431 }
3432 }
Andy Hung010a1a12014-03-13 13:57:33 -07003433 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003434 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003435
Eric Laurent81784c32012-11-19 14:55:58 -08003436 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003437 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003438
Andy Hung8946a282018-04-19 20:04:56 -07003439#ifdef TEE_SINK
3440 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3441#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003442 } else {
3443 bytesWritten = framesWritten;
3444 }
3445 // otherwise use the HAL / AudioStreamOut directly
3446 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003447 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003448
Eric Laurentbfb1b832013-01-07 09:53:42 -08003449 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003450 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3451 mWriteAckSequence += 2;
3452 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003453 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003454 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003455 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003456 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003457 // FIXME We should have an implementation of timestamps for direct output threads.
3458 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003459 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003460 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003461
Eric Laurentbfb1b832013-01-07 09:53:42 -08003462 if (mUseAsyncWrite &&
3463 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3464 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003465 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003466 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003467 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003468 }
Eric Laurent81784c32012-11-19 14:55:58 -08003469 }
3470
Eric Laurent81784c32012-11-19 14:55:58 -08003471 mNumWrites++;
3472 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003473 if (mStandby) {
3474 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003475 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003476 mStandby = false;
3477 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003478 return bytesWritten;
3479}
3480
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003481// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07003482void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003483 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003484{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003485 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003486 if (outputSink != nullptr) {
3487 outputSink->startMelComputation(processor);
3488 }
Vlad Popab042ee62022-10-20 18:05:00 +02003489}
3490
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003491// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07003492void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003493{
3494 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003495 if (outputSink != nullptr) {
3496 outputSink->stopMelComputation();
3497 }
Vlad Popab042ee62022-10-20 18:05:00 +02003498}
3499
Andy Hung71742ab2023-07-07 13:47:37 -07003500void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003501{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003502 bool supportsDrain = false;
3503 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003504 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3505 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003506 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3507 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003508 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003509 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003510 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003511 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003512 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003513 }
3514}
3515
Andy Hung71742ab2023-07-07 13:47:37 -07003516void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003517{
Eric Laurent275e8e92014-11-30 15:14:47 -08003518 {
3519 Mutex::Autolock _l(mLock);
3520 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003521 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003522 track->invalidate();
3523 }
Andy Hungdae27702016-10-31 14:01:16 -07003524 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3525 // After we exit there are no more track changes sent to BatteryNotifier
3526 // because that requires an active threadLoop.
3527 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3528 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003529 }
Eric Laurent81784c32012-11-19 14:55:58 -08003530}
3531
3532/*
3533The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003534 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003535 - mActiveSleepTimeUs from activeSleepTimeUs()
3536 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003537 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3538 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003539 - maxPeriod from frame count and sample rate (MIXER only)
3540
3541The parameters that affect these derived values are:
3542 - frame count
3543 - frame size
3544 - sample rate
3545 - device type: A2DP or not
3546 - device latency
3547 - format: PCM or not
3548 - active sleep time
3549 - idle sleep time
3550*/
3551
Andy Hung71742ab2023-07-07 13:47:37 -07003552void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003553{
Andy Hung25c2dac2014-02-27 14:56:00 -08003554 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003555 mActiveSleepTimeUs = activeSleepTimeUs();
3556 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003557
Eric Laurent52568142022-10-28 11:23:28 +02003558 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
Carter Hsu0ca47c22023-06-02 18:01:45 +08003559
Eric Laurent42537be2016-01-08 17:16:42 -08003560 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3561 // truncating audio when going to standby.
jiabinc52b1ff2019-10-31 17:20:42 -07003562 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003563 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3564 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3565 }
3566 }
Eric Laurent81784c32012-11-19 14:55:58 -08003567}
3568
Andy Hung71742ab2023-07-07 13:47:37 -07003569bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003570{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003571 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003572 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003573 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003574 size_t size = mTracks.size();
3575 for (size_t i = 0; i < size; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003576 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003577 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003578 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003579 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003580 }
3581 }
Eric Laurent13084622016-05-17 10:51:49 -07003582 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003583}
3584
Andy Hung71742ab2023-07-07 13:47:37 -07003585void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003586{
3587 Mutex::Autolock _l(mLock);
3588 invalidateTracks_l(streamType);
3589}
3590
Andy Hung71742ab2023-07-07 13:47:37 -07003591void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003592 Mutex::Autolock _l(mLock);
3593 invalidateTracks_l(portIds);
3594}
3595
Andy Hung71742ab2023-07-07 13:47:37 -07003596bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003597 bool trackMatch = false;
3598 const size_t size = mTracks.size();
3599 for (size_t i = 0; i < size; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003600 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003601 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3602 t->invalidate();
3603 portIds.erase(t->portId());
3604 trackMatch = true;
3605 }
3606 if (portIds.empty()) {
3607 break;
3608 }
3609 }
3610 return trackMatch;
3611}
3612
jiabinf042b9b2021-05-07 23:46:28 +00003613// getTrackById_l must be called with holding thread lock
Andy Hung71742ab2023-07-07 13:47:37 -07003614IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003615 audio_port_handle_t trackPortId) {
3616 for (size_t i = 0; i < mTracks.size(); i++) {
3617 if (mTracks[i]->portId() == trackPortId) {
3618 return mTracks[i].get();
3619 }
3620 }
3621 return nullptr;
3622}
3623
Andy Hung71742ab2023-07-07 13:47:37 -07003624status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003625{
Glenn Kastend848eb42016-03-08 13:42:11 -08003626 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003627 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003628 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003629
Andy Hungd3639922022-04-28 18:00:49 -07003630 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003631 if (!audio_is_global_session(session)) {
3632 // player sessions on a spatializer output will use a dedicated input buffer and
3633 // will either output multi channel to mEffectBuffer if the track is spatilaized
3634 // or stereo to mPostSpatializerBuffer if not spatialized.
3635 uint32_t channelMask;
3636 bool isSessionSpatialized =
3637 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3638 if (isSessionSpatialized) {
3639 channelMask = mMixerChannelMask;
3640 } else {
3641 channelMask = mChannelMask;
3642 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003643 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003644 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung2cbc2722023-07-17 17:05:00 -07003645 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003646 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003647 &halInBuffer);
3648 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003649
Andy Hung2cbc2722023-07-17 17:05:00 -07003650 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003651 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3652 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3653 &halOutBuffer);
3654 if (result != OK) return result;
3655
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003656 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003657
Mikhail Naganov022b9952017-01-04 16:36:51 -08003658 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3659 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003660 } else {
3661 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3662 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3663 // mPostSpatializerBuffer as output buffer
3664 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung2cbc2722023-07-17 17:05:00 -07003665 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003666 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3667 if (result != OK) return result;
Andy Hung2cbc2722023-07-17 17:05:00 -07003668 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003669 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3670 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003671
Eric Laurentb62d0362021-10-26 17:40:18 +02003672 if (session == AUDIO_SESSION_DEVICE) {
3673 halInBuffer = halOutBuffer;
3674 }
3675 }
3676 } else {
Andy Hung2cbc2722023-07-17 17:05:00 -07003677 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003678 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3679 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3680 &halInBuffer);
3681 if (result != OK) return result;
3682 halOutBuffer = halInBuffer;
3683 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3684 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003685 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003686 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003687 // Only one effect chain can be present in direct output thread and it uses
3688 // the sink buffer as input
3689 if (mType != DIRECT) {
3690 size_t numSamples = mNormalFrameCount
3691 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3692 + mHapticChannelCount);
Andy Hung2cbc2722023-07-17 17:05:00 -07003693 const status_t allocateStatus =
3694 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003695 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003696 &halInBuffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07003697 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003698
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003699 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003700 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3701 buffer, session);
3702 }
3703 }
3704 }
3705
3706 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003707 // Attach all tracks with same session ID to this chain.
3708 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003709 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003710 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003711 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3712 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003713 track->setMainBuffer(buffer);
3714 chain->incTrackCnt();
3715 }
3716 }
3717
3718 // indicate all active tracks in the chain
Andy Hung3ff4b552023-06-26 19:20:57 -07003719 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003720 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003721 ALOGV("addEffectChain_l() activating track %p on session %d",
3722 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003723 chain->incActiveTrackCnt();
3724 }
3725 }
3726 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003727
Eric Laurentaaa44472014-09-12 17:41:50 -07003728 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003729 chain->setInBuffer(halInBuffer);
3730 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003731 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3732 // chains list in order to be processed last as it contains output device effects.
3733 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3734 // processing effects specific to an output stream before effects applied to all streams
3735 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003736 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3737 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003738 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003739 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003740 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003741 // Effect chain for other sessions are inserted at beginning of effect
3742 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003743 // sessions is not important.
3744 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003745 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3746 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003747 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003748 size_t size = mEffectChains.size();
3749 size_t i = 0;
3750 for (i = 0; i < size; i++) {
3751 if (mEffectChains[i]->sessionId() < session) {
3752 break;
3753 }
3754 }
3755 mEffectChains.insertAt(chain, i);
3756 checkSuspendOnAddEffectChain_l(chain);
3757
3758 return NO_ERROR;
3759}
3760
Andy Hung71742ab2023-07-07 13:47:37 -07003761size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003762{
Glenn Kastend848eb42016-03-08 13:42:11 -08003763 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003764
3765 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3766
3767 for (size_t i = 0; i < mEffectChains.size(); i++) {
3768 if (chain == mEffectChains[i]) {
3769 mEffectChains.removeAt(i);
3770 // detach all active tracks from the chain
Andy Hung3ff4b552023-06-26 19:20:57 -07003771 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003772 if (session == track->sessionId()) {
3773 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3774 chain.get(), session);
3775 chain->decActiveTrackCnt();
3776 }
3777 }
3778
3779 // detach all tracks with same session ID from this chain
Andy Hung71ba4b32022-10-06 12:09:49 -07003780 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003781 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003782 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003783 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003784 chain->decTrackCnt();
3785 }
3786 }
3787 break;
3788 }
3789 }
3790 return mEffectChains.size();
3791}
3792
Andy Hung71742ab2023-07-07 13:47:37 -07003793status_t PlaybackThread::attachAuxEffect(
Andy Hung3ff4b552023-06-26 19:20:57 -07003794 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003795{
3796 Mutex::Autolock _l(mLock);
3797 return attachAuxEffect_l(track, EffectId);
3798}
3799
Andy Hung71742ab2023-07-07 13:47:37 -07003800status_t PlaybackThread::attachAuxEffect_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07003801 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003802{
3803 status_t status = NO_ERROR;
3804
3805 if (EffectId == 0) {
3806 track->setAuxBuffer(0, NULL);
3807 } else {
3808 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hungbd72c542023-06-20 18:56:17 -07003809 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003810 if (effect != 0) {
3811 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3812 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3813 } else {
3814 status = INVALID_OPERATION;
3815 }
3816 } else {
3817 status = BAD_VALUE;
3818 }
3819 }
3820 return status;
3821}
3822
Andy Hung71742ab2023-07-07 13:47:37 -07003823void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003824{
3825 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003826 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003827 if (track->auxEffectId() == effectId) {
3828 attachAuxEffect_l(track, 0);
3829 }
3830 }
3831}
3832
Andy Hung71742ab2023-07-07 13:47:37 -07003833bool PlaybackThread::threadLoop()
Andy Hung71ba4b32022-10-06 12:09:49 -07003834NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003835{
Andy Hung4bf583b2023-05-30 18:10:23 -07003836 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003837
Andy Hung3ff4b552023-06-26 19:20:57 -07003838 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003839
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003840 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003841 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003842
3843 // MIXER
3844 nsecs_t lastWarning = 0;
3845
3846 // DUPLICATING
3847 // FIXME could this be made local to while loop?
3848 writeFrames = 0;
3849
3850 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003851 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003852
Andy Hungd3639922022-04-28 18:00:49 -07003853 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003854 sleepTimeShift = 0;
3855 }
3856
3857 CpuStats cpuStats;
3858 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3859
3860 acquireWakeLock();
3861
Glenn Kasteneef598c2017-04-03 14:41:13 -07003862 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3863 // thread associated with this PlaybackThread.
3864 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3865 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003866 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3867 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003868 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003869 const char *logString = NULL;
3870
rago1bb90822017-05-02 18:31:48 -07003871 // Estimated time for next buffer to be written to hal. This is used only on
3872 // suspended mode (for now) to help schedule the wait time until next iteration.
3873 nsecs_t timeLoopNextNs = 0;
3874
Eric Laurent664539d2013-09-23 18:24:31 -07003875 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003876
Andy Hung2dbffc22018-08-08 18:50:41 -07003877 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003878
Eric Laurentb3f315a2021-07-13 15:09:05 +02003879 sendCheckOutputStageEffectsEvent();
3880
Andy Hung446f4df2019-02-21 12:26:41 -08003881 // loopCount is used for statistics and diagnostics.
3882 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003883 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003884 // Log merge requests are performed during AudioFlinger binder transactions, but
3885 // that does not cover audio playback. It's requested here for that reason.
Andy Hung2cbc2722023-07-17 17:05:00 -07003886 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003887
Eric Laurent81784c32012-11-19 14:55:58 -08003888 cpuStats.sample(myName);
3889
Andy Hungbd72c542023-06-20 18:56:17 -07003890 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003891 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003892 bool isHapticSessionSpatialized = false;
Andy Hung3ff4b552023-06-26 19:20:57 -07003893 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003894
Andy Hung2dbffc22018-08-08 18:50:41 -07003895 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3896 //
jiabinc52b1ff2019-10-31 17:20:42 -07003897 // Note: we access outDeviceTypes() outside of mLock.
3898 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003899 // Here, we try for the AF lock, but do not block on it as the latency
3900 // is more informational.
Andy Hung2cbc2722023-07-17 17:05:00 -07003901 if (mAfThreadCallback->mutex().tryLock() == NO_ERROR) {
Andy Hungd63e79d2023-07-13 16:52:46 -07003902 std::vector<SoftwarePatch> swPatches;
Andy Hung71ba4b32022-10-06 12:09:49 -07003903 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07003904 status_t status = INVALID_OPERATION;
3905 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung2cbc2722023-07-17 17:05:00 -07003906 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungd63e79d2023-07-13 16:52:46 -07003907 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07003908 && swPatches.size() > 0) {
3909 status = swPatches[0].getLatencyMs_l(&latencyMs);
3910 downstreamPatchHandle = swPatches[0].getPatchHandle();
3911 }
3912 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003913 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003914 lastDownstreamPatchHandle = downstreamPatchHandle;
3915 }
3916 if (status == OK) {
3917 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003918 // latency of 5 seconds).
3919 const double minLatency = 0., maxLatency = 5000.;
3920 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003921 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003922 } else {
3923 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung71ba4b32022-10-06 12:09:49 -07003924 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07003925 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003926 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003927 }
Andy Hung2cbc2722023-07-17 17:05:00 -07003928 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07003929 }
3930 } else {
3931 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3932 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003933 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003934 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3935 }
3936 }
3937
Eric Laurentb3f315a2021-07-13 15:09:05 +02003938 if (mCheckOutputStageEffects.exchange(false)) {
3939 checkOutputStageEffects();
3940 }
3941
Vlad Popa7e81cea2023-01-19 16:34:16 +01003942 MetadataUpdate metadataUpdate;
Eric Laurent81784c32012-11-19 14:55:58 -08003943 { // scope for mLock
3944
3945 Mutex::Autolock _l(mLock);
3946
Eric Laurent021cf962014-05-13 10:18:14 -07003947 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003948 if (mCheckOutputStageEffects.load()) {
3949 continue;
3950 }
Eric Laurent10351942014-05-08 18:49:52 -07003951
Glenn Kasteneef598c2017-04-03 14:41:13 -07003952 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003953 if (logString != NULL) {
3954 mNBLogWriter->logTimestamp();
3955 mNBLogWriter->log(logString);
3956 logString = NULL;
3957 }
3958
Dean Wheatley12473e92021-03-18 23:00:55 +11003959 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003960
Eric Laurent81784c32012-11-19 14:55:58 -08003961 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003962 if (mSignalPending) {
3963 // A signal was raised while we were unlocked
3964 mSignalPending = false;
3965 } else if (waitingAsyncCallback_l()) {
3966 if (exitPending()) {
3967 break;
3968 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003969 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003970 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003971 releaseWakeLock_l();
3972 released = true;
3973 }
Andy Hung10cbff12017-02-21 17:30:14 -08003974
3975 const int64_t waitNs = computeWaitTimeNs_l();
3976 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3977 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3978 if (status == TIMED_OUT) {
3979 mSignalPending = true; // if timeout recheck everything
3980 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003981 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003982 if (released) {
3983 acquireWakeLock_l();
3984 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003985 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3986 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003987
3988 continue;
3989 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003990 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003991 isSuspended()) {
3992 // put audio hardware into standby after short delay
3993 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003994
3995 threadLoop_standby();
3996
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003997 // This is where we go into standby
3998 if (!mStandby) {
3999 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004000 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004001 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004002 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004003 }
Andy Hungd0979812019-02-21 15:51:44 -08004004 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004005 }
4006
Eric Tan39ec8d62018-07-24 09:49:29 -07004007 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004008 // we're about to wait, flush the binder command buffer
4009 IPCThreadState::self()->flushCommands();
4010
4011 clearOutputTracks();
4012
4013 if (exitPending()) {
4014 break;
4015 }
4016
4017 releaseWakeLock_l();
4018 // wait until we have something to do...
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00004019 ALOGV("%s going to sleep", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004020 mWaitWorkCV.wait(mLock);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00004021 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004022 acquireWakeLock_l();
4023
4024 mMixerStatus = MIXER_IDLE;
4025 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4026 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004027 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004028 checkSilentMode_l();
4029
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004030 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4031 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004032 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004033 sleepTimeShift = 0;
4034 }
4035
4036 continue;
4037 }
4038 }
Eric Laurent81784c32012-11-19 14:55:58 -08004039 // mMixerStatusIgnoringFastTracks is also updated internally
4040 mMixerStatus = prepareTracks_l(&tracksToRemove);
4041
Andy Hungdae27702016-10-31 14:01:16 -07004042 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004043
Vlad Popa7e81cea2023-01-19 16:34:16 +01004044 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004045
Eric Laurent81784c32012-11-19 14:55:58 -08004046 // prevent any changes in effect chain list and in each effect chain
4047 // during mixing and effect process as the audio buffers could be deleted
4048 // or modified if an effect is created or deleted
4049 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004050
4051 // Determine which session to pick up haptic data.
4052 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004053 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004054 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004055 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004056 for (const auto& track : mActiveTracks) {
Andy Hungbd72c542023-06-20 18:56:17 -07004057 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004058 if (effectChain != nullptr
4059 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004060 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004061 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004062 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004063 break;
4064 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004065 if (activeHapticSessionId == AUDIO_SESSION_NONE
4066 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004067 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004068 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004069 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004070 }
4071 }
4072 }
4073
Andy Hungc1646382019-04-30 16:12:10 -07004074 // Acquire a local copy of active tracks with lock (release w/o lock).
4075 //
4076 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4077 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4078 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4079 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent6f9534f2022-05-03 18:15:04 +02004080
4081 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004082
Jiabin Huangfb476842022-12-06 03:18:10 +00004083 for (const auto &track : mActiveTracks ) {
4084 track->updateTeePatches();
4085 }
4086
Eric Laurent19952e12023-04-20 10:08:29 +02004087 // signal actual start of output stream when the render position reported by the kernel
4088 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004089 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4090 && (mKernelPositionOnStandby
4091 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004092 mHalStarted = true;
4093 mWaitHalStartCV.broadcast();
4094 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004095 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004096
Eric Laurentbfb1b832013-01-07 09:53:42 -08004097 if (mBytesRemaining == 0) {
4098 mCurrentWriteLength = 0;
4099 if (mMixerStatus == MIXER_TRACKS_READY) {
4100 // threadLoop_mix() sets mCurrentWriteLength
4101 threadLoop_mix();
4102 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4103 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004104 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004105 // must be written to HAL
4106 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004107 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004108 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004109
4110 // Tally underrun frames as we are inserting 0s here.
4111 for (const auto& track : activeTracks) {
Andy Hung3ff4b552023-06-26 19:20:57 -07004112 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004113 && !track->isStopped()
4114 && !track->isPaused()
4115 && !track->isTerminated()) {
4116 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4117 __func__, track->id(), track->getTrackStateAsString(),
4118 mNormalFrameCount);
Andy Hung3ff4b552023-06-26 19:20:57 -07004119 track->audioTrackServerProxy()->tallyUnderrunFrames(
4120 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004121 }
4122 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004123 }
4124 }
Andy Hung98ef9782014-03-04 14:46:50 -08004125 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004126 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004127 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004128 // or mSinkBuffer (if there are no effects and there is no data already copied to
4129 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004130 //
4131 // This is done pre-effects computation; if effects change to
4132 // support higher precision, this needs to move.
4133 //
4134 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004135 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004136 uint32_t mixerChannelCount = mEffectBufferValid ?
4137 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004138 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004139 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4140 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4141
David Li88ee0902022-06-22 10:01:21 +08004142 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4143 // do these processes after effects are applied.
4144 if (!mEffectBufferValid) {
4145 // mono blend occurs for mixer threads only (not direct or offloaded)
4146 // and is handled here if we're going directly to the sink.
4147 if (requireMonoBlend()) {
4148 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4149 mNormalFrameCount, true /*limit*/);
4150 }
Andy Hung2ddee192015-12-18 17:34:44 -08004151
David Li88ee0902022-06-22 10:01:21 +08004152 if (!hasFastMixer()) {
4153 // Balance must take effect after mono conversion.
4154 // We do it here if there is no FastMixer.
4155 // mBalance detects zero balance within the class for speed
4156 // (not needed here).
4157 mBalance.setBalance(mMasterBalance.load());
4158 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4159 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004160 }
4161
Andy Hung98ef9782014-03-04 14:46:50 -08004162 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004163 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004164
4165 // If we're going directly to the sink and there are haptic channels,
4166 // we should adjust channels as the sample data is partially interleaved
4167 // in this case.
4168 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4169 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4170 mChannelCount + mHapticChannelCount,
4171 audio_bytes_per_sample(format),
4172 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4173 }
Andy Hung98ef9782014-03-04 14:46:50 -08004174 }
4175
Eric Laurentbfb1b832013-01-07 09:53:42 -08004176 mBytesRemaining = mCurrentWriteLength;
4177 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004178 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4179 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4180 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4181 mBytesWritten += mBytesRemaining;
4182 mFramesWritten += framesRemaining;
4183 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004184 mBytesRemaining = 0;
4185 }
Eric Laurent81784c32012-11-19 14:55:58 -08004186
Eric Laurentbfb1b832013-01-07 09:53:42 -08004187 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004188 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004189 for (size_t i = 0; i < effectChains.size(); i ++) {
4190 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004191 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004192 if (activeHapticSessionId != AUDIO_SESSION_NONE
4193 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004194 // Haptic data is active in this case, copy it directly from
4195 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004196 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4197 audio_channel_count_from_out_mask(mMixerChannelMask) :
4198 mChannelCount;
4199 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4200 hapticSessionChannelCount = mChannelCount;
4201 }
4202
jiabin47affe52019-04-04 18:02:07 -07004203 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004204 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004205 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004206 memcpy_by_audio_format(
4207 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004208 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004209 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004210 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004211 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004212 }
Eric Laurent81784c32012-11-19 14:55:58 -08004213 }
4214 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004215 // Process effect chains for offloaded thread even if no audio
4216 // was read from audio track: process only updates effect state
4217 // and thus does have to be synchronized with audio writes but may have
4218 // to be called while waiting for async write callback
4219 if (mType == OFFLOAD) {
4220 for (size_t i = 0; i < effectChains.size(); i ++) {
4221 effectChains[i]->process_l();
4222 }
4223 }
Eric Laurent81784c32012-11-19 14:55:58 -08004224
Andy Hung98ef9782014-03-04 14:46:50 -08004225 // Only if the Effects buffer is enabled and there is data in the
4226 // Effects buffer (buffer valid), we need to
4227 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004228 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004229 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004230 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004231 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004232 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004233 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004234 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004235 }
4236
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004237 if (!hasFastMixer()) {
4238 // Balance must take effect after mono conversion.
4239 // We do it here if there is no FastMixer.
4240 // mBalance detects zero balance within the class for speed (not needed here).
4241 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004242 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004243 }
4244
Eric Laurentb62d0362021-10-26 17:40:18 +02004245 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4246 // mPostSpatializerBuffer if the haptics track is spatialized.
4247 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4248 // For other thread types, the haptics channels are already in mEffectBuffer.
4249 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4250 const size_t srcBufferSize = mNormalFrameCount *
4251 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4252 mEffectBufferFormat);
4253 const size_t dstBufferSize = mNormalFrameCount
4254 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4255
4256 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4257 mEffectBufferFormat,
4258 (uint8_t*)mEffectBuffer + srcBufferSize,
4259 mEffectBufferFormat,
4260 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004261 }
Atneya Nair68436cf2022-09-19 17:51:37 -07004262 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4263 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4264 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4265 // Clamp PCM float values more than this distance from 0 to insulate
4266 // a HAL which doesn't handle NaN correctly.
4267 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4268 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4269 static_cast<const float*>(effectBuffer),
4270 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4271 } else {
4272 memcpy_by_audio_format(mSinkBuffer, mFormat,
4273 effectBuffer, mEffectBufferFormat, framesToCopy);
4274 }
jiabin245cdd92018-12-07 17:55:15 -08004275 // The sample data is partially interleaved when haptic channels exist,
4276 // we need to adjust channels here.
4277 if (mHapticChannelCount > 0) {
4278 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4279 mChannelCount + mHapticChannelCount,
4280 audio_bytes_per_sample(mFormat),
4281 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4282 }
Andy Hung98ef9782014-03-04 14:46:50 -08004283 }
4284
Eric Laurent81784c32012-11-19 14:55:58 -08004285 // enable changes in effect chain
4286 unlockEffectChains(effectChains);
4287
Vlad Popafce10862023-02-03 10:37:07 +01004288 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung2cbc2722023-07-17 17:05:00 -07004289 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004290 metadataUpdate.playbackMetadataUpdate);
4291 }
4292
Eric Laurentbfb1b832013-01-07 09:53:42 -08004293 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004294 // mSleepTimeUs == 0 means we must write to audio hardware
4295 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004296 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004297 // writePeriodNs is updated >= 0 when ret > 0.
4298 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004299 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004300 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004301 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004302 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004303 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004304 if (ret < 0) {
4305 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004306 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004307 mBytesWritten += ret;
4308 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004309 const int64_t frames = ret / mFrameSize;
4310 mFramesWritten += frames;
4311
4312 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4313 // process information relating to write time.
4314 if (audio_has_proportional_frames(mFormat)) {
4315 // we are in a continuous mixing cycle
4316 if (mMixerStatus == MIXER_TRACKS_READY &&
4317 loopCount == lastLoopCountWritten + 1) {
4318
4319 const double jitterMs =
4320 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4321 {frames, writePeriodNs},
4322 {0, 0} /* lastTimestamp */, mSampleRate);
4323 const double processMs =
4324 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4325
4326 Mutex::Autolock _l(mLock);
4327 mIoJitterMs.add(jitterMs);
4328 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004329
4330 if (mPipeSink.get() != nullptr) {
4331 // Using the Monopipe availableToWrite, we estimate the current
4332 // buffer size.
4333 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4334 const ssize_t
4335 availableToWrite = mPipeSink->availableToWrite();
4336 const size_t pipeFrames = monoPipe->maxFrames();
4337 const size_t
4338 remainingFrames = pipeFrames - max(availableToWrite, 0);
4339 mMonopipePipeDepthStats.add(remainingFrames);
4340 }
Andy Hung446f4df2019-02-21 12:26:41 -08004341 }
4342
4343 // write blocked detection
4344 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004345 if ((mType == MIXER || mType == SPATIALIZER)
4346 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004347 mNumDelayedWrites++;
4348 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4349 ATRACE_NAME("underrun");
4350 ALOGW("write blocked for %lld msecs, "
4351 "%d delayed writes, thread %d",
4352 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4353 mNumDelayedWrites, mId);
4354 lastWarning = lastIoEndNs;
4355 }
4356 }
4357 }
4358 // update timing info.
4359 mLastIoBeginNs = lastIoBeginNs;
4360 mLastIoEndNs = lastIoEndNs;
4361 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004362 }
4363 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4364 (mMixerStatus == MIXER_DRAIN_ALL)) {
4365 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004366 }
Andy Hungd3639922022-04-28 18:00:49 -07004367 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004368
4369 if (mThreadThrottle
4370 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004371 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004372 // Limit MixerThread data processing to no more than twice the
4373 // expected processing rate.
4374 //
4375 // This helps prevent underruns with NuPlayer and other applications
4376 // which may set up buffers that are close to the minimum size, or use
4377 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4378 //
4379 // The throttle smooths out sudden large data drains from the device,
4380 // e.g. when it comes out of standby, which often causes problems with
4381 // (1) mixer threads without a fast mixer (which has its own warm-up)
4382 // (2) minimum buffer sized tracks (even if the track is full,
4383 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004384 //
4385 // Total time spent in last processing cycle equals time spent in
4386 // 1. threadLoop_write, as well as time spent in
4387 // 2. threadLoop_mix (significant for heavy mixing, especially
4388 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004389
Andy Hung446f4df2019-02-21 12:26:41 -08004390 // it's OK if deltaMs is an overestimate.
4391
4392 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004393
Ivan Lozanoea04d392017-11-07 14:37:07 -08004394 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004395 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004396 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004397
Andy Hung08fb1742015-05-31 23:22:10 -07004398 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004399 // notify of throttle start on verbose log
4400 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4401 "mixer(%p) throttle begin:"
4402 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004403 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004404 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004405 // Throttle must be attributed to the previous mixer loop's write time
4406 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004407 // This also ensures proper timing statistics.
4408 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004409 } else {
4410 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4411 if (diff > 0) {
4412 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004413 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004414 ALOGD_IF(!isSingleDeviceType(
4415 outDeviceTypes(), audio_is_a2dp_out_device) &&
4416 !isSingleDeviceType(
4417 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004418 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004419 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4420 }
Andy Hung08fb1742015-05-31 23:22:10 -07004421 }
4422 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004423 }
Eric Laurent81784c32012-11-19 14:55:58 -08004424
Eric Laurentbfb1b832013-01-07 09:53:42 -08004425 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004426 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004427 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004428 // suspended requires accurate metering of sleep time.
4429 if (isSuspended()) {
4430 // advance by expected sleepTime
4431 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4432 const nsecs_t nowNs = systemTime();
4433
4434 // compute expected next time vs current time.
4435 // (negative deltas are treated as delays).
4436 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4437 if (deltaNs < -kMaxNextBufferDelayNs) {
4438 // Delays longer than the max allowed trigger a reset.
4439 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4440 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4441 timeLoopNextNs = nowNs + deltaNs;
4442 } else if (deltaNs < 0) {
4443 // Delays within the max delay allowed: zero the delta/sleepTime
4444 // to help the system catch up in the next iteration(s)
4445 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4446 deltaNs = 0;
4447 }
4448 // update sleep time (which is >= 0)
4449 mSleepTimeUs = deltaNs / 1000;
4450 }
Eric Laurente93cc032016-05-05 10:15:10 -07004451 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4452 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004453 }
Glenn Kastene7754022014-10-31 12:11:26 -07004454 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004455 }
Eric Laurent81784c32012-11-19 14:55:58 -08004456 }
4457
4458 // Finally let go of removed track(s), without the lock held
4459 // since we can't guarantee the destructors won't acquire that
4460 // same lock. This will also mutate and push a new fast mixer state.
4461 threadLoop_removeTracks(tracksToRemove);
4462 tracksToRemove.clear();
4463
4464 // FIXME I don't understand the need for this here;
4465 // it was in the original code but maybe the
4466 // assignment in saveOutputTracks() makes this unnecessary?
4467 clearOutputTracks();
4468
4469 // Effect chains will be actually deleted here if they were removed from
4470 // mEffectChains list during mixing or effects processing
4471 effectChains.clear();
4472
4473 // FIXME Note that the above .clear() is no longer necessary since effectChains
4474 // is now local to this block, but will keep it for now (at least until merge done).
4475 }
4476
Eric Laurentbfb1b832013-01-07 09:53:42 -08004477 threadLoop_exit();
4478
Eric Laurentcf817a22014-08-04 20:36:31 -07004479 if (!mStandby) {
4480 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004481 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004482 }
4483
4484 releaseWakeLock();
4485
4486 ALOGV("Thread %p type %d exiting", this, mType);
4487 return false;
4488}
4489
Andy Hung71742ab2023-07-07 13:47:37 -07004490void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004491{
Dean Wheatley12473e92021-03-18 23:00:55 +11004492 if (mStandby) {
4493 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4494 return;
4495 } else if (mHwPaused) {
4496 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4497 return;
4498 }
4499
4500 // Gather the framesReleased counters for all active tracks,
4501 // and associate with the sink frames written out. We need
4502 // this to convert the sink timestamp to the track timestamp.
4503 bool kernelLocationUpdate = false;
4504 ExtendedTimestamp timestamp; // use private copy to fetch
4505
4506 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4507 // HAL may be draining some small duration buffered data for fade out.
4508 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4509 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4510 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4511 mSampleRate);
4512
4513 if (isTimestampCorrectionEnabled()) {
4514 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4515 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4516 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4517 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4518 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4519 = correctedTimestamp.mFrames;
4520 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4521 = correctedTimestamp.mTimeNs;
4522 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4523 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4524 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4525
4526 // Note: Downstream latency only added if timestamp correction enabled.
4527 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4528 const int64_t newPosition =
4529 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4530 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4531 // prevent retrograde
4532 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4533 newPosition,
4534 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4535 - mSuspendedFrames));
4536 }
4537 }
4538
4539 // We always fetch the timestamp here because often the downstream
4540 // sink will block while writing.
4541
4542 // We keep track of the last valid kernel position in case we are in underrun
4543 // and the normal mixer period is the same as the fast mixer period, or there
4544 // is some error from the HAL.
4545 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4546 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4547 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4548 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4549 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4550
4551 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4552 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4553 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4554 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4555 }
4556
4557 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4558 kernelLocationUpdate = true;
4559 } else {
4560 ALOGVV("getTimestamp error - no valid kernel position");
4561 }
4562
4563 // copy over kernel info
4564 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4565 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4566 + mSuspendedFrames; // add frames discarded when suspended
4567 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4568 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4569 } else {
4570 mTimestampVerifier.error();
4571 }
4572
4573 // mFramesWritten for non-offloaded tracks are contiguous
4574 // even after standby() is called. This is useful for the track frame
4575 // to sink frame mapping.
4576 bool serverLocationUpdate = false;
4577 if (mFramesWritten != mLastFramesWritten) {
4578 serverLocationUpdate = true;
4579 mLastFramesWritten = mFramesWritten;
4580 }
4581 // Only update timestamps if there is a meaningful change.
4582 // Either the kernel timestamp must be valid or we have written something.
4583 if (kernelLocationUpdate || serverLocationUpdate) {
4584 if (serverLocationUpdate) {
4585 // use the time before we called the HAL write - it is a bit more accurate
4586 // to when the server last read data than the current time here.
4587 //
4588 // If we haven't written anything, mLastIoBeginNs will be -1
4589 // and we use systemTime().
4590 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4591 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4592 ? systemTime() : mLastIoBeginNs;
4593 }
4594
Andy Hung3ff4b552023-06-26 19:20:57 -07004595 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004596 if (!t->isFastTrack()) {
4597 t->updateTrackFrameInfo(
Andy Hung3ff4b552023-06-26 19:20:57 -07004598 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004599 mFramesWritten,
4600 mSampleRate,
4601 mTimestamp);
4602 }
4603 }
4604 }
4605
4606 if (audio_has_proportional_frames(mFormat)) {
4607 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4608 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4609 mLatencyMs.add(latencyMs);
4610 }
4611 }
4612#if 0
4613 // logFormat example
4614 if (z % 100 == 0) {
4615 timespec ts;
4616 clock_gettime(CLOCK_MONOTONIC, &ts);
4617 LOGT("This is an integer %d, this is a float %f, this is my "
4618 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4619 LOGT("A deceptive null-terminated string %\0");
4620 }
4621 ++z;
4622#endif
4623}
4624
Eric Laurentbfb1b832013-01-07 09:53:42 -08004625// removeTracks_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07004626void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hung71ba4b32022-10-06 12:09:49 -07004627NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurentbfb1b832013-01-07 09:53:42 -08004628{
Andy Hungfe726a62018-09-27 15:17:25 -07004629 for (const auto& track : tracksToRemove) {
4630 mActiveTracks.remove(track);
4631 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hungbd72c542023-06-20 18:56:17 -07004632 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004633 if (chain != 0) {
4634 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4635 __func__, track->id(), chain.get(), track->sessionId());
4636 chain->decActiveTrackCnt();
4637 }
4638 // If an external client track, inform APM we're no longer active, and remove if needed.
4639 // We do this under lock so that the state is consistent if the Track is destroyed.
4640 if (track->isExternalTrack()) {
4641 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004642 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004643 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004644 }
4645 }
Andy Hungfe726a62018-09-27 15:17:25 -07004646 if (track->isTerminated()) {
4647 // remove from our tracks vector
4648 removeTrack_l(track);
4649 }
jiabineb3bda02020-06-30 14:07:03 -07004650 if (mHapticChannelCount > 0 &&
4651 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4652 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004653 mLock.unlock();
4654 // Unlock due to VibratorService will lock for this call and will
4655 // call Tracks.mute/unmute which also require thread's lock.
4656 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4657 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004658
4659 // When the track is stop, set the haptic intensity as MUTE
4660 // for the HapticGenerator effect.
4661 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004662 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004663 }
jiabin245cdd92018-12-07 17:55:15 -08004664 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004665 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004666}
Eric Laurent81784c32012-11-19 14:55:58 -08004667
Andy Hung71742ab2023-07-07 13:47:37 -07004668status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004669{
4670 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004671 ExtendedTimestamp ets;
4672 status_t status = mNormalSink->getTimestamp(ets);
4673 if (status == NO_ERROR) {
4674 status = ets.getBestTimestamp(&timestamp);
4675 }
4676 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004677 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004678 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004679 collectTimestamps_l();
4680 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4681 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004682 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004683 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4684 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4685 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4686 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4687 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004688 }
4689 return INVALID_OPERATION;
4690}
Eric Laurent1c333e22014-05-20 10:48:17 -07004691
Eric Laurenteab90452019-06-24 15:17:46 -07004692// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4693// still applied by the mixer.
4694// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4695// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4696// if more than one track are active
Andy Hung71742ab2023-07-07 13:47:37 -07004697status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004698{
4699 status_t result = NO_ERROR;
4700 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4701 if (*volume != mLeftVolFloat) {
4702 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004703 // HAL can return INVALID_OPERATION if operation is not supported.
4704 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004705 "Error when setting output stream volume: %d", result);
4706 if (result == NO_ERROR) {
4707 mLeftVolFloat = *volume;
4708 }
4709 }
4710 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4711 // remove stream volume contribution from software volume.
4712 if (mLeftVolFloat == *volume) {
4713 *volume = 1.0f;
4714 }
4715 }
4716 return result;
4717}
4718
Andy Hung71742ab2023-07-07 13:47:37 -07004719status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004720 audio_patch_handle_t *handle)
4721{
Andy Hungf60abce2016-08-26 11:37:54 -07004722 status_t status;
4723 if (property_get_bool("af.patch_park", false /* default_value */)) {
4724 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4725 // or if HAL does not properly lock against access.
4726 AutoPark<FastMixer> park(mFastMixer);
4727 status = PlaybackThread::createAudioPatch_l(patch, handle);
4728 } else {
4729 status = PlaybackThread::createAudioPatch_l(patch, handle);
4730 }
Eric Laurentb0463942022-12-20 16:31:10 +01004731
4732 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004733 return status;
4734}
4735
Andy Hung71742ab2023-07-07 13:47:37 -07004736status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004737 audio_patch_handle_t *handle)
4738{
4739 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004740
4741 // store new device and send to effects
4742 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004743 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004744 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004745 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4746 && !mOutput->audioHwDev->supportsAudioPatches(),
4747 "Enumerated device type(%#x) must not be used "
4748 "as it does not support audio patches",
4749 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004750 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung71ba4b32022-10-06 12:09:49 -07004751 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4752 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004753 }
4754
François Gaffie0c280aa2018-07-25 10:02:15 +02004755 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004756#ifdef ADD_BATTERY_DATA
4757 // when changing the audio output device, call addBatteryData to notify
4758 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004759 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004760 uint32_t params = 0;
4761 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004762 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004763 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004764 }
4765
Eric Laurent054d9d32015-04-24 08:48:48 -07004766 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004767 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004768 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4769 }
4770
4771 if (params != 0) {
4772 addBatteryData(params);
4773 }
4774 }
4775#endif
4776
4777 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004778 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004779 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004780
jiabinc52b1ff2019-10-31 17:20:42 -07004781 // mPatch.num_sinks is not set when the thread is created so that
4782 // the first patch creation triggers an ioConfigChanged callback
4783 bool configChanged = (mPatch.num_sinks == 0) ||
4784 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004785 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004786 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004787 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004788
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004789 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004790 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4791 status = hwDevice->createAudioPatch(patch->num_sources,
4792 patch->sources,
4793 patch->num_sinks,
4794 patch->sinks,
4795 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004796 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004797 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004798 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004799 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004800 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004801
4802 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004803 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004804 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004805 // also dispatch to active AudioTracks for MediaMetrics
4806 for (const auto &track : mActiveTracks) {
4807 track->logEndInterval();
4808 track->logBeginInterval(patchSinksAsString);
4809 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004810
Eric Laurente8726fe2015-06-26 09:39:24 -07004811 if (configChanged) {
4812 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4813 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004814 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004815 mActiveTracks.setHasChanged();
4816
Eric Laurent1c333e22014-05-20 10:48:17 -07004817 return status;
4818}
4819
Andy Hung71742ab2023-07-07 13:47:37 -07004820status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004821{
Andy Hungf60abce2016-08-26 11:37:54 -07004822 status_t status;
4823 if (property_get_bool("af.patch_park", false /* default_value */)) {
4824 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4825 // or if HAL does not properly lock against access.
4826 AutoPark<FastMixer> park(mFastMixer);
4827 status = PlaybackThread::releaseAudioPatch_l(handle);
4828 } else {
4829 status = PlaybackThread::releaseAudioPatch_l(handle);
4830 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004831 return status;
4832}
4833
Andy Hung71742ab2023-07-07 13:47:37 -07004834status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004835{
4836 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004837
jiabinc52b1ff2019-10-31 17:20:42 -07004838 mPatch = audio_patch{};
4839 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004840
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004841 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004842 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4843 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004844 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004845 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004846 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004847 // Force meteadata update after a route change
4848 mActiveTracks.setHasChanged();
4849
Eric Laurent1c333e22014-05-20 10:48:17 -07004850 return status;
4851}
4852
Andy Hung71742ab2023-07-07 13:47:37 -07004853void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004854{
4855 Mutex::Autolock _l(mLock);
4856 mTracks.add(track);
4857}
4858
Andy Hung71742ab2023-07-07 13:47:37 -07004859void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004860{
4861 Mutex::Autolock _l(mLock);
4862 destroyTrack_l(track);
4863}
4864
Andy Hung71742ab2023-07-07 13:47:37 -07004865void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07004866{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004867 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004868 config->role = AUDIO_PORT_ROLE_SOURCE;
4869 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4870 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004871 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4872 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4873 config->flags.output = mOutput->flags;
4874 }
Eric Laurent83b88082014-06-20 18:31:16 -07004875}
4876
Eric Laurent81784c32012-11-19 14:55:58 -08004877// ----------------------------------------------------------------------------
4878
Andy Hung71742ab2023-07-07 13:47:37 -07004879/* static */
4880sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07004881 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hung71742ab2023-07-07 13:47:37 -07004882 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung2cbc2722023-07-17 17:05:00 -07004883 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hung71742ab2023-07-07 13:47:37 -07004884}
4885
Andy Hung2cbc2722023-07-17 17:05:00 -07004886MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004887 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung2cbc2722023-07-17 17:05:00 -07004888 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004889 // mAudioMixer below
4890 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01004891 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004892 mFastMixerFutex(0),
4893 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004894 // mOutputSink below
4895 // mPipeSink below
4896 // mNormalSink below
4897{
Andy Hung2cbc2722023-07-17 17:05:00 -07004898 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004899 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004900 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004901 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004902 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4903 mNormalFrameCount);
4904 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4905
Andy Hungfbfc3952015-01-15 13:33:51 -08004906 if (type == DUPLICATING) {
4907 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4908 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4909 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4910 return;
4911 }
Eric Laurent81784c32012-11-19 14:55:58 -08004912 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004913 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004914 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004915 const NBAIO_Format offers[1] = {Format_from_SR_C(
4916 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004917#if !LOG_NDEBUG
4918 ssize_t index =
4919#else
4920 (void)
4921#endif
4922 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004923 ALOG_ASSERT(index == 0);
4924
4925 // initialize fast mixer depending on configuration
4926 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00004927 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08004928 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004929 } else {
4930 switch (kUseFastMixer) {
4931 case FastMixer_Never:
4932 initFastMixer = false;
4933 break;
4934 case FastMixer_Always:
4935 initFastMixer = true;
4936 break;
4937 case FastMixer_Static:
4938 case FastMixer_Dynamic:
4939 initFastMixer = mFrameCount < mNormalFrameCount;
4940 break;
4941 }
4942 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4943 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4944 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004945 }
4946 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004947 audio_format_t fastMixerFormat;
4948 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4949 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4950 } else {
4951 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4952 }
4953 if (mFormat != fastMixerFormat) {
4954 // change our Sink format to accept our intermediate precision
4955 mFormat = fastMixerFormat;
4956 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004957 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004958 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4959 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4960 }
Eric Laurent81784c32012-11-19 14:55:58 -08004961
4962 // create a MonoPipe to connect our submix to FastMixer
4963 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004964
Andy Hung1258c1a2014-05-23 21:22:17 -07004965 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004966 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004967 format.mFormat = fastMixerFormat;
4968 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4969
Eric Laurent81784c32012-11-19 14:55:58 -08004970 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4971 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4972 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4973 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung71ba4b32022-10-06 12:09:49 -07004974 const NBAIO_Format offersFast[1] = {format};
4975 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004976#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02004977 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004978#else
4979 (void)
4980#endif
Andy Hung71ba4b32022-10-06 12:09:49 -07004981 monoPipe->negotiate(offersFast, std::size(offersFast),
4982 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08004983 ALOG_ASSERT(index == 0);
4984 monoPipe->setAvgFrames((mScreenState & 1) ?
4985 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4986 mPipeSink = monoPipe;
4987
Eric Laurent81784c32012-11-19 14:55:58 -08004988 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004989 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004990 FastMixerStateQueue *sq = mFastMixer->sq();
4991#ifdef STATE_QUEUE_DUMP
4992 sq->setObserverDump(&mStateQueueObserverDump);
4993 sq->setMutatorDump(&mStateQueueMutatorDump);
4994#endif
4995 FastMixerState *state = sq->begin();
4996 FastTrack *fastTrack = &state->mFastTracks[0];
4997 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4998 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4999 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005000 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5001 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5002 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005003 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005004 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07005005 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01005006 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005007 fastTrack->mGeneration++;
5008 state->mFastTracksGen++;
5009 state->mTrackMask = 1;
5010 // fast mixer will use the HAL output sink
5011 state->mOutputSink = mOutputSink.get();
5012 state->mOutputSinkGen++;
5013 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005014 // specify sink channel mask when haptic channel mask present as it can not
5015 // be calculated directly from channel count
5016 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005017 ? AUDIO_CHANNEL_NONE
5018 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005019 state->mCommand = FastMixerState::COLD_IDLE;
5020 // already done in constructor initialization list
5021 //mFastMixerFutex = 0;
5022 state->mColdFutexAddr = &mFastMixerFutex;
5023 state->mColdGen++;
5024 state->mDumpState = &mFastMixerDumpState;
Andy Hung2cbc2722023-07-17 17:05:00 -07005025 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005026 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005027 sq->end();
5028 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5029
Eric Tan0513b5d2018-09-17 10:32:48 -07005030 NBLog::thread_info_t info;
5031 info.id = mId;
5032 info.type = NBLog::FASTMIXER;
5033 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5034
Eric Laurent81784c32012-11-19 14:55:58 -08005035 // start the fast mixer
5036 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5037 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005038 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005039 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005040
5041#ifdef AUDIO_WATCHDOG
5042 // create and start the watchdog
5043 mAudioWatchdog = new AudioWatchdog();
5044 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5045 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5046 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005047 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005048#endif
Andy Hung8946a282018-04-19 20:04:56 -07005049 } else {
5050#ifdef TEE_SINK
5051 // Only use the MixerThread tee if there is no FastMixer.
5052 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5053 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5054#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005055 }
5056
5057 switch (kUseFastMixer) {
5058 case FastMixer_Never:
5059 case FastMixer_Dynamic:
5060 mNormalSink = mOutputSink;
5061 break;
5062 case FastMixer_Always:
5063 mNormalSink = mPipeSink;
5064 break;
5065 case FastMixer_Static:
5066 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5067 break;
5068 }
5069}
5070
Andy Hung71742ab2023-07-07 13:47:37 -07005071MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005072{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005073 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005074 FastMixerStateQueue *sq = mFastMixer->sq();
5075 FastMixerState *state = sq->begin();
5076 if (state->mCommand == FastMixerState::COLD_IDLE) {
5077 int32_t old = android_atomic_inc(&mFastMixerFutex);
5078 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005079 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005080 }
5081 }
5082 state->mCommand = FastMixerState::EXIT;
5083 sq->end();
5084 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5085 mFastMixer->join();
5086 // Though the fast mixer thread has exited, it's state queue is still valid.
5087 // We'll use that extract the final state which contains one remaining fast track
5088 // corresponding to our sub-mix.
5089 state = sq->begin();
5090 ALOG_ASSERT(state->mTrackMask == 1);
5091 FastTrack *fastTrack = &state->mFastTracks[0];
5092 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5093 delete fastTrack->mBufferProvider;
5094 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005095 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005096#ifdef AUDIO_WATCHDOG
5097 if (mAudioWatchdog != 0) {
5098 mAudioWatchdog->requestExit();
5099 mAudioWatchdog->requestExitAndWait();
5100 mAudioWatchdog.clear();
5101 }
5102#endif
5103 }
Andy Hung2cbc2722023-07-17 17:05:00 -07005104 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005105 delete mAudioMixer;
5106}
5107
Andy Hung71742ab2023-07-07 13:47:37 -07005108void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005109 PlaybackThread::onFirstRef();
5110
5111 Mutex::Autolock _l(mLock);
5112 if (mOutput != nullptr && mOutput->stream != nullptr) {
5113 status_t status = mOutput->stream->setLatencyModeCallback(this);
5114 if (status != INVALID_OPERATION) {
5115 updateHalSupportedLatencyModes_l();
5116 }
5117 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5118 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5119 mBluetoothLatencyModesEnabled.store(
5120 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5121 }
5122}
Eric Laurent81784c32012-11-19 14:55:58 -08005123
Andy Hung71742ab2023-07-07 13:47:37 -07005124uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005125{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005126 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005127 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5128 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5129 }
5130 return latency;
5131}
5132
Andy Hung71742ab2023-07-07 13:47:37 -07005133ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005134{
5135 // FIXME we should only do one push per cycle; confirm this is true
5136 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005137 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005138 FastMixerStateQueue *sq = mFastMixer->sq();
5139 FastMixerState *state = sq->begin();
5140 if (state->mCommand != FastMixerState::MIX_WRITE &&
5141 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5142 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005143
5144 // FIXME workaround for first HAL write being CPU bound on some devices
5145 ATRACE_BEGIN("write");
5146 mOutput->write((char *)mSinkBuffer, 0);
5147 ATRACE_END();
5148
Eric Laurent81784c32012-11-19 14:55:58 -08005149 int32_t old = android_atomic_inc(&mFastMixerFutex);
5150 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005151 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005152 }
5153#ifdef AUDIO_WATCHDOG
5154 if (mAudioWatchdog != 0) {
5155 mAudioWatchdog->resume();
5156 }
5157#endif
5158 }
5159 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005160#ifdef FAST_THREAD_STATISTICS
Andy Hung2cbc2722023-07-17 17:05:00 -07005161 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005162 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005163#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005164 sq->end();
5165 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5166 if (kUseFastMixer == FastMixer_Dynamic) {
5167 mNormalSink = mPipeSink;
5168 }
5169 } else {
5170 sq->end(false /*didModify*/);
5171 }
5172 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005173 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005174}
5175
Andy Hung71742ab2023-07-07 13:47:37 -07005176void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005177{
5178 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005179 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005180 FastMixerStateQueue *sq = mFastMixer->sq();
5181 FastMixerState *state = sq->begin();
5182 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005183 // Report any frames trapped in the Monopipe
5184 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5185 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5186 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5187 "monoPipeWritten:%lld monoPipeLeft:%lld",
5188 (long long)mFramesWritten, (long long)mSuspendedFrames,
5189 (long long)mPipeSink->framesWritten(), pipeFrames);
5190 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5191
Eric Laurent81784c32012-11-19 14:55:58 -08005192 state->mCommand = FastMixerState::COLD_IDLE;
5193 state->mColdFutexAddr = &mFastMixerFutex;
5194 state->mColdGen++;
5195 mFastMixerFutex = 0;
5196 sq->end();
5197 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5198 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5199 if (kUseFastMixer == FastMixer_Dynamic) {
5200 mNormalSink = mOutputSink;
5201 }
5202#ifdef AUDIO_WATCHDOG
5203 if (mAudioWatchdog != 0) {
5204 mAudioWatchdog->pause();
5205 }
5206#endif
5207 } else {
5208 sq->end(false /*didModify*/);
5209 }
5210 }
5211 PlaybackThread::threadLoop_standby();
5212}
5213
Andy Hung71742ab2023-07-07 13:47:37 -07005214bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005215{
5216 return false;
5217}
5218
Andy Hung71742ab2023-07-07 13:47:37 -07005219bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005220{
5221 return !mStandby;
5222}
5223
Andy Hung71742ab2023-07-07 13:47:37 -07005224bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005225{
5226 Mutex::Autolock _l(mLock);
5227 return waitingAsyncCallback_l();
5228}
5229
Eric Laurent81784c32012-11-19 14:55:58 -08005230// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung71742ab2023-07-07 13:47:37 -07005231void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005232{
5233 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005234 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005235 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005236 // discard any pending drain or write ack by incrementing sequence
5237 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5238 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005239 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005240 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5241 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005242 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005243 mHwPaused = false;
Eric Laurent6f9534f2022-05-03 18:15:04 +02005244 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005245}
5246
Andy Hung71742ab2023-07-07 13:47:37 -07005247void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005248{
5249 ALOGV("signal playback thread");
5250 broadcast_l();
5251}
5252
Andy Hung71742ab2023-07-07 13:47:37 -07005253void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005254{
5255 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5256 invalidateTracks((audio_stream_type_t)i);
5257 }
5258}
5259
Andy Hung71742ab2023-07-07 13:47:37 -07005260void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005261{
Eric Laurent81784c32012-11-19 14:55:58 -08005262 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005263 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005264 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005265 // increase sleep time progressively when application underrun condition clears.
5266 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5267 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5268 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005269 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005270 sleepTimeShift--;
5271 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005272 mSleepTimeUs = 0;
5273 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005274 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005275
Eric Laurent81784c32012-11-19 14:55:58 -08005276}
5277
Andy Hung71742ab2023-07-07 13:47:37 -07005278void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005279{
5280 // If no tracks are ready, sleep once for the duration of an output
5281 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005282 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005283 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005284 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5285 // Using the Monopipe availableToWrite, we estimate the
5286 // sleep time to retry for more data (before we underrun).
5287 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5288 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5289 const size_t pipeFrames = monoPipe->maxFrames();
5290 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5291 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5292 const size_t framesDelay = std::min(
5293 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5294 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5295 pipeFrames, framesLeft, framesDelay);
5296 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5297 } else {
5298 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5299 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5300 mSleepTimeUs = kMinThreadSleepTimeUs;
5301 }
5302 // reduce sleep time in case of consecutive application underruns to avoid
5303 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5304 // duration we would end up writing less data than needed by the audio HAL if
5305 // the condition persists.
5306 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5307 sleepTimeShift++;
5308 }
Eric Laurent81784c32012-11-19 14:55:58 -08005309 }
5310 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005311 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005312 }
5313 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005314 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5315 // before effects processing or output.
5316 if (mMixerBufferValid) {
5317 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005318 if (mType == SPATIALIZER) {
5319 memset(mSinkBuffer, 0, mSinkBufferSize);
5320 }
Andy Hung98ef9782014-03-04 14:46:50 -08005321 } else {
5322 memset(mSinkBuffer, 0, mSinkBufferSize);
5323 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005324 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005325 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5326 "anticipated start");
5327 }
5328 // TODO add standby time extension fct of effect tail
5329}
5330
5331// prepareTracks_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07005332PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07005333 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005334{
Andy Hungc0691382018-09-12 18:01:57 -07005335 // clean up deleted track ids in AudioMixer before allocating new tracks
5336 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5337 // for each trackId, destroy it in the AudioMixer
5338 if (mAudioMixer->exists(trackId)) {
5339 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005340 }
5341 });
Andy Hungc0691382018-09-12 18:01:57 -07005342 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005343
5344 mixer_state mixerStatus = MIXER_IDLE;
5345 // find out which tracks need to be processed
5346 size_t count = mActiveTracks.size();
5347 size_t mixedTracks = 0;
5348 size_t tracksWithEffect = 0;
5349 // counts only _active_ fast tracks
5350 size_t fastTracks = 0;
5351 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5352
5353 float masterVolume = mMasterVolume;
5354 bool masterMute = mMasterMute;
5355
5356 if (masterMute) {
5357 masterVolume = 0;
5358 }
5359 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hungbd72c542023-06-20 18:56:17 -07005360 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005361 if (chain != 0) {
5362 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5363 chain->setVolume_l(&v, &v);
5364 masterVolume = (float)((v + (1 << 23)) >> 24);
5365 chain.clear();
5366 }
5367
5368 // prepare a new state to push
5369 FastMixerStateQueue *sq = NULL;
5370 FastMixerState *state = NULL;
5371 bool didModify = false;
5372 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005373 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005374 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005375 sq = mFastMixer->sq();
5376 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005377 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005378 }
5379
Andy Hung69aed5f2014-02-25 17:24:40 -08005380 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005381 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005382
Andy Hungbd3b2b02018-05-21 10:53:11 -07005383 // DeferredOperations handles statistics after setting mixerStatus.
5384 class DeferredOperations {
5385 public:
Andy Hungea840382020-05-05 21:50:17 -07005386 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5387 : mMixerStatus(mixerStatus)
5388 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005389
5390 // when leaving scope, tally frames properly.
5391 ~DeferredOperations() {
5392 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5393 // because that is when the underrun occurs.
5394 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005395 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005396 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005397 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005398 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005399 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005400 }
5401 }
Andy Hungea840382020-05-05 21:50:17 -07005402 // send the max underrun frames for this mixer period
5403 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005404 }
5405
5406 // tallyUnderrunFrames() is called to update the track counters
5407 // with the number of underrun frames for a particular mixer period.
5408 // We defer tallying until we know the final mixer status.
Andy Hung3ff4b552023-06-26 19:20:57 -07005409 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005410 mUnderrunFrames.emplace_back(track, underrunFrames);
5411 }
5412
5413 private:
5414 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005415 ThreadMetrics * const mThreadMetrics;
Andy Hung3ff4b552023-06-26 19:20:57 -07005416 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005417 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005418 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005419
jiabin245cdd92018-12-07 17:55:15 -08005420 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005421 for (size_t i=0 ; i<count ; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005422 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005423
5424 // this const just means the local variable doesn't change
Andy Hung3ff4b552023-06-26 19:20:57 -07005425 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005426
5427 // process fast tracks
5428 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005429 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5430 "%s(%d): FastTrack(%d) present without FastMixer",
5431 __func__, id(), track->id());
5432
jiabin245cdd92018-12-07 17:55:15 -08005433 if (track->getHapticPlaybackEnabled()) {
5434 noFastHapticTrack = false;
5435 }
Eric Laurent81784c32012-11-19 14:55:58 -08005436
5437 // It's theoretically possible (though unlikely) for a fast track to be created
5438 // and then removed within the same normal mix cycle. This is not a problem, as
5439 // the track never becomes active so it's fast mixer slot is never touched.
5440 // The converse, of removing an (active) track and then creating a new track
5441 // at the identical fast mixer slot within the same normal mix cycle,
5442 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung3ff4b552023-06-26 19:20:57 -07005443 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005444 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005445 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5446 FastTrack *fastTrack = &state->mFastTracks[j];
5447
5448 // Determine whether the track is currently in underrun condition,
5449 // and whether it had a recent underrun.
5450 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5451 FastTrackUnderruns underruns = ftDump->mUnderruns;
5452 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung3ff4b552023-06-26 19:20:57 -07005453 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005454 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung3ff4b552023-06-26 19:20:57 -07005455 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005456 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung3ff4b552023-06-26 19:20:57 -07005457 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005458 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung3ff4b552023-06-26 19:20:57 -07005459 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005460 // don't count underruns that occur while stopping or pausing
5461 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005462 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005463 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5464 recentUnderruns > 0) {
5465 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005466 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005467 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005468 // Immediately account for FastTrack underruns.
Andy Hung3ff4b552023-06-26 19:20:57 -07005469 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005470
5471 // This is similar to the state machine for normal tracks,
5472 // with a few modifications for fast tracks.
5473 bool isActive = true;
Andy Hung3ff4b552023-06-26 19:20:57 -07005474 switch (track->state()) {
5475 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005476 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005477 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005478 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005479 }
5480 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005481 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005482 // ramp down is not yet implemented
5483 track->setPaused();
5484 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005485 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005486 // ramp up is not yet implemented
Andy Hung3ff4b552023-06-26 19:20:57 -07005487 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005488 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005489 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005490 if (recentFull > 0 || recentPartial > 0) {
5491 // track has provided at least some frames recently: reset retry count
Andy Hung3ff4b552023-06-26 19:20:57 -07005492 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005493 }
5494 if (recentUnderruns == 0) {
5495 // no recent underruns: stay active
5496 break;
5497 }
5498 // there has recently been an underrun of some kind
5499 if (track->sharedBuffer() == 0) {
5500 // were any of the recent underruns "empty" (no frames available)?
5501 if (recentEmpty == 0) {
5502 // no, then ignore the partial underruns as they are allowed indefinitely
5503 break;
5504 }
5505 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung3ff4b552023-06-26 19:20:57 -07005506 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005507 break;
5508 }
5509 // indicate to client process that the track was disabled because of underrun;
5510 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005511 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005512 // remove from active list, but state remains ACTIVE [confusing but true]
5513 isActive = false;
5514 break;
5515 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005516 FALLTHROUGH_INTENDED;
Andy Hung3ff4b552023-06-26 19:20:57 -07005517 case IAfTrackBase::STOPPING_2:
5518 case IAfTrackBase::PAUSED:
5519 case IAfTrackBase::STOPPED:
5520 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005521 // Check for presentation complete if track is inactive
5522 // We have consumed all the buffers of this track.
5523 // This would be incomplete if we auto-paused on underrun
5524 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005525 uint32_t latency = 0;
5526 status_t result = mOutput->stream->getLatency(&latency);
5527 ALOGE_IF(result != OK,
5528 "Error when retrieving output stream latency: %d", result);
5529 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005530 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005531 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5532 // track stays in active list until presentation is complete
5533 break;
5534 }
5535 }
5536 if (track->isStopping_2()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005537 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005538 }
5539 if (track->isStopped()) {
5540 // Can't reset directly, as fast mixer is still polling this track
5541 // track->reset();
5542 // So instead mark this track as needing to be reset after push with ack
5543 resetMask |= 1 << i;
5544 }
5545 isActive = false;
5546 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005547 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005548 default:
Andy Hung3ff4b552023-06-26 19:20:57 -07005549 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005550 }
5551
5552 if (isActive) {
5553 // was it previously inactive?
5554 if (!(state->mTrackMask & (1 << j))) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005555 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5556 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005557 fastTrack->mBufferProvider = eabp;
5558 fastTrack->mVolumeProvider = vp;
Andy Hung3ff4b552023-06-26 19:20:57 -07005559 fastTrack->mChannelMask = track->channelMask();
5560 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005561 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005562 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005563 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005564 fastTrack->mGeneration++;
5565 state->mTrackMask |= 1 << j;
5566 didModify = true;
5567 // no acknowledgement required for newly active tracks
5568 }
Andy Hung3ff4b552023-06-26 19:20:57 -07005569 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005570 float volume;
5571 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5572 volume = 0.f;
5573 } else {
5574 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5575 }
5576
5577 handleVoipVolume_l(&volume);
5578
Eric Laurent81784c32012-11-19 14:55:58 -08005579 // cache the combined master volume and stream type volume for fast mixer; this
5580 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005581 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005582 proxy->framesReleased()).first;
5583 volume *= vh;
Andy Hung3ff4b552023-06-26 19:20:57 -07005584 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005585 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005586 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5587 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005588
Andy Hung2cbc2722023-07-17 17:05:00 -07005589 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005590 /*muteState=*/{masterVolume == 0.f,
5591 mStreamTypes[track->streamType()].volume == 0.f,
5592 mStreamTypes[track->streamType()].mute,
5593 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005594 vlf == 0.f && vrf == 0.f,
5595 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005596
5597 vlf *= volume;
5598 vrf *= volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005599
jiabin76d94692022-12-15 21:51:21 +00005600 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005601 ++fastTracks;
5602 } else {
5603 // was it previously active?
5604 if (state->mTrackMask & (1 << j)) {
5605 fastTrack->mBufferProvider = NULL;
5606 fastTrack->mGeneration++;
5607 state->mTrackMask &= ~(1 << j);
5608 didModify = true;
5609 // If any fast tracks were removed, we must wait for acknowledgement
5610 // because we're about to decrement the last sp<> on those tracks.
5611 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5612 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005613 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5614 // AudioTrack may start (which may not be with a start() but with a write()
5615 // after underrun) and immediately paused or released. In that case the
5616 // FastTrack state hasn't had time to update.
5617 // TODO Remove the ALOGW when this theory is confirmed.
5618 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005619 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung3ff4b552023-06-26 19:20:57 -07005620 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005621 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005622 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005623 }
5624 tracksToRemove->add(track);
5625 // Avoids a misleading display in dumpsys
Andy Hung3ff4b552023-06-26 19:20:57 -07005626 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005627 }
jiabin245cdd92018-12-07 17:55:15 -08005628 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5629 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5630 didModify = true;
5631 }
Eric Laurent81784c32012-11-19 14:55:58 -08005632 continue;
5633 }
5634
5635 { // local variable scope to avoid goto warning
5636
5637 audio_track_cblk_t* cblk = track->cblk();
5638
5639 // The first time a track is added we wait
5640 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005641 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005642
5643 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005644 // use the trackId as the AudioMixer name.
5645 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005646 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005647 trackId,
Andy Hung3ff4b552023-06-26 19:20:57 -07005648 track->channelMask(),
5649 track->format(),
5650 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005651 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005652 ALOGW("%s(): AudioMixer cannot create track(%d)"
5653 " mask %#x, format %#x, sessionId %d",
5654 __func__, trackId,
Andy Hung3ff4b552023-06-26 19:20:57 -07005655 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005656 tracksToRemove->add(track);
5657 track->invalidate(); // consider it dead.
5658 continue;
5659 }
5660 }
5661
Eric Laurent81784c32012-11-19 14:55:58 -08005662 // make sure that we have enough frames to mix one full buffer.
5663 // enforce this condition only once to enable draining the buffer in case the client
5664 // app does not call stop() and relies on underrun to stop:
5665 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5666 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005667 size_t desiredFrames;
Andy Hung3ff4b552023-06-26 19:20:57 -07005668 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5669 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005670
5671 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005672 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005673 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5674 // add frames already consumed but not yet released by the resampler
5675 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005676 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005677
Eric Laurent81784c32012-11-19 14:55:58 -08005678 uint32_t minFrames = 1;
5679 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5680 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005681 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005682 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005683
5684 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005685 if (ATRACE_ENABLED()) {
5686 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005687 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005688 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005689 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005690 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005691 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005692 !track->isPaused() && !track->isTerminated())
5693 {
Andy Hungc0691382018-09-12 18:01:57 -07005694 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005695
5696 mixedTracks++;
5697
Andy Hung69aed5f2014-02-25 17:24:40 -08005698 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5699 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005700 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005701 if (track->mainBuffer() != mSinkBuffer &&
5702 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005703 if (mEffectBufferEnabled) {
5704 mEffectBufferValid = true; // Later can set directly.
5705 }
Eric Laurent81784c32012-11-19 14:55:58 -08005706 chain = getEffectChain_l(track->sessionId());
5707 // Delegate volume control to effect in track effect chain if needed
5708 if (chain != 0) {
5709 tracksWithEffect++;
5710 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005711 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005712 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005713 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005714 }
5715 }
5716
5717
5718 int param = AudioMixer::VOLUME;
Andy Hung3ff4b552023-06-26 19:20:57 -07005719 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005720 // no ramp for the first volume setting
Andy Hung3ff4b552023-06-26 19:20:57 -07005721 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5722 if (track->state() == IAfTrackBase::RESUMING) {
5723 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005724 // If a new track is paused immediately after start, do not ramp on resume.
5725 if (cblk->mServer != 0) {
5726 param = AudioMixer::RAMP_VOLUME;
5727 }
Eric Laurent81784c32012-11-19 14:55:58 -08005728 }
Andy Hungc0691382018-09-12 18:01:57 -07005729 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005730 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005731 // FIXME should not make a decision based on mServer
5732 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005733 // If the track is stopped before the first frame was mixed,
5734 // do not apply ramp
5735 param = AudioMixer::RAMP_VOLUME;
5736 }
5737
5738 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005739 uint32_t vl, vr; // in U8.24 integer format
5740 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005741 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005742 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005743 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung3ff4b552023-06-26 19:20:57 -07005744 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005745 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung3ff4b552023-06-26 19:20:57 -07005746 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005747
Eric Laurenteab90452019-06-24 15:17:46 -07005748 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5749 v = 0;
5750 }
5751
5752 handleVoipVolume_l(&v);
5753
5754 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005755 vl = vr = 0;
5756 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005757 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005758 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005759 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005760 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5761 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005762 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005763 if (vlf > GAIN_FLOAT_UNITY) {
5764 ALOGV("Track left volume out of range: %.3g", vlf);
5765 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005766 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005767 if (vrf > GAIN_FLOAT_UNITY) {
5768 ALOGV("Track right volume out of range: %.3g", vrf);
5769 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005770 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005771
Andy Hung2cbc2722023-07-17 17:05:00 -07005772 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005773 /*muteState=*/{masterVolume == 0.f,
5774 mStreamTypes[track->streamType()].volume == 0.f,
5775 mStreamTypes[track->streamType()].mute,
5776 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005777 vlf == 0.f && vrf == 0.f,
5778 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005779
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005780 // now apply the master volume and stream type volume and shaper volume
5781 vlf *= v * vh;
5782 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005783 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005784 // then derive vl and vr as U8.24 versions for the effect chain
5785 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5786 vl = (uint32_t) (scaleto8_24 * vlf);
5787 vr = (uint32_t) (scaleto8_24 * vrf);
5788 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005789 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005790 // send level comes from shared memory and so may be corrupt
5791 if (sendLevel > MAX_GAIN_INT) {
5792 ALOGV("Track send level out of range: %04X", sendLevel);
5793 sendLevel = MAX_GAIN_INT;
5794 }
Andy Hung6be49402014-05-30 10:42:03 -07005795 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5796 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005797 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005798
jiabin76d94692022-12-15 21:51:21 +00005799 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005800
Eric Laurent81784c32012-11-19 14:55:58 -08005801 // Delegate volume control to effect in track effect chain if needed
5802 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5803 // Do not ramp volume if volume is controlled by effect
5804 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005805 // Update remaining floating point volume levels
5806 vlf = (float)vl / (1 << 24);
5807 vrf = (float)vr / (1 << 24);
Andy Hung3ff4b552023-06-26 19:20:57 -07005808 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005809 } else {
5810 // force no volume ramp when volume controller was just disabled or removed
5811 // from effect chain to avoid volume spike
Andy Hung3ff4b552023-06-26 19:20:57 -07005812 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005813 param = AudioMixer::VOLUME;
5814 }
Andy Hung3ff4b552023-06-26 19:20:57 -07005815 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005816 }
5817
Eric Laurent81784c32012-11-19 14:55:58 -08005818 // XXX: these things DON'T need to be done each time
Andy Hung3ff4b552023-06-26 19:20:57 -07005819 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005820 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005821
Andy Hungc0691382018-09-12 18:01:57 -07005822 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5823 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5824 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005825 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005826 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005827 AudioMixer::TRACK,
5828 AudioMixer::FORMAT, (void *)track->format());
5829 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005830 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005831 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005832 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005833
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005834 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005835 mAudioMixer->setParameter(
5836 trackId,
5837 AudioMixer::TRACK,
5838 AudioMixer::MIXER_CHANNEL_MASK,
5839 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5840 } else {
5841 mAudioMixer->setParameter(
5842 trackId,
5843 AudioMixer::TRACK,
5844 AudioMixer::MIXER_CHANNEL_MASK,
5845 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5846 }
5847
Glenn Kastene3aa6592012-12-04 12:22:46 -08005848 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005849 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005850 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005851 if (reqSampleRate == 0) {
5852 reqSampleRate = mSampleRate;
5853 } else if (reqSampleRate > maxSampleRate) {
5854 reqSampleRate = maxSampleRate;
5855 }
Eric Laurent81784c32012-11-19 14:55:58 -08005856 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005857 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005858 AudioMixer::RESAMPLE,
5859 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005860 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005861
Andy Hung8edb8dc2015-03-26 19:13:55 -07005862 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005863 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005864 AudioMixer::TIMESTRETCH,
5865 AudioMixer::PLAYBACK_RATE,
Andy Hung71ba4b32022-10-06 12:09:49 -07005866 // cast away constness for this generic API.
5867 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005868
Andy Hung69aed5f2014-02-25 17:24:40 -08005869 /*
5870 * Select the appropriate output buffer for the track.
5871 *
Andy Hung98ef9782014-03-04 14:46:50 -08005872 * Tracks with effects go into their own effects chain buffer
5873 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005874 *
5875 * Other tracks can use mMixerBuffer for higher precision
5876 * channel accumulation. If this buffer is enabled
5877 * (mMixerBufferEnabled true), then selected tracks will accumulate
5878 * into it.
5879 *
5880 */
5881 if (mMixerBufferEnabled
5882 && (track->mainBuffer() == mSinkBuffer
5883 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005884 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005885 mAudioMixer->setParameter(
5886 trackId,
5887 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005888 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005889 mAudioMixer->setParameter(
5890 trackId,
5891 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005892 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005893 } else {
5894 mAudioMixer->setParameter(
5895 trackId,
5896 AudioMixer::TRACK,
5897 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5898 mAudioMixer->setParameter(
5899 trackId,
5900 AudioMixer::TRACK,
5901 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5902 // TODO: override track->mainBuffer()?
5903 mMixerBufferValid = true;
5904 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005905 } else {
5906 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005907 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005908 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07005909 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005910 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005911 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005912 AudioMixer::TRACK,
5913 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5914 }
Eric Laurent81784c32012-11-19 14:55:58 -08005915 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005916 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005917 AudioMixer::TRACK,
5918 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005919 mAudioMixer->setParameter(
5920 trackId,
5921 AudioMixer::TRACK,
5922 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005923 mAudioMixer->setParameter(
5924 trackId,
5925 AudioMixer::TRACK,
5926 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung3ff4b552023-06-26 19:20:57 -07005927 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005928 mAudioMixer->setParameter(
5929 trackId,
5930 AudioMixer::TRACK,
Andy Hung3ff4b552023-06-26 19:20:57 -07005931 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08005932
5933 // reset retry count
Andy Hung3ff4b552023-06-26 19:20:57 -07005934 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005935
5936 // If one track is ready, set the mixer ready if:
5937 // - the mixer was not ready during previous round OR
5938 // - no other track is not ready
5939 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5940 mixerStatus != MIXER_TRACKS_ENABLED) {
5941 mixerStatus = MIXER_TRACKS_READY;
5942 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005943
5944 // Enable the next few lines to instrument a test for underrun log handling.
5945 // TODO: Remove when we have a better way of testing the underrun log.
5946#if 0
5947 static int i;
5948 if ((++i & 0xf) == 0) {
5949 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5950 }
5951#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005952 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005953 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005954 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005955 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5956 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005957 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005958 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005959 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005960
Eric Laurent81784c32012-11-19 14:55:58 -08005961 // clear effect chain input buffer if an active track underruns to avoid sending
5962 // previous audio buffer again to effects
5963 chain = getEffectChain_l(track->sessionId());
5964 if (chain != 0) {
5965 chain->clearInputBuffer();
5966 }
5967
Andy Hungc0691382018-09-12 18:01:57 -07005968 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005969 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5970 track->isStopped() || track->isPaused()) {
5971 // We have consumed all the buffers of this track.
5972 // Remove it from the list of active tracks.
5973 // TODO: use actual buffer filling status instead of latency when available from
5974 // audio HAL
5975 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005976 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005977 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5978 if (track->isStopped()) {
5979 track->reset();
5980 }
5981 tracksToRemove->add(track);
5982 }
5983 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005984 // No buffers for this track. Give it a few chances to
5985 // fill a buffer, then remove it from active list.
Andy Hung3ff4b552023-06-26 19:20:57 -07005986 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005987 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5988 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005989 tracksToRemove->add(track);
5990 // indicate to client process that the track was disabled because of underrun;
5991 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005992 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005993 // If one track is not ready, mark the mixer also not ready if:
5994 // - the mixer was ready during previous round OR
5995 // - no other track is ready
5996 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5997 mixerStatus != MIXER_TRACKS_READY) {
5998 mixerStatus = MIXER_TRACKS_ENABLED;
5999 }
6000 }
Andy Hungc0691382018-09-12 18:01:57 -07006001 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006002 }
6003
6004 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006005
6006 }
6007
jiabin245cdd92018-12-07 17:55:15 -08006008 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6009 // When there is no fast track playing haptic and FastMixer exists,
6010 // enabling the first FastTrack, which provides mixed data from normal
6011 // tracks, to play haptic data.
6012 FastTrack *fastTrack = &state->mFastTracks[0];
6013 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6014 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6015 didModify = true;
6016 }
6017 }
6018
Eric Laurent81784c32012-11-19 14:55:58 -08006019 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006020 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006021 if (didModify) {
6022 state->mFastTracksGen++;
6023 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6024 if (kUseFastMixer == FastMixer_Dynamic &&
6025 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6026 state->mCommand = FastMixerState::COLD_IDLE;
6027 state->mColdFutexAddr = &mFastMixerFutex;
6028 state->mColdGen++;
6029 mFastMixerFutex = 0;
6030 if (kUseFastMixer == FastMixer_Dynamic) {
6031 mNormalSink = mOutputSink;
6032 }
6033 // If we go into cold idle, need to wait for acknowledgement
6034 // so that fast mixer stops doing I/O.
6035 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6036 pauseAudioWatchdog = true;
6037 }
Eric Laurent81784c32012-11-19 14:55:58 -08006038 }
6039 if (sq != NULL) {
6040 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006041 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6042 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6043 // when bringing the output sink into standby.)
6044 //
6045 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6046 //
6047 // This occurs with BT suspend when we idle the FastMixer with
6048 // active tracks, which may be added or removed.
6049 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006050 }
6051#ifdef AUDIO_WATCHDOG
6052 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6053 mAudioWatchdog->pause();
6054 }
6055#endif
6056
6057 // Now perform the deferred reset on fast tracks that have stopped
6058 while (resetMask != 0) {
6059 size_t i = __builtin_ctz(resetMask);
6060 ALOG_ASSERT(i < count);
6061 resetMask &= ~(1 << i);
Andy Hung3ff4b552023-06-26 19:20:57 -07006062 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006063 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6064 track->reset();
6065 }
6066
Andy Hung80d03d22018-04-10 10:32:11 -07006067 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6068 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6069 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6070 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6071 // See also the implementation of destroyTrack_l().
6072 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006073 const int trackId = track->id();
6074 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6075 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006076 }
6077 }
6078
Eric Laurent81784c32012-11-19 14:55:58 -08006079 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006080 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006081
Eric Laurentb3f315a2021-07-13 15:09:05 +02006082 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6083 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006084 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006085 }
6086
6087 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006088 // as long as there are effects we should clear the effects buffer, to avoid
6089 // passing a non-clean buffer to the effect chain
6090 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006091 if (mType == SPATIALIZER) {
6092 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6093 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006094 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006095 // sink or mix buffer must be cleared if all tracks are connected to an
6096 // effect chain as in this case the mixer will not write to the sink or mix buffer
6097 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006098 // always clear sink buffer for spatializer output as the output of the spatializer
6099 // effect will be accumulated into it
6100 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6101 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006102 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006103 if (mMixerBufferValid) {
6104 memset(mMixerBuffer, 0, mMixerBufferSize);
6105 // TODO: In testing, mSinkBuffer below need not be cleared because
6106 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6107 // after mixing.
6108 //
6109 // To enforce this guarantee:
6110 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6111 // (mixedTracks == 0 && fastTracks > 0))
6112 // must imply MIXER_TRACKS_READY.
6113 // Later, we may clear buffers regardless, and skip much of this logic.
6114 }
Andy Hung98ef9782014-03-04 14:46:50 -08006115 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006116 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006117 }
6118
6119 // if any fast tracks, then status is ready
6120 mMixerStatusIgnoringFastTracks = mixerStatus;
6121 if (fastTracks > 0) {
6122 mixerStatus = MIXER_TRACKS_READY;
6123 }
6124 return mixerStatus;
6125}
6126
Eric Laurentad7dd962016-09-22 12:38:37 -07006127// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006128uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006129{
6130 uint32_t trackCount = 0;
6131 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006132 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006133 trackCount++;
6134 }
6135 }
6136 return trackCount;
6137}
6138
Andy Hung71742ab2023-07-07 13:47:37 -07006139bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006140{
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006141 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6142 // could falsely detect that the frame position has stalled due to underrun because we haven't
6143 // given the Audio HAL enough time to update.
6144 const nsecs_t nowNs = systemTime();
6145 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6146 return mLatchedValue;
6147 }
6148 mPreviousNs = nowNs;
6149 mLatchedValue = false;
6150 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006151 uint64_t position = 0;
6152 struct timespec unused;
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006153 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006154 if (ret == NO_ERROR) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006155 if (position != mPreviousPosition) {
6156 mPreviousPosition = position;
6157 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006158 }
6159 }
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006160 return mLatchedValue;
6161}
6162
Andy Hung71742ab2023-07-07 13:47:37 -07006163void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006164{
6165 mLatchedValue = true;
6166 mPreviousPosition = 0;
6167 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006168}
6169
Andy Hung1bc088a2018-02-09 15:57:31 -08006170// isTrackAllowed_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006171bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006172 audio_channel_mask_t channelMask, audio_format_t format,
6173 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006174{
Andy Hung1bc088a2018-02-09 15:57:31 -08006175 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6176 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006177 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006178 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006179 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006180 ALOGW("%s: invalid format: %#x", __func__, format);
6181 return false;
6182 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006183 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006184 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6185 return false;
6186 }
6187 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006188}
6189
Eric Laurent10351942014-05-08 18:49:52 -07006190// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006191bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006192 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006193{
Eric Laurent81784c32012-11-19 14:55:58 -08006194 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006195 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006196
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006197 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006198
Eric Laurent10351942014-05-08 18:49:52 -07006199 AudioParameter param = AudioParameter(keyValuePair);
6200 int value;
6201 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6202 reconfig = true;
6203 }
6204 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung71742ab2023-07-07 13:47:37 -07006205 if (!AudioFlinger::isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006206 status = BAD_VALUE;
6207 } else {
6208 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006209 reconfig = true;
6210 }
Eric Laurent10351942014-05-08 18:49:52 -07006211 }
6212 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung71742ab2023-07-07 13:47:37 -07006213 if (!AudioFlinger::isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006214 status = BAD_VALUE;
6215 } else {
6216 // no need to save value, since it's constant
6217 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006218 }
Eric Laurent10351942014-05-08 18:49:52 -07006219 }
6220 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6221 // do not accept frame count changes if tracks are open as the track buffer
6222 // size depends on frame count and correct behavior would not be guaranteed
6223 // if frame count is changed after track creation
6224 if (!mTracks.isEmpty()) {
6225 status = INVALID_OPERATION;
6226 } else {
6227 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006228 }
Eric Laurent10351942014-05-08 18:49:52 -07006229 }
6230 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006231 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006232 }
Eric Laurent81784c32012-11-19 14:55:58 -08006233
Eric Laurent10351942014-05-08 18:49:52 -07006234 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006235 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006236 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungb72a5502023-03-27 15:53:06 -07006237 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6238 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006239 mOutput->standby();
Andy Hungb72a5502023-03-27 15:53:06 -07006240 mThreadMetrics.logEndInterval();
6241 mThreadSnapshot.onEnd();
Andy Hungdda7aed2023-03-27 15:53:06 -07006242 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006243 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006244 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006245 }
Eric Laurent10351942014-05-08 18:49:52 -07006246 if (status == NO_ERROR && reconfig) {
6247 readOutputParameters_l();
6248 delete mAudioMixer;
6249 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006250 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006251 const int trackId = track->id();
Andy Hung71ba4b32022-10-06 12:09:49 -07006252 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006253 trackId,
Andy Hung3ff4b552023-06-26 19:20:57 -07006254 track->channelMask(),
6255 track->format(),
6256 track->sessionId());
Andy Hung71ba4b32022-10-06 12:09:49 -07006257 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006258 "%s(): AudioMixer cannot create track(%d)"
6259 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006260 __func__,
Andy Hung3ff4b552023-06-26 19:20:57 -07006261 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006262 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006263 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006264 }
Eric Laurent81784c32012-11-19 14:55:58 -08006265 }
6266
Dean Wheatley68918102021-03-19 22:09:19 +11006267 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006268}
6269
6270
Andy Hung71742ab2023-07-07 13:47:37 -07006271void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006272{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006273 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006274 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006275 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006276 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006277 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6278 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6279 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006280 if (hasFastMixer()) {
6281 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6282
6283 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6284 // while we are dumping it. It may be inconsistent, but it won't mutate!
6285 // This is a large object so we place it on the heap.
6286 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006287 const std::unique_ptr<FastMixerDumpState> copy =
6288 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006289 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006290
6291#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006292 // Similar for state queue
6293 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6294 observerCopy.dump(fd);
6295 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6296 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006297#endif
6298
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006299#ifdef AUDIO_WATCHDOG
6300 if (mAudioWatchdog != 0) {
6301 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6302 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6303 wdCopy.dump(fd);
6304 }
6305#endif
6306
6307 } else {
6308 dprintf(fd, " No FastMixer\n");
6309 }
Eric Laurent90cea102023-05-15 15:08:27 +02006310
6311 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6312 mBluetoothLatencyModesEnabled ? "" : "not ");
6313 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6314 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6315 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006316}
6317
Andy Hung71742ab2023-07-07 13:47:37 -07006318uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006319{
6320 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6321}
6322
Andy Hung71742ab2023-07-07 13:47:37 -07006323uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006324{
6325 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6326}
6327
Andy Hung71742ab2023-07-07 13:47:37 -07006328void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006329{
6330 PlaybackThread::cacheParameters_l();
6331
6332 // FIXME: Relaxed timing because of a certain device that can't meet latency
6333 // Should be reduced to 2x after the vendor fixes the driver issue
6334 // increase threshold again due to low power audio mode. The way this warning
6335 // threshold is calculated and its usefulness should be reconsidered anyway.
6336 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6337}
6338
Andy Hung71742ab2023-07-07 13:47:37 -07006339void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung2cbc2722023-07-17 17:05:00 -07006340 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006341}
6342
Andy Hung71742ab2023-07-07 13:47:37 -07006343void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006344 // Only handle latency mode if:
6345 // - mBluetoothLatencyModesEnabled is true
6346 // - the HAL supports latency modes
6347 // - the selected device is Bluetooth LE or A2DP
6348 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6349 return;
6350 }
6351 if (mOutDeviceTypeAddrs.size() != 1
6352 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6353 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6354 return;
6355 }
6356
6357 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6358 if (mSupportedLatencyModes.size() == 1) {
6359 // If the HAL only support one latency mode currently, confirm the choice
6360 latencyMode = mSupportedLatencyModes[0];
6361 } else if (mSupportedLatencyModes.size() > 1) {
6362 // Request low latency if:
6363 // - At least one active track is either:
6364 // - a fast track with gaming usage or
6365 // - a track with acessibility usage
6366 for (const auto& track : mActiveTracks) {
6367 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6368 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6369 latencyMode = AUDIO_LATENCY_MODE_LOW;
6370 break;
6371 }
6372 }
6373 }
6374
6375 if (latencyMode != mSetLatencyMode) {
6376 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6377 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6378 __func__, mId, toString(latencyMode).c_str(), status);
6379 if (status == NO_ERROR) {
6380 mSetLatencyMode = latencyMode;
6381 }
6382 }
6383}
6384
Andy Hung71742ab2023-07-07 13:47:37 -07006385void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006386
6387 if (mOutput == nullptr || mOutput->stream == nullptr) {
6388 return;
6389 }
6390 std::vector<audio_latency_mode_t> latencyModes;
6391 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6392 if (status != NO_ERROR) {
6393 latencyModes.clear();
6394 }
6395 if (latencyModes != mSupportedLatencyModes) {
6396 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6397 __func__, mId, status, toString(latencyModes).c_str());
6398 mSupportedLatencyModes.swap(latencyModes);
6399 sendHalLatencyModesChangedEvent_l();
6400 }
6401}
6402
Andy Hung71742ab2023-07-07 13:47:37 -07006403status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006404 std::vector<audio_latency_mode_t>* modes) {
6405 if (modes == nullptr) {
6406 return BAD_VALUE;
6407 }
6408 Mutex::Autolock _l(mLock);
6409 *modes = mSupportedLatencyModes;
6410 return NO_ERROR;
6411}
6412
Andy Hung71742ab2023-07-07 13:47:37 -07006413void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006414 std::vector<audio_latency_mode_t> modes) {
6415 Mutex::Autolock _l(mLock);
6416 if (modes != mSupportedLatencyModes) {
6417 ALOGD("%s: thread(%d) supported latency modes: %s",
6418 __func__, mId, toString(modes).c_str());
6419 mSupportedLatencyModes.swap(modes);
6420 sendHalLatencyModesChangedEvent_l();
6421 }
6422}
6423
Andy Hung71742ab2023-07-07 13:47:37 -07006424status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006425 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6426 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6427 return INVALID_OPERATION;
6428 }
6429 mBluetoothLatencyModesEnabled.store(enabled);
6430 return NO_ERROR;
6431}
6432
Eric Laurent81784c32012-11-19 14:55:58 -08006433// ----------------------------------------------------------------------------
6434
Andy Hung71742ab2023-07-07 13:47:37 -07006435/* static */
6436sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07006437 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07006438 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6439 const audio_offload_info_t& offloadInfo) {
6440 return sp<DirectOutputThread>::make(
Andy Hung2cbc2722023-07-17 17:05:00 -07006441 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung71742ab2023-07-07 13:47:37 -07006442}
6443
Andy Hung2cbc2722023-07-17 17:05:00 -07006444DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fenn56576722022-10-05 13:42:36 -07006445 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6446 const audio_offload_info_t& offloadInfo)
Andy Hung2cbc2722023-07-17 17:05:00 -07006447 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fenn56576722022-10-05 13:42:36 -07006448 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006449{
Andy Hung2cbc2722023-07-17 17:05:00 -07006450 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006451}
6452
Andy Hung71742ab2023-07-07 13:47:37 -07006453DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006454{
6455}
6456
Andy Hung71742ab2023-07-07 13:47:37 -07006457void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006458{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006459 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006460 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6461 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6462}
6463
Andy Hung71742ab2023-07-07 13:47:37 -07006464void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006465{
6466 Mutex::Autolock _l(mLock);
6467 if (mMasterBalance != balance) {
6468 mMasterBalance.store(balance);
6469 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6470 broadcast_l();
6471 }
6472}
6473
Andy Hung71742ab2023-07-07 13:47:37 -07006474void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006475{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006476 float left, right;
6477
Andy Hung333ab962019-05-28 20:23:35 -07006478 // Ensure volumeshaper state always advances even when muted.
Andy Hung3ff4b552023-06-26 19:20:57 -07006479 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hungee86cee2022-12-13 19:19:53 -08006480
Andy Hungee86cee2022-12-13 19:19:53 -08006481 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6482 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6483
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006484 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6485 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hungee86cee2022-12-13 19:19:53 -08006486
6487 const int64_t volumeShaperFrames =
6488 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6489 const auto [shaperVolume, shaperActive] =
6490 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006491 mVolumeShaperActive = shaperActive;
6492
Vlad Popae2f5aef2022-07-25 16:00:20 +02006493 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6494 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6495 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6496
6497 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6498
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006499 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006500 left = right = 0;
6501 } else {
6502 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006503 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006504
Glenn Kastenc56f3422014-03-21 17:53:17 -07006505 if (left > GAIN_FLOAT_UNITY) {
6506 left = GAIN_FLOAT_UNITY;
6507 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006508 if (right > GAIN_FLOAT_UNITY) {
6509 right = GAIN_FLOAT_UNITY;
6510 }
zhangjincheng73e73872023-01-16 17:17:38 +08006511 left *= v;
6512 right *= v;
Andy Hung2cbc2722023-07-17 17:05:00 -07006513 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng73e73872023-01-16 17:17:38 +08006514 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6515 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6516 right *= mMasterBalanceRight;
6517 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006518 }
6519
Andy Hung2cbc2722023-07-17 17:05:00 -07006520 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006521 /*muteState=*/{mMasterMute,
6522 mStreamTypes[track->streamType()].volume == 0.f,
6523 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006524 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006525 clientVolumeMute,
6526 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006527
Eric Laurentbfb1b832013-01-07 09:53:42 -08006528 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006529 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006530 if (left != mLeftVolFloat || right != mRightVolFloat) {
6531 mLeftVolFloat = left;
6532 mRightVolFloat = right;
6533
Eric Laurentbfb1b832013-01-07 09:53:42 -08006534 // Delegate volume control to effect in track effect chain if needed
6535 // only one effect chain can be present on DirectOutputThread, so if
6536 // there is one, the track is connected to it
6537 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006538 // if effect chain exists, volume is handled by it.
6539 // Convert volumes from float to 8.24
6540 uint32_t vl = (uint32_t)(left * (1 << 24));
6541 uint32_t vr = (uint32_t)(right * (1 << 24));
6542 // Direct/Offload effect chains set output volume in setVolume_l().
6543 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6544 } else {
6545 // otherwise we directly set the volume.
6546 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006547 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006548 }
6549 }
6550}
6551
Andy Hung71742ab2023-07-07 13:47:37 -07006552void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006553{
Andy Hung3ff4b552023-06-26 19:20:57 -07006554 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6555 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006556
Eric Laurent0f0631e2015-07-06 18:01:25 -07006557 if (previousTrack != 0 && latestTrack != 0) {
6558 if (mType == DIRECT) {
6559 if (previousTrack.get() != latestTrack.get()) {
6560 mFlushPending = true;
6561 }
6562 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006563 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6564 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006565 mFlushPending = true;
6566 }
6567 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006568 } else if (previousTrack == 0) {
6569 // there could be an old track added back during track transition for direct
6570 // output, so always issues flush to flush data of the previous track if it
6571 // was already destroyed with HAL paused, then flush can resume the playback
6572 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006573 }
6574 PlaybackThread::onAddNewTrack_l();
6575}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006576
Andy Hung71742ab2023-07-07 13:47:37 -07006577PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07006578 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006579)
6580{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006581 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006582 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006583 bool doHwPause = false;
6584 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006585
6586 // find out which tracks need to be processed
Andy Hung3ff4b552023-06-26 19:20:57 -07006587 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006588 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006589 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006590 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006591 continue;
6592 }
6593
Andy Hung3ff4b552023-06-26 19:20:57 -07006594 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006595#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006596 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006597#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006598 // Only consider last track started for volume and mixer state control.
6599 // In theory an older track could underrun and restart after the new one starts
6600 // but as we only care about the transition phase between two tracks on a
6601 // direct output, it is not a problem to ignore the underrun case.
Andy Hung3ff4b552023-06-26 19:20:57 -07006602 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006603 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006604
Kuowei Li23666472021-01-20 10:23:25 +08006605 if (track->isPausePending()) {
6606 track->pauseAck();
6607 // It is possible a track might have been flushed or stopped.
6608 // Other operations such as flush pending might occur on the next prepare.
6609 if (track->isPausing()) {
6610 track->setPaused();
6611 }
6612 // Always perform pause, as an immediate flush will change
6613 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006614 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006615 doHwPause = true;
6616 mHwPaused = true;
6617 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006618 } else if (track->isFlushPending()) {
6619 track->flushAck();
6620 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006621 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006622 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006623 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006624 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006625 if (last) {
6626 mLeftVolFloat = mRightVolFloat = -1.0;
6627 if (mHwPaused) {
6628 doHwResume = true;
6629 mHwPaused = false;
6630 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006631 }
6632 }
6633
Eric Laurent81784c32012-11-19 14:55:58 -08006634 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006635 // for all its buffers to be filled before processing it.
6636 // Allow draining the buffer in case the client
6637 // app does not call stop() and relies on underrun to stop:
Andy Hung3ff4b552023-06-26 19:20:57 -07006638 // hence the test on (track->retryCount() > 1).
6639 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006640 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6641 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006642 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006643
6644 // target retry count that we will use is based on the time we wait for retries.
6645 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6646 // the retry threshold is when we accept any size for PCM data. This is slightly
6647 // smaller than the retry count so we can push small bits of data without a glitch.
6648 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006649 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006650 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung3ff4b552023-06-26 19:20:57 -07006651 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006652 minFrames = mNormalFrameCount;
6653 } else {
6654 minFrames = 1;
6655 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006656
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006657 const size_t framesReady = track->framesReady();
6658 const int trackId = track->id();
6659 if (ATRACE_ENABLED()) {
6660 std::string traceName("nRdy");
6661 traceName += std::to_string(trackId);
6662 ATRACE_INT(traceName.c_str(), framesReady);
6663 }
6664 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006665 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006666 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006667 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006668
Andy Hung3ff4b552023-06-26 19:20:57 -07006669 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6670 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006671 if (last) {
6672 // make sure processVolume_l() will apply new volume even if 0
6673 mLeftVolFloat = mRightVolFloat = -1.0;
6674 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006675 if (!mHwSupportsPause) {
6676 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006677 }
6678 }
6679
6680 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006681 processVolume_l(track, last);
6682 if (last) {
Andy Hung3ff4b552023-06-26 19:20:57 -07006683 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006684 if (previousTrack != 0) {
6685 if (track != previousTrack.get()) {
6686 // Flush any data still being written from last track
6687 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006688 // Invalidate previous track to force a seek when resuming.
6689 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006690 }
6691 }
6692 mPreviousTrack = track;
6693
Eric Laurentd595b7c2013-04-03 17:27:56 -07006694 // reset retry count
Andy Hung3ff4b552023-06-26 19:20:57 -07006695 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006696 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006697 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006698 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006699 doHwResume = true;
6700 mHwPaused = false;
6701 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006702 }
Eric Laurent81784c32012-11-19 14:55:58 -08006703 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006704 // clear effect chain input buffer if the last active track started underruns
6705 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006706 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006707 mEffectChains[0]->clearInputBuffer();
6708 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006709 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07006710 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006711 if (last && mHwPaused) {
6712 doHwResume = true;
6713 mHwPaused = false;
6714 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006715 }
6716 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6717 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006718 // We have consumed all the buffers of this track.
6719 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006720 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006721 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006722 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006723 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006724 if (presComplete) {
6725 mOutput->presentationComplete();
6726 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006727 if (track->isStopping_2()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07006728 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006729 }
Eric Laurent81784c32012-11-19 14:55:58 -08006730 if (track->isStopped()) {
6731 track->reset();
6732 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006733 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006734 }
6735 } else {
6736 // No buffers for this track. Give it a few chances to
6737 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006738 // Only consider last track started for mixer state control
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006739 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07006740 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung3ff4b552023-06-26 19:20:57 -07006741 && --(track->retryCount()) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006742 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung3ff4b552023-06-26 19:20:57 -07006743 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006744 } else {
6745 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6746 tracksToRemove->add(track);
6747 // indicate to client process that the track was disabled because of
6748 // underrun; it will then automatically call start() when data is available
6749 track->disable();
6750 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6751 // unlike mixerthread, HAL can be paused for direct output
6752 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6753 "minFrames = %u, mFormat = %#x",
6754 framesReady, minFrames, mFormat);
6755 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6756 doHwPause = true;
6757 mHwPaused = true;
6758 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006759 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006760 } else if (last) {
6761 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006762 }
6763 }
6764 }
6765 }
6766
Eric Laurentd1f69b02014-12-15 14:33:13 -08006767 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006768 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006769 for (size_t i = 0; i < mTracks.size(); i++) {
6770 if (mTracks[i]->isFlushPending()) {
6771 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006772 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006773 }
6774 }
6775 }
6776
6777 // make sure the pause/flush/resume sequence is executed in the right order.
6778 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6779 // before flush and then resume HW. This can happen in case of pause/flush/resume
6780 // if resume is received before pause is executed.
6781 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006782 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006783 status_t result = mOutput->stream->pause();
6784 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006785 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006786 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006787 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006788 flushHw_l();
6789 }
6790 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006791 status_t result = mOutput->stream->resume();
6792 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006793 }
Eric Laurent81784c32012-11-19 14:55:58 -08006794 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006795 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006796
6797 return mixerStatus;
6798}
6799
Andy Hung71742ab2023-07-07 13:47:37 -07006800void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006801{
Eric Laurent81784c32012-11-19 14:55:58 -08006802 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006803 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006804 // output audio to hardware
6805 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006806 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006807 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006808 status_t status = mActiveTrack->getNextBuffer(&buffer);
6809 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006810 // no need to pad with 0 for compressed audio
6811 if (audio_has_proportional_frames(mFormat)) {
6812 memset(curBuf, 0, frameCount * mFrameSize);
6813 }
Eric Laurent81784c32012-11-19 14:55:58 -08006814 break;
6815 }
6816 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6817 frameCount -= buffer.frameCount;
6818 curBuf += buffer.frameCount * mFrameSize;
6819 mActiveTrack->releaseBuffer(&buffer);
6820 }
Andy Hung2098f272014-02-27 14:00:06 -08006821 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006822 mSleepTimeUs = 0;
6823 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006824 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006825}
6826
Andy Hung71742ab2023-07-07 13:47:37 -07006827void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006828{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006829 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006830 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006831 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006832 return;
6833 }
Andy Hung85ba3332021-04-27 17:40:26 -07006834 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6835 mSleepTimeUs = mActiveSleepTimeUs;
6836 } else {
6837 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006838 }
Andy Hung85ba3332021-04-27 17:40:26 -07006839 // Note: In S or later, we do not write zeroes for
6840 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006841}
6842
Andy Hung71742ab2023-07-07 13:47:37 -07006843void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006844{
6845 {
6846 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006847 for (size_t i = 0; i < mTracks.size(); i++) {
6848 if (mTracks[i]->isFlushPending()) {
6849 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006850 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006851 }
6852 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006853 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006854 flushHw_l();
6855 }
6856 }
6857 PlaybackThread::threadLoop_exit();
6858}
6859
6860// must be called with thread mutex locked
Andy Hung71742ab2023-07-07 13:47:37 -07006861bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006862{
6863 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006864 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006865
6866 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6867 // after a timeout and we will enter standby then.
6868 if (mTracks.size() > 0) {
6869 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006870 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung3ff4b552023-06-26 19:20:57 -07006871 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006872 }
6873
Eric Laurent5cff4032015-05-26 13:49:58 -07006874 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006875}
6876
Eric Laurent10351942014-05-08 18:49:52 -07006877// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006878bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006879 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006880{
6881 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006882 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006883
Eric Laurent10351942014-05-08 18:49:52 -07006884 AudioParameter param = AudioParameter(keyValuePair);
6885 int value;
6886 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006887 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006888 }
Eric Laurent10351942014-05-08 18:49:52 -07006889 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6890 // do not accept frame count changes if tracks are open as the track buffer
6891 // size depends on frame count and correct behavior would not be garantied
6892 // if frame count is changed after track creation
6893 if (!mTracks.isEmpty()) {
6894 status = INVALID_OPERATION;
6895 } else {
6896 reconfig = true;
6897 }
6898 }
6899 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006900 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006901 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006902 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006903 if (!mStandby) {
6904 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006905 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02006906 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07006907 }
Eric Laurent10351942014-05-08 18:49:52 -07006908 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006909 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006910 }
6911 if (status == NO_ERROR && reconfig) {
6912 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006913 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006914 }
6915 }
6916
Dean Wheatley68918102021-03-19 22:09:19 +11006917 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006918}
6919
Andy Hung71742ab2023-07-07 13:47:37 -07006920uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006921{
6922 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006923 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006924 time = PlaybackThread::activeSleepTimeUs();
6925 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006926 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006927 }
6928 return time;
6929}
6930
Andy Hung71742ab2023-07-07 13:47:37 -07006931uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006932{
6933 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006934 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006935 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6936 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006937 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006938 }
6939 return time;
6940}
6941
Andy Hung71742ab2023-07-07 13:47:37 -07006942uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006943{
6944 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006945 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006946 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6947 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006948 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006949 }
6950 return time;
6951}
6952
Andy Hung71742ab2023-07-07 13:47:37 -07006953void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006954{
6955 PlaybackThread::cacheParameters_l();
6956
6957 // use shorter standby delay as on normal output to release
6958 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006959 // no delay on outputs with HW A/V sync
6960 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006961 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006962 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006963 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006964 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006965 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006966 }
Eric Laurent81784c32012-11-19 14:55:58 -08006967}
6968
Andy Hung71742ab2023-07-07 13:47:37 -07006969void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07006970{
ziyangch8f194f12021-12-01 13:48:04 -08006971 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08006972 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006973 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006974 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006975 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006976 mTimestamp.clear();
Andy Hungee86cee2022-12-13 19:19:53 -08006977 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07006978}
6979
Andy Hung71742ab2023-07-07 13:47:37 -07006980int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08006981 // If a VolumeShaper is active, we must wake up periodically to update volume.
6982 const int64_t NS_PER_MS = 1000000;
6983 return mVolumeShaperActive ?
6984 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6985}
6986
Eric Laurent81784c32012-11-19 14:55:58 -08006987// ----------------------------------------------------------------------------
6988
Andy Hung71742ab2023-07-07 13:47:37 -07006989AsyncCallbackThread::AsyncCallbackThread(
6990 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006991 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006992 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006993 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006994 mDrainSequence(0),
6995 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006996{
6997}
6998
Andy Hung71742ab2023-07-07 13:47:37 -07006999void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007000{
7001 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7002}
7003
Andy Hung71742ab2023-07-07 13:47:37 -07007004bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007005{
7006 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007007 uint32_t writeAckSequence;
7008 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007009 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007010
7011 {
7012 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007013 while (!((mWriteAckSequence & 1) ||
7014 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007015 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007016 exitPending())) {
7017 mWaitWorkCV.wait(mLock);
7018 }
7019
Eric Laurentbfb1b832013-01-07 09:53:42 -08007020 if (exitPending()) {
7021 break;
7022 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007023 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7024 mWriteAckSequence, mDrainSequence);
7025 writeAckSequence = mWriteAckSequence;
7026 mWriteAckSequence &= ~1;
7027 drainSequence = mDrainSequence;
7028 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007029 asyncError = mAsyncError;
7030 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007031 }
7032 {
Andy Hung71742ab2023-07-07 13:47:37 -07007033 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007034 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007035 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007036 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007037 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007038 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007039 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007040 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007041 if (asyncError) {
7042 playbackThread->onAsyncError();
7043 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007044 }
7045 }
7046 }
7047 return false;
7048}
7049
Andy Hung71742ab2023-07-07 13:47:37 -07007050void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007051{
7052 ALOGV("AsyncCallbackThread::exit");
7053 Mutex::Autolock _l(mLock);
7054 requestExit();
7055 mWaitWorkCV.broadcast();
7056}
7057
Andy Hung71742ab2023-07-07 13:47:37 -07007058void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007059{
7060 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007061 // bit 0 is cleared
7062 mWriteAckSequence = sequence << 1;
7063}
7064
Andy Hung71742ab2023-07-07 13:47:37 -07007065void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007066{
7067 Mutex::Autolock _l(mLock);
7068 // ignore unexpected callbacks
7069 if (mWriteAckSequence & 2) {
7070 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007071 mWaitWorkCV.signal();
7072 }
7073}
7074
Andy Hung71742ab2023-07-07 13:47:37 -07007075void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007076{
7077 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007078 // bit 0 is cleared
7079 mDrainSequence = sequence << 1;
7080}
7081
Andy Hung71742ab2023-07-07 13:47:37 -07007082void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007083{
7084 Mutex::Autolock _l(mLock);
7085 // ignore unexpected callbacks
7086 if (mDrainSequence & 2) {
7087 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007088 mWaitWorkCV.signal();
7089 }
7090}
7091
Andy Hung71742ab2023-07-07 13:47:37 -07007092void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007093{
7094 Mutex::Autolock _l(mLock);
7095 mAsyncError = true;
7096 mWaitWorkCV.signal();
7097}
7098
Eric Laurentbfb1b832013-01-07 09:53:42 -08007099
7100// ----------------------------------------------------------------------------
Andy Hung71742ab2023-07-07 13:47:37 -07007101
7102/* static */
7103sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07007104 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07007105 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7106 const audio_offload_info_t& offloadInfo) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007107 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung71742ab2023-07-07 13:47:37 -07007108}
7109
Andy Hung2cbc2722023-07-17 17:05:00 -07007110OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fenn56576722022-10-05 13:42:36 -07007111 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7112 const audio_offload_info_t& offloadInfo)
Andy Hung2cbc2722023-07-17 17:05:00 -07007113 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007114 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007115{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007116 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007117 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007118 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007119}
7120
Andy Hung71742ab2023-07-07 13:47:37 -07007121void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007122{
7123 if (mFlushPending || mHwPaused) {
7124 // If a flush is pending or track was paused, just discard buffered data
7125 flushHw_l();
7126 } else {
7127 mMixerStatus = MIXER_DRAIN_ALL;
7128 threadLoop_drain();
7129 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007130 if (mUseAsyncWrite) {
7131 ALOG_ASSERT(mCallbackThread != 0);
7132 mCallbackThread->exit();
7133 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007134 PlaybackThread::threadLoop_exit();
7135}
7136
Andy Hung71742ab2023-07-07 13:47:37 -07007137PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07007138 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007139)
7140{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007141 size_t count = mActiveTracks.size();
7142
7143 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007144 bool doHwPause = false;
7145 bool doHwResume = false;
7146
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007147 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007148
Eric Laurentbfb1b832013-01-07 09:53:42 -08007149 // find out which tracks need to be processed
Andy Hung3ff4b552023-06-26 19:20:57 -07007150 for (const sp<IAfTrack>& t : mActiveTracks) {
7151 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007152#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007153 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007154#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007155 // Only consider last track started for volume and mixer state control.
7156 // In theory an older track could underrun and restart after the new one starts
7157 // but as we only care about the transition phase between two tracks on a
7158 // direct output, it is not a problem to ignore the underrun case.
Andy Hung3ff4b552023-06-26 19:20:57 -07007159 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007160 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007161
Haynes Mathew George7844f672014-01-15 12:32:55 -08007162 if (track->isInvalid()) {
7163 ALOGW("An invalidated track shouldn't be in active list");
7164 tracksToRemove->add(track);
7165 continue;
7166 }
7167
Andy Hung3ff4b552023-06-26 19:20:57 -07007168 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007169 ALOGW("An idle track shouldn't be in active list");
7170 continue;
7171 }
7172
Kuowei Li23666472021-01-20 10:23:25 +08007173 if (track->isPausePending()) {
7174 track->pauseAck();
7175 // It is possible a track might have been flushed or stopped.
7176 // Other operations such as flush pending might occur on the next prepare.
7177 if (track->isPausing()) {
7178 track->setPaused();
7179 }
7180 // Always perform pause if last, as an immediate flush will change
7181 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007182 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007183 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007184 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007185 mHwPaused = true;
7186 }
7187 // If we were part way through writing the mixbuffer to
7188 // the HAL we must save this until we resume
7189 // BUG - this will be wrong if a different track is made active,
7190 // in that case we want to discard the pending data in the
7191 // mixbuffer and tell the client to present it again when the
7192 // track is resumed
7193 mPausedWriteLength = mCurrentWriteLength;
7194 mPausedBytesRemaining = mBytesRemaining;
7195 mBytesRemaining = 0; // stop writing
7196 }
7197 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007198 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007199 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007200 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007201 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07007202 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007203 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007204 track->flushAck();
7205 if (last) {
7206 mFlushPending = true;
7207 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007208 } else if (track->isResumePending()){
7209 track->resumeAck();
7210 if (last) {
7211 if (mPausedBytesRemaining) {
7212 // Need to continue write that was interrupted
7213 mCurrentWriteLength = mPausedWriteLength;
7214 mBytesRemaining = mPausedBytesRemaining;
7215 mPausedBytesRemaining = 0;
7216 }
7217 if (mHwPaused) {
7218 doHwResume = true;
7219 mHwPaused = false;
7220 // threadLoop_mix() will handle the case that we need to
7221 // resume an interrupted write
7222 }
7223 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007224 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007225
Eric Laurent3df841a2016-07-15 15:15:40 -07007226 mLeftVolFloat = mRightVolFloat = -1.0;
7227
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007228 // Do not handle new data in this iteration even if track->framesReady()
7229 mixerStatus = MIXER_TRACKS_ENABLED;
7230 }
7231 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007232 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007233 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung3ff4b552023-06-26 19:20:57 -07007234 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7235 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007236 if (last) {
7237 // make sure processVolume_l() will apply new volume even if 0
7238 mLeftVolFloat = mRightVolFloat = -1.0;
7239 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007240 }
7241
7242 if (last) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007243 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007244 if (previousTrack != 0) {
7245 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007246 // Flush any data still being written from last track
7247 mBytesRemaining = 0;
7248 if (mPausedBytesRemaining) {
7249 // Last track was paused so we also need to flush saved
7250 // mixbuffer state and invalidate track so that it will
7251 // re-submit that unwritten data when it is next resumed
7252 mPausedBytesRemaining = 0;
7253 // Invalidate is a bit drastic - would be more efficient
7254 // to have a flag to tell client that some of the
7255 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007256 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007257 }
7258 // flush data already sent to the DSP if changing audio session as audio
7259 // comes from a different source. Also invalidate previous track to force a
7260 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007261 if (previousTrack->sessionId() != track->sessionId()) {
7262 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007263 }
7264 }
7265 }
7266 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007267 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007268 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007269 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007270 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07007271 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007272 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007273 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007274 mixerStatus = MIXER_TRACKS_READY;
7275 }
7276 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007277 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007278 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007279 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007280 // Hardware buffer can hold a large amount of audio so we must
7281 // wait for all current track's data to drain before we say
7282 // that the track is stopped.
7283 if (mBytesRemaining == 0) {
7284 // Only start draining when all data in mixbuffer
7285 // has been written
7286 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung3ff4b552023-06-26 19:20:57 -07007287 track->setState(IAfTrackBase::STOPPING_2);
7288 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007289 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7290 if (last && !mStandby) {
7291 // do not modify drain sequence if we are already draining. This happens
7292 // when resuming from pause after drain.
7293 if ((mDrainSequence & 1) == 0) {
7294 mSleepTimeUs = 0;
7295 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7296 mixerStatus = MIXER_DRAIN_TRACK;
7297 mDrainSequence += 2;
7298 }
7299 if (mHwPaused) {
7300 // It is possible to move from PAUSED to STOPPING_1 without
7301 // a resume so we must ensure hardware is running
7302 doHwResume = true;
7303 mHwPaused = false;
7304 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007305 }
7306 }
Eric Laurente93cc032016-05-05 10:15:10 -07007307 } else if (last) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007308 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007309 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007310 }
7311 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007312 // Drain has completed or we are in standby, signal presentation complete
7313 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007314 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007315 mOutput->presentationComplete();
7316 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007317 track->reset();
7318 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007319 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007320 if (!mUseAsyncWrite) {
7321 // If we don't get explicit drain notification we must
7322 // register discontinuity regardless of whether this is
7323 // the previous (!last) or the upcoming (last) track
7324 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007325 mTimestampVerifier.discontinuity(
7326 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007327 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007328 }
7329 } else {
7330 // No buffers for this track. Give it a few chances to
7331 // fill a buffer, then remove it from active list.
Brian Lindahl9e661ad2022-07-27 18:01:07 +02007332 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07007333 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung3ff4b552023-06-26 19:20:57 -07007334 && --(track->retryCount()) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02007335 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung3ff4b552023-06-26 19:20:57 -07007336 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007337 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007338 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7339 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007340 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007341 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007342 // it will then automatically call start() when data is available
7343 track->disable();
7344 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007345 } else if (last){
7346 mixerStatus = MIXER_TRACKS_ENABLED;
7347 }
7348 }
7349 }
7350 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007351 if (track->isReady()) { // check ready to prevent premature start.
7352 processVolume_l(track, last);
7353 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007354 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007355
Eric Laurentea0fade2013-10-04 16:23:48 -07007356 // make sure the pause/flush/resume sequence is executed in the right order.
7357 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7358 // before flush and then resume HW. This can happen in case of pause/flush/resume
7359 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007360 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007361 status_t result = mOutput->stream->pause();
7362 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007363 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007364 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007365 if (mFlushPending) {
7366 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007367 }
Eric Laurentfd477972013-10-25 18:10:40 -07007368 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007369 status_t result = mOutput->stream->resume();
7370 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007371 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007372
Eric Laurentbfb1b832013-01-07 09:53:42 -08007373 // remove all the tracks that need to be...
7374 removeTracks_l(*tracksToRemove);
7375
7376 return mixerStatus;
7377}
7378
Eric Laurentbfb1b832013-01-07 09:53:42 -08007379// must be called with thread mutex locked
Andy Hung71742ab2023-07-07 13:47:37 -07007380bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007381{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007382 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7383 mWriteAckSequence, mDrainSequence);
7384 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007385 return true;
7386 }
7387 return false;
7388}
7389
Andy Hung71742ab2023-07-07 13:47:37 -07007390bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007391{
7392 Mutex::Autolock _l(mLock);
7393 return waitingAsyncCallback_l();
7394}
7395
Andy Hung71742ab2023-07-07 13:47:37 -07007396void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007397{
Eric Laurente659ef42014-09-29 13:06:46 -07007398 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007399 // Flush anything still waiting in the mixbuffer
7400 mCurrentWriteLength = 0;
7401 mBytesRemaining = 0;
7402 mPausedWriteLength = 0;
7403 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007404 // reset bytes written count to reflect that DSP buffers are empty after flush.
7405 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007406
Eric Laurentbfb1b832013-01-07 09:53:42 -08007407 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007408 // discard any pending drain or write ack by incrementing sequence
7409 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7410 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007411 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007412 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7413 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007414 }
7415}
7416
Andy Hung71742ab2023-07-07 13:47:37 -07007417void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007418{
7419 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007420 if (PlaybackThread::invalidateTracks_l(streamType)) {
7421 mFlushPending = true;
7422 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007423}
7424
Andy Hung71742ab2023-07-07 13:47:37 -07007425void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08007426 Mutex::Autolock _l(mLock);
7427 if (PlaybackThread::invalidateTracks_l(portIds)) {
7428 mFlushPending = true;
7429 }
7430}
7431
Eric Laurentbfb1b832013-01-07 09:53:42 -08007432// ----------------------------------------------------------------------------
7433
Andy Hung71742ab2023-07-07 13:47:37 -07007434/* static */
7435sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung2cbc2722023-07-17 17:05:00 -07007436 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07007437 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007438 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -07007439}
7440
Andy Hung2cbc2722023-07-17 17:05:00 -07007441DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung44f27182023-07-06 20:56:16 -07007442 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -07007443 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007444 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007445 mWaitTimeMs(UINT_MAX)
7446{
7447 addOutputTrack(mainThread);
7448}
7449
Andy Hung71742ab2023-07-07 13:47:37 -07007450DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007451{
7452 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7453 mOutputTracks[i]->destroy();
7454 }
7455}
7456
Andy Hung71742ab2023-07-07 13:47:37 -07007457void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007458{
7459 // mix buffers...
Andy Hung71ba4b32022-10-06 12:09:49 -07007460 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007461 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007462 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007463 if (mMixerBufferValid) {
7464 memset(mMixerBuffer, 0, mMixerBufferSize);
7465 } else {
7466 memset(mSinkBuffer, 0, mSinkBufferSize);
7467 }
Eric Laurent81784c32012-11-19 14:55:58 -08007468 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007469 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007470 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007471 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007472 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007473}
7474
Andy Hung71742ab2023-07-07 13:47:37 -07007475void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007476{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007477 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007478 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007479 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007480 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007481 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007482 }
7483 } else if (mBytesWritten != 0) {
7484 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7485 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007486 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007487 } else {
7488 // flush remaining overflow buffers in output tracks
7489 writeFrames = 0;
7490 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007491 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007492 }
7493}
7494
Andy Hung71742ab2023-07-07 13:47:37 -07007495ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007496{
7497 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007498 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7499
7500 // Consider the first OutputTrack for timestamp and frame counting.
7501
7502 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7503 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7504 // we always claim success.
7505 if (i == 0) {
7506 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7507 ALOGD_IF(correction != 0 && writeFrames != 0,
7508 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7509 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7510 mFramesWritten -= correction;
7511 }
7512
7513 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007514 }
Andy Hungcf10d742020-04-28 15:38:24 -07007515 if (mStandby) {
7516 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007517 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007518 mStandby = false;
7519 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007520 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007521}
7522
Andy Hung71742ab2023-07-07 13:47:37 -07007523void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007524{
7525 // DuplicatingThread implements standby by stopping all tracks
7526 for (size_t i = 0; i < outputTracks.size(); i++) {
7527 outputTracks[i]->stop();
7528 }
7529}
7530
Andy Hung71742ab2023-07-07 13:47:37 -07007531void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007532{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007533 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007534
7535 std::stringstream ss;
7536 const size_t numTracks = mOutputTracks.size();
7537 ss << " " << numTracks << " OutputTracks";
7538 if (numTracks > 0) {
7539 ss << ":";
7540 for (const auto &track : mOutputTracks) {
Andy Hung44f27182023-07-06 20:56:16 -07007541 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007542 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007543 if (thread.get() != nullptr) {
7544 ss << thread.get() << ", " << thread->id();
7545 } else {
7546 ss << "null";
7547 }
7548 ss << ")";
7549 }
7550 }
7551 ss << "\n";
7552 std::string result = ss.str();
7553 write(fd, result.c_str(), result.size());
7554}
7555
Andy Hung71742ab2023-07-07 13:47:37 -07007556void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007557{
7558 outputTracks = mOutputTracks;
7559}
7560
Andy Hung71742ab2023-07-07 13:47:37 -07007561void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007562{
7563 outputTracks.clear();
7564}
7565
Andy Hung71742ab2023-07-07 13:47:37 -07007566void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007567{
7568 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007569 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7570 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7571 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7572 const size_t frameCount =
7573 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7574 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7575 // from different OutputTracks and their associated MixerThreads (e.g. one may
7576 // nearly empty and the other may be dropping data).
7577
Svet Ganov33761132021-05-13 22:51:08 +00007578 // TODO b/182392769: use attribution source util, move to server edge
7579 AttributionSourceState attributionSource = AttributionSourceState();
7580 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007581 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007582 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007583 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007584 attributionSource.token = sp<BBinder>::make();
Andy Hung3ff4b552023-06-26 19:20:57 -07007585 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007586 this,
7587 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007588 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007589 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007590 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007591 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007592 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7593 if (status != NO_ERROR) {
7594 ALOGE("addOutputTrack() initCheck failed %d", status);
7595 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007596 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007597 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7598 mOutputTracks.add(outputTrack);
7599 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7600 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007601}
7602
Andy Hung71742ab2023-07-07 13:47:37 -07007603void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007604{
7605 Mutex::Autolock _l(mLock);
7606 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7607 if (mOutputTracks[i]->thread() == thread) {
7608 mOutputTracks[i]->destroy();
7609 mOutputTracks.removeAt(i);
7610 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007611 if (thread->getOutput() == mOutput) {
7612 mOutput = NULL;
7613 }
Eric Laurent81784c32012-11-19 14:55:58 -08007614 return;
7615 }
7616 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007617 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007618}
7619
7620// caller must hold mLock
Andy Hung71742ab2023-07-07 13:47:37 -07007621void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007622{
7623 mWaitTimeMs = UINT_MAX;
7624 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung44f27182023-07-06 20:56:16 -07007625 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007626 if (strong != 0) {
7627 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7628 if (waitTimeMs < mWaitTimeMs) {
7629 mWaitTimeMs = waitTimeMs;
7630 }
7631 }
7632 }
7633}
7634
Andy Hung71742ab2023-07-07 13:47:37 -07007635bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007636{
7637 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung44f27182023-07-06 20:56:16 -07007638 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007639 if (thread == 0) {
7640 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7641 outputTracks[i].get());
7642 return false;
7643 }
Andy Hung44f27182023-07-06 20:56:16 -07007644 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007645 // see note at standby() declaration
Andy Hung4989d312023-06-29 21:19:25 -07007646 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007647 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7648 thread.get());
7649 return false;
7650 }
7651 }
7652 return true;
7653}
7654
Andy Hung71742ab2023-07-07 13:47:37 -07007655void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007656 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007657{
Kevin Rocard12381092018-04-11 09:19:59 -07007658 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7659 outputTrack->setMetadatas(metadata.tracks);
7660 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007661}
7662
Andy Hung71742ab2023-07-07 13:47:37 -07007663uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007664{
7665 return (mWaitTimeMs * 1000) / 2;
7666}
7667
Andy Hung71742ab2023-07-07 13:47:37 -07007668void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007669{
7670 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7671 updateWaitTime_l();
7672
7673 MixerThread::cacheParameters_l();
7674}
7675
Eric Laurentb3f315a2021-07-13 15:09:05 +02007676// ----------------------------------------------------------------------------
7677
Andy Hung71742ab2023-07-07 13:47:37 -07007678/* static */
7679sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07007680 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07007681 AudioStreamOut* output,
7682 audio_io_handle_t id,
7683 bool systemReady,
7684 audio_config_base_t* mixerConfig) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007685 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hung71742ab2023-07-07 13:47:37 -07007686}
7687
Andy Hung2cbc2722023-07-17 17:05:00 -07007688SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007689 AudioStreamOut* output,
7690 audio_io_handle_t id,
7691 bool systemReady,
7692 audio_config_base_t *mixerConfig)
Andy Hung2cbc2722023-07-17 17:05:00 -07007693 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007694{
7695}
7696
Andy Hung71742ab2023-07-07 13:47:37 -07007697void SpatializerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01007698 MixerThread::onFirstRef();
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007699
Andy Hung41ccf7f2022-12-14 14:25:49 -08007700 const pid_t tid = getTid();
7701 if (tid == -1) {
7702 // Unusual: PlaybackThread::onFirstRef() should set the threadLoop running.
7703 ALOGW("%s: Cannot update Spatializer mixer thread priority, not running", __func__);
7704 } else {
7705 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
7706 if (priorityBoost > 0) {
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007707 stream()->setHalThreadPriority(priorityBoost);
7708 }
7709 }
Eric Laurent6f9534f2022-05-03 18:15:04 +02007710}
7711
Andy Hung71742ab2023-07-07 13:47:37 -07007712void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent6f9534f2022-05-03 18:15:04 +02007713 // if mSupportedLatencyModes is empty, the HAL stream does not support
7714 // latency mode control and we can exit.
7715 if (mSupportedLatencyModes.empty()) {
7716 return;
7717 }
7718 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7719 if (mSupportedLatencyModes.size() == 1) {
7720 // If the HAL only support one latency mode currently, confirm the choice
7721 latencyMode = mSupportedLatencyModes[0];
7722 } else if (mSupportedLatencyModes.size() > 1) {
7723 // Request low latency if:
7724 // - The low latency mode is requested by the spatializer controller
7725 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7726 // AND
7727 // - At least one active track is spatialized
7728 bool hasSpatializedActiveTrack = false;
7729 for (const auto& track : mActiveTracks) {
7730 if (track->isSpatialized()) {
7731 hasSpatializedActiveTrack = true;
7732 break;
7733 }
7734 }
7735 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7736 latencyMode = AUDIO_LATENCY_MODE_LOW;
7737 }
7738 }
7739
7740 if (latencyMode != mSetLatencyMode) {
7741 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007742 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7743 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent6f9534f2022-05-03 18:15:04 +02007744 if (status == NO_ERROR) {
7745 mSetLatencyMode = latencyMode;
7746 }
7747 }
7748}
7749
Andy Hung71742ab2023-07-07 13:47:37 -07007750status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent6f9534f2022-05-03 18:15:04 +02007751 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7752 return BAD_VALUE;
7753 }
7754 Mutex::Autolock _l(mLock);
7755 mRequestedLatencyMode = mode;
7756 return NO_ERROR;
7757}
7758
Andy Hung71742ab2023-07-07 13:47:37 -07007759void SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007760{
7761 bool hasVirtualizer = false;
7762 bool hasDownMixer = false;
Andy Hungbd72c542023-06-20 18:56:17 -07007763 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007764 {
7765 Mutex::Autolock _l(mLock);
Andy Hungbd72c542023-06-20 18:56:17 -07007766 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007767 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007768 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007769 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7770 }
7771
7772 finalDownMixer = mFinalDownMixer;
7773 mFinalDownMixer.clear();
7774 }
7775
7776 if (hasVirtualizer) {
7777 if (finalDownMixer != nullptr) {
7778 int32_t ret;
Andy Hungbd72c542023-06-20 18:56:17 -07007779 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007780 }
7781 finalDownMixer.clear();
7782 } else if (!hasDownMixer) {
7783 std::vector<effect_descriptor_t> descriptors;
Andy Hung2cbc2722023-07-17 17:05:00 -07007784 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007785 EFFECT_UIID_DOWNMIX, &descriptors);
7786 if (status != NO_ERROR) {
7787 return;
7788 }
7789 ALOG_ASSERT(!descriptors.empty(),
7790 "%s getDescriptors() returned no error but empty list", __func__);
7791
7792 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7793 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007794 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007795
7796 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7797 ALOGW("%s error creating downmixer %d", __func__, status);
7798 finalDownMixer.clear();
7799 } else {
7800 int32_t ret;
Andy Hungbd72c542023-06-20 18:56:17 -07007801 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007802 }
7803 }
7804
7805 {
7806 Mutex::Autolock _l(mLock);
7807 mFinalDownMixer = finalDownMixer;
7808 }
7809}
7810
Eric Laurent81784c32012-11-19 14:55:58 -08007811// ----------------------------------------------------------------------------
7812// Record
7813// ----------------------------------------------------------------------------
7814
Andy Hung2cbc2722023-07-17 17:05:00 -07007815sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung44f27182023-07-06 20:56:16 -07007816 AudioStreamIn* input,
7817 audio_io_handle_t id,
7818 bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007819 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung44f27182023-07-06 20:56:16 -07007820}
7821
Andy Hung2cbc2722023-07-17 17:05:00 -07007822RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007823 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007824 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007825 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007826 ) :
Andy Hung2cbc2722023-07-17 17:05:00 -07007827 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007828 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007829 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007830 mActiveTracks(&this->mLocalLog),
7831 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007832 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007833 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007834 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7835 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007836 // mFastCapture below
7837 , mFastCaptureFutex(0)
7838 // mInputSource
7839 // mPipeSink
7840 // mPipeSource
7841 , mPipeFramesP2(0)
7842 // mPipeMemory
7843 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007844 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007845 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007846{
Glenn Kastend7dca052015-03-05 16:05:54 -08007847 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung2cbc2722023-07-17 17:05:00 -07007848 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007849
George Burgess IVa8f90c12020-05-14 11:27:19 -07007850 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007851 mIsMsdDevice = strcmp(
7852 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7853 }
7854
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007855 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007856
Andy Hungc8fddf32018-08-08 18:32:37 -07007857 // TODO: We may also match on address as well as device type for
7858 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007859 // TODO: This property should be ensure that only contains one single device type.
7860 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7861 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007862 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7863 : AUDIO_DEVICE_NONE));
7864
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007865 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007866 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007867 size_t numCounterOffers = 0;
7868 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007869#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007870 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007871#else
7872 (void)
7873#endif
7874 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007875 ALOG_ASSERT(index == 0);
7876
7877 // initialize fast capture depending on configuration
7878 bool initFastCapture;
7879 switch (kUseFastCapture) {
7880 case FastCapture_Never:
7881 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007882 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007883 break;
7884 case FastCapture_Always:
7885 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007886 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007887 break;
7888 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007889 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
7890 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7891 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d "
7892 "mIsMsdDevice = %d", this, (long long)mFrameCount, mSampleRate,
7893 kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007894 break;
7895 // case FastCapture_Dynamic:
7896 }
7897
7898 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007899 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007900 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007901 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7902 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007903 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007904 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007905 const sp<MemoryDealer> roHeap(readOnlyHeap());
7906 sp<IMemory> pipeMemory;
7907 if ((roHeap == 0) ||
7908 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007909 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007910 ALOGE("not enough memory for pipe buffer size=%zu; "
7911 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7912 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7913 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007914 goto failed;
7915 }
7916 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7917 memset(pipeBuffer, 0, pipeSize);
7918 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07007919 const NBAIO_Format offersFast[1] = {format};
7920 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007921 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung71ba4b32022-10-06 12:09:49 -07007922 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007923 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007924 mPipeSink = pipe;
7925 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung71ba4b32022-10-06 12:09:49 -07007926 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007927 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung71ba4b32022-10-06 12:09:49 -07007928 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007929 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007930 mPipeSource = pipeReader;
7931 mPipeFramesP2 = pipeFramesP2;
7932 mPipeMemory = pipeMemory;
7933
7934 // create fast capture
7935 mFastCapture = new FastCapture();
7936 FastCaptureStateQueue *sq = mFastCapture->sq();
7937#ifdef STATE_QUEUE_DUMP
7938 // FIXME
7939#endif
7940 FastCaptureState *state = sq->begin();
7941 state->mCblk = NULL;
7942 state->mInputSource = mInputSource.get();
7943 state->mInputSourceGen++;
7944 state->mPipeSink = pipe;
7945 state->mPipeSinkGen++;
7946 state->mFrameCount = mFrameCount;
7947 state->mCommand = FastCaptureState::COLD_IDLE;
7948 // already done in constructor initialization list
7949 //mFastCaptureFutex = 0;
7950 state->mColdFutexAddr = &mFastCaptureFutex;
7951 state->mColdGen++;
7952 state->mDumpState = &mFastCaptureDumpState;
7953#ifdef TEE_SINK
7954 // FIXME
7955#endif
Andy Hung2cbc2722023-07-17 17:05:00 -07007956 mFastCaptureNBLogWriter =
7957 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007958 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7959 sq->end();
7960 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7961
7962 // start the fast capture
7963 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7964 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007965 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007966 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007967#ifdef AUDIO_WATCHDOG
7968 // FIXME
7969#endif
7970
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007971 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007972 }
Andy Hung8946a282018-04-19 20:04:56 -07007973#ifdef TEE_SINK
7974 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7975 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7976#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007977failed: ;
7978
7979 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007980}
7981
Andy Hung71742ab2023-07-07 13:47:37 -07007982RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007983{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007984 if (mFastCapture != 0) {
7985 FastCaptureStateQueue *sq = mFastCapture->sq();
7986 FastCaptureState *state = sq->begin();
7987 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7988 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7989 if (old == -1) {
7990 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7991 }
7992 }
7993 state->mCommand = FastCaptureState::EXIT;
7994 sq->end();
7995 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7996 mFastCapture->join();
7997 mFastCapture.clear();
7998 }
Andy Hung2cbc2722023-07-17 17:05:00 -07007999 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8000 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008001 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008002}
8003
Andy Hung71742ab2023-07-07 13:47:37 -07008004void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008005{
Glenn Kastend7dca052015-03-05 16:05:54 -08008006 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008007}
8008
Andy Hung71742ab2023-07-07 13:47:37 -07008009void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008010{
8011 ALOGV(" preExit()");
8012 Mutex::Autolock _l(mLock);
8013 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008014 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008015 track->invalidate();
8016 }
8017 mActiveTracks.clear();
8018 mStartStopCond.broadcast();
8019}
8020
Andy Hung71742ab2023-07-07 13:47:37 -07008021bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008022{
Eric Laurent81784c32012-11-19 14:55:58 -08008023 nsecs_t lastWarning = 0;
8024
8025 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008026
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008027reacquire_wakelock:
Andy Hung3ff4b552023-06-26 19:20:57 -07008028 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008029 {
8030 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07008031 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008032 }
8033
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008034 // used to request a deferred sleep, to be executed later while mutex is unlocked
8035 uint32_t sleepUs = 0;
8036
Andy Hung446f4df2019-02-21 12:26:41 -08008037 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8038
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008039 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008040 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hungbd72c542023-06-20 18:56:17 -07008041 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008042
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008043 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung3ff4b552023-06-26 19:20:57 -07008044 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008045
Glenn Kasten735f45f2014-08-18 15:51:59 -07008046 // reference to the (first and only) active fast track
Andy Hung3ff4b552023-06-26 19:20:57 -07008047 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008048
Glenn Kasten735f45f2014-08-18 15:51:59 -07008049 // reference to a fast track which is about to be removed
Andy Hung3ff4b552023-06-26 19:20:57 -07008050 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008051
Eric Laurent33403f02020-05-29 18:35:06 -07008052 bool silenceFastCapture = false;
8053
Eric Laurent81784c32012-11-19 14:55:58 -08008054 { // scope for mLock
8055 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08008056
Eric Laurent021cf962014-05-13 10:18:14 -07008057 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008058
Eric Laurent000a4192014-01-29 15:17:32 -08008059 // check exitPending here because checkForNewParameters_l() and
8060 // checkForNewParameters_l() can temporarily release mLock
8061 if (exitPending()) {
8062 break;
8063 }
8064
Eric Laurent5c25d562016-07-13 17:17:45 -07008065 // sleep with mutex unlocked
8066 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008067 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07008068 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
8069 ATRACE_END();
8070 sleepUs = 0;
8071 continue;
8072 }
8073
Glenn Kasten2b806402013-11-20 16:37:38 -08008074 // if no active track(s), then standby and release wakelock
8075 size_t size = mActiveTracks.size();
8076 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008077 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008078 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008079 releaseWakeLock_l();
8080 ALOGV("RecordThread: loop stopping");
8081 // go to sleep
8082 mWaitWorkCV.wait(mLock);
8083 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008084 goto reacquire_wakelock;
8085 }
8086
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008087 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008088 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008089 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008090
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008091 activeTrack = mActiveTracks[i];
8092 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008093 if (activeTrack->isFastTrack()) {
8094 ALOG_ASSERT(fastTrackToRemove == 0);
8095 fastTrackToRemove = activeTrack;
8096 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008097 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008098 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008099 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008100 continue;
8101 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008102
Andy Hung3ff4b552023-06-26 19:20:57 -07008103 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008104 switch (activeTrackState) {
8105
Andy Hung3ff4b552023-06-26 19:20:57 -07008106 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008107 mActiveTracks.remove(activeTrack);
Andy Hung3ff4b552023-06-26 19:20:57 -07008108 activeTrack->setState(IAfTrackBase::PAUSED);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008109 doBroadcast = true;
8110 size--;
8111 continue;
8112
Andy Hung3ff4b552023-06-26 19:20:57 -07008113 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008114 sleepUs = 10000;
8115 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008116 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008117 continue;
8118
Andy Hung3ff4b552023-06-26 19:20:57 -07008119 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008120 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008121 if (mStandby) {
8122 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008123 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008124 mStandby = false;
8125 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008126 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008127 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008128 break;
8129
Andy Hung3ff4b552023-06-26 19:20:57 -07008130 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008131 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008132 break;
8133
Andy Hung3ff4b552023-06-26 19:20:57 -07008134 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8135 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8136 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008137 default:
Andy Hungce685402018-10-05 17:23:27 -07008138 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8139 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008140 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008141
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008142 if (activeTrack->isFastTrack()) {
8143 ALOG_ASSERT(!mFastTrackAvail);
8144 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008145 // if the active fast track is silenced either:
8146 // 1) silence the whole capture from fast capture buffer if this is
8147 // the only active track
8148 // 2) invalidate this track: this will cause the client to reconnect and possibly
8149 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008150 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008151 if (activeTrack->isSilenced()) {
8152 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008153 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008154 } else {
8155 silenceFastCapture = true;
8156 }
8157 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008158 // Invalidate fast tracks if access to audio history is required as this is not
8159 // possible with fast tracks. Once the fast track has been invalidated, no new
8160 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8161 if (mMaxSharedAudioHistoryMs != 0) {
8162 invalidate = true;
8163 }
8164 if (invalidate) {
8165 activeTrack->invalidate();
8166 ALOG_ASSERT(fastTrackToRemove == 0);
8167 fastTrackToRemove = activeTrack;
8168 removeTrack_l(activeTrack);
8169 mActiveTracks.remove(activeTrack);
8170 size--;
8171 continue;
8172 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008173 fastTrack = activeTrack;
8174 }
Eric Laurent33403f02020-05-29 18:35:06 -07008175
8176 activeTracks.add(activeTrack);
8177 i++;
8178
Glenn Kasten9e982352013-08-14 14:39:50 -07008179 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008180
Andy Hungdae27702016-10-31 14:01:16 -07008181 mActiveTracks.updatePowerState(this);
8182
Kevin Rocard069c2712018-03-29 19:09:14 -07008183 updateMetadata_l();
8184
Eric Laurent5c25d562016-07-13 17:17:45 -07008185 if (allStopped) {
8186 standbyIfNotAlreadyInStandby();
8187 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008188 if (doBroadcast) {
8189 mStartStopCond.broadcast();
8190 }
8191
8192 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008193 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008194 if (sleepUs == 0) {
8195 sleepUs = kRecordThreadSleepUs;
8196 }
8197 continue;
8198 }
8199 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008200
Eric Laurent81784c32012-11-19 14:55:58 -08008201 lockEffectChains_l(effectChains);
8202 }
8203
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008204 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008205
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008206 size_t size = effectChains.size();
8207 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008208 // thread mutex is not locked, but effect chain is locked
8209 effectChains[i]->process_l();
8210 }
8211
Glenn Kasten735f45f2014-08-18 15:51:59 -07008212 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008213 if (mFastCapture != 0) {
8214 FastCaptureStateQueue *sq = mFastCapture->sq();
8215 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008216 bool didModify = false;
8217 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008218 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8219 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8220 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8221 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8222 if (old == -1) {
8223 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8224 }
8225 }
8226 state->mCommand = FastCaptureState::READ_WRITE;
8227#if 0 // FIXME
Andy Hung2cbc2722023-07-17 17:05:00 -07008228 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008229 FastThreadDumpState::kSamplingNforLowRamDevice :
8230 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008231#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008232 didModify = true;
8233 }
8234 audio_track_cblk_t *cblkOld = state->mCblk;
8235 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8236 if (cblkNew != cblkOld) {
8237 state->mCblk = cblkNew;
8238 // block until acked if removing a fast track
8239 if (cblkOld != NULL) {
8240 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8241 }
8242 didModify = true;
8243 }
jiabin01c8f562018-07-19 17:47:28 -07008244 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8245 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8246 if (state->mFastPatchRecordBufferProvider != abp) {
8247 state->mFastPatchRecordBufferProvider = abp;
8248 state->mFastPatchRecordFormat = fastTrack == 0 ?
8249 AUDIO_FORMAT_INVALID : fastTrack->format();
8250 didModify = true;
8251 }
Eric Laurent33403f02020-05-29 18:35:06 -07008252 if (state->mSilenceCapture != silenceFastCapture) {
8253 state->mSilenceCapture = silenceFastCapture;
8254 didModify = true;
8255 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008256 sq->end(didModify);
8257 if (didModify) {
8258 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008259#if 0
8260 if (kUseFastCapture == FastCapture_Dynamic) {
8261 mNormalSource = mPipeSource;
8262 }
8263#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008264 }
8265 }
8266
Glenn Kasten735f45f2014-08-18 15:51:59 -07008267 // now run the fast track destructor with thread mutex unlocked
8268 fastTrackToRemove.clear();
8269
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008270 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8271 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8272 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8273 // If destination is non-contiguous, first read past the nominal end of buffer, then
8274 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008275
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008276 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung71ba4b32022-10-06 12:09:49 -07008277 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008278 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008279
8280 // If an NBAIO source is present, use it to read the normal capture's data
8281 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008282 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008283
8284 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8285 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8286 // we immediately retry the read() to get data and prevent another overflow.
8287 for (int retries = 0; retries <= 2; ++retries) {
8288 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8289 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8290 framesToRead);
8291 if (framesRead != OVERRUN) break;
8292 }
8293
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008294 const ssize_t availableToRead = mPipeSource->availableToRead();
8295 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008296 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008297 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008298 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8299 "more frames to read than fifo size, %zd > %zu",
8300 availableToRead, mPipeFramesP2);
8301 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8302 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8303 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8304 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008305 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8306 }
8307 if (framesRead < 0) {
8308 status_t status = (status_t) framesRead;
8309 switch (status) {
8310 case OVERRUN:
8311 ALOGW("overrun on read from pipe");
8312 framesRead = 0;
8313 break;
8314 case NEGOTIATE:
8315 ALOGE("re-negotiation is needed");
8316 framesRead = -1; // Will cause an attempt to recover.
8317 break;
8318 default:
8319 ALOGE("unknown error %d on read from pipe", status);
8320 break;
8321 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008322 }
8323 // otherwise use the HAL / AudioStreamIn directly
8324 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008325 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008326 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008327 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008328 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008329 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008330 if (result < 0) {
8331 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008332 } else {
8333 framesRead = bytesRead / mFrameSize;
8334 }
8335 }
8336
Andy Hung446f4df2019-02-21 12:26:41 -08008337 const int64_t lastIoEndNs = systemTime(); // end IO timing
8338
Andy Hung3f0c9022016-01-15 17:49:46 -08008339 // Update server timestamp with server stats
8340 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008341 if (framesRead >= 0) {
8342 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8343 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8344 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008345
8346 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008347 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008348 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008349 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008350 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8351 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8352 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008353 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008354 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8355
8356 mTimestampVerifier.add(position, time, mSampleRate);
8357
8358 // Correct timestamps
8359 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008360 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008361 id(), (long long)time, (long long)position);
8362 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8363 position = correctedTimestamp.mFrames;
8364 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008365 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008366 id(), (long long)time, (long long)position);
8367 }
8368
Andy Hung3f0c9022016-01-15 17:49:46 -08008369 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8370 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8371 // Note: In general record buffers should tend to be empty in
8372 // a properly running pipeline.
8373 //
8374 // Also, it is not advantageous to call get_presentation_position during the read
8375 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008376 } else {
8377 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008378 }
8379 }
Andy Hunge6c37112019-02-26 17:38:10 -08008380
8381 // From the timestamp, input read latency is negative output write latency.
8382 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung3ff4b552023-06-26 19:20:57 -07008383 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008384 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8385 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8386 mLatencyMs.add(latencyMs);
8387 }
8388
Andy Hung3f0c9022016-01-15 17:49:46 -08008389 // Use this to track timestamp information
8390 // ALOGD("%s", mTimestamp.toString().c_str());
8391
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008392 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008393 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008394 // Force input into standby so that it tries to recover at next read attempt
8395 inputStandBy();
8396 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008397 }
8398 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008399 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008400 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008401 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008402 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008403
Andy Hung8946a282018-04-19 20:04:56 -07008404#ifdef TEE_SINK
8405 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8406#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008407 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008408 {
8409 size_t part1 = mRsmpInFramesP2 - rear;
8410 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008411 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008412 (framesRead - part1) * mFrameSize);
8413 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008414 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008415 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008416
8417 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008418
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008419 // loop over each active track
8420 for (size_t i = 0; i < size; i++) {
8421 activeTrack = activeTracks[i];
8422
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008423 // skip fast tracks, as those are handled directly by FastCapture
8424 if (activeTrack->isFastTrack()) {
8425 continue;
8426 }
8427
Andy Hung73c02e42015-03-29 01:13:58 -07008428 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008429 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8430
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008431 enum {
8432 OVERRUN_UNKNOWN,
8433 OVERRUN_TRUE,
8434 OVERRUN_FALSE
8435 } overrun = OVERRUN_UNKNOWN;
8436
8437 // loop over getNextBuffer to handle circular sink
8438 for (;;) {
8439
Andy Hung3ff4b552023-06-26 19:20:57 -07008440 activeTrack->sinkBuffer().frameCount = ~0;
8441 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8442 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008443 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8444
Andy Hung73c02e42015-03-29 01:13:58 -07008445 // check available frames and handle overrun conditions
8446 // if the record track isn't draining fast enough.
8447 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008448 size_t framesIn;
Andy Hung3ff4b552023-06-26 19:20:57 -07008449 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008450 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008451 overrun = OVERRUN_TRUE;
8452 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008453 if (framesOut == 0 || framesIn == 0) {
8454 break;
8455 }
8456
Andy Hung6770c6f2015-04-07 13:43:36 -07008457 // Don't allow framesOut to be larger than what is possible with resampling
8458 // from framesIn.
8459 // This isn't strictly necessary but helps limit buffer resizing in
8460 // RecordBufferConverter. TODO: remove when no longer needed.
8461 framesOut = min(framesOut,
8462 destinationFramesPossible(
Andy Hung3ff4b552023-06-26 19:20:57 -07008463 framesIn, mSampleRate, activeTrack->sampleRate()));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008464
8465 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008466 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008467 // straight from RecordThread buffer to RecordTrack buffer.
8468 AudioBufferProvider::Buffer buffer;
8469 buffer.frameCount = framesOut;
Andy Hung71ba4b32022-10-06 12:09:49 -07008470 const status_t getNextBufferStatus =
Andy Hung3ff4b552023-06-26 19:20:57 -07008471 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07008472 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008473 ALOGV_IF(buffer.frameCount != framesOut,
8474 "%s() read less than expected (%zu vs %zu)",
8475 __func__, buffer.frameCount, framesOut);
8476 framesOut = buffer.frameCount;
Andy Hung3ff4b552023-06-26 19:20:57 -07008477 memcpy(activeTrack->sinkBuffer().raw,
8478 buffer.raw, buffer.frameCount * mFrameSize);
8479 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008480 } else {
8481 framesOut = 0;
8482 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung71ba4b32022-10-06 12:09:49 -07008483 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008484 }
8485 } else {
8486 // process frames from the RecordThread buffer provider to the RecordTrack
8487 // buffer
Andy Hung3ff4b552023-06-26 19:20:57 -07008488 framesOut = activeTrack->recordBufferConverter()->convert(
8489 activeTrack->sinkBuffer().raw,
8490 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008491 framesOut);
8492 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008493
8494 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8495 overrun = OVERRUN_FALSE;
8496 }
8497
Andy Hung93bb5732023-05-04 21:16:34 -07008498 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8499 const ssize_t framesToDrop =
Andy Hung3ff4b552023-06-26 19:20:57 -07008500 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008501 if (framesToDrop == 0) {
8502 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008503 if (framesOut > 0) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008504 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008505 // Sanitize before releasing if the track has no access to the source data
8506 // An idle UID receives silence from non virtual devices until active
8507 if (activeTrack->isSilenced()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008508 memset(activeTrack->sinkBuffer().raw,
8509 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008510 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008511 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008512 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008513 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008514 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008515 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008516 }
8517 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008518
8519 switch (overrun) {
8520 case OVERRUN_TRUE:
8521 // client isn't retrieving buffers fast enough
8522 if (!activeTrack->setOverflow()) {
8523 nsecs_t now = systemTime();
8524 // FIXME should lastWarning per track?
8525 if ((now - lastWarning) > kWarningThrottleNs) {
8526 ALOGW("RecordThread: buffer overflow");
8527 lastWarning = now;
8528 }
8529 }
8530 break;
8531 case OVERRUN_FALSE:
8532 activeTrack->clearOverflow();
8533 break;
8534 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008535 break;
8536 }
8537
Andy Hung3f0c9022016-01-15 17:49:46 -08008538 // update frame information and push timestamp out
8539 activeTrack->updateTrackFrameInfo(
Andy Hung3ff4b552023-06-26 19:20:57 -07008540 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008541 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8542 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008543 }
8544
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008545unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008546 // enable changes in effect chain
8547 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008548 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008549 if (audio_has_proportional_frames(mFormat)
8550 && loopCount == lastLoopCountRead + 1) {
8551 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8552 const double jitterMs =
8553 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8554 {framesRead, readPeriodNs},
8555 {0, 0} /* lastTimestamp */, mSampleRate);
8556 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8557
8558 Mutex::Autolock _l(mLock);
8559 mIoJitterMs.add(jitterMs);
8560 mProcessTimeMs.add(processMs);
8561 }
8562 // update timing info.
8563 mLastIoBeginNs = lastIoBeginNs;
8564 mLastIoEndNs = lastIoEndNs;
8565 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008566 }
8567
Glenn Kasten93e471f2013-08-19 08:40:07 -07008568 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008569
8570 {
8571 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008572 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008573 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008574 track->invalidate();
8575 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008576 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008577 mStartStopCond.broadcast();
8578 }
8579
8580 releaseWakeLock();
8581
8582 ALOGV("RecordThread %p exiting", this);
8583 return false;
8584}
8585
Andy Hung71742ab2023-07-07 13:47:37 -07008586void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008587{
8588 if (!mStandby) {
8589 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008590 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008591 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008592 mStandby = true;
8593 }
8594}
8595
Andy Hung71742ab2023-07-07 13:47:37 -07008596void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008597{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008598 // Idle the fast capture if it's currently running
8599 if (mFastCapture != 0) {
8600 FastCaptureStateQueue *sq = mFastCapture->sq();
8601 FastCaptureState *state = sq->begin();
8602 if (!(state->mCommand & FastCaptureState::IDLE)) {
8603 state->mCommand = FastCaptureState::COLD_IDLE;
8604 state->mColdFutexAddr = &mFastCaptureFutex;
8605 state->mColdGen++;
8606 mFastCaptureFutex = 0;
8607 sq->end();
8608 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8609 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8610#if 0
8611 if (kUseFastCapture == FastCapture_Dynamic) {
8612 // FIXME
8613 }
8614#endif
8615#ifdef AUDIO_WATCHDOG
8616 // FIXME
8617#endif
8618 } else {
8619 sq->end(false /*didModify*/);
8620 }
8621 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008622 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008623 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008624
8625 // If going into standby, flush the pipe source.
8626 if (mPipeSource.get() != nullptr) {
8627 const ssize_t flushed = mPipeSource->flush();
8628 if (flushed > 0) {
8629 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8630 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8631 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8632 }
8633 }
Eric Laurent81784c32012-11-19 14:55:58 -08008634}
8635
Glenn Kasten05997e22014-03-13 15:08:33 -07008636// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07008637sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hungd65869f2023-06-27 17:05:02 -07008638 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008639 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008640 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008641 audio_format_t format,
8642 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008643 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008644 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008645 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008646 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008647 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008648 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008649 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008650 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008651 audio_port_handle_t portId,
8652 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008653{
Glenn Kasten74935e42013-12-19 08:56:45 -08008654 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008655 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung3ff4b552023-06-26 19:20:57 -07008656 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008657 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008658 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008659 audio_input_flags_t requestedFlags = *flags;
8660 uint32_t sampleRate;
8661
8662 lStatus = initCheck();
8663 if (lStatus != NO_ERROR) {
8664 ALOGE("createRecordTrack_l() audio driver not initialized");
8665 goto Exit;
8666 }
8667
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008668 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8669 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8670 lStatus = BAD_VALUE;
8671 goto Exit;
8672 }
8673
Eric Laurentec376dc2021-04-08 20:41:22 +02008674 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008675 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008676 lStatus = PERMISSION_DENIED;
8677 goto Exit;
8678 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008679 if (maxSharedAudioHistoryMs < 0
8680 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8681 lStatus = BAD_VALUE;
8682 goto Exit;
8683 }
8684 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008685 if (*pSampleRate == 0) {
8686 *pSampleRate = mSampleRate;
8687 }
8688 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008689
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008690 // special case for FAST flag considered OK if fast capture is present and access to
8691 // audio history is not required
8692 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008693 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8694 }
8695
Eric Laurentf14db3c2017-12-08 14:20:36 -08008696 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008697 if ((*flags & inputFlags) != *flags) {
8698 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8699 " input flags (%08x)",
8700 *flags, inputFlags);
8701 *flags = (audio_input_flags_t)(*flags & inputFlags);
8702 }
Eric Laurent81784c32012-11-19 14:55:58 -08008703
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008704 // client expresses a preference for FAST and no access to audio history,
8705 // but we get the final say
8706 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008707 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008708 // we formerly checked for a callback handler (non-0 tid),
8709 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008710 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008711 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008712 // Frame count is not specified (0), or is less than or equal the pipe depth.
8713 // It is OK to provide a higher capacity than requested.
8714 // We will force it to mPipeFramesP2 below.
8715 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008716 // PCM data
8717 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008718 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008719 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008720 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008721 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008722 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008723 hasFastCapture() &&
8724 // there are sufficient fast track slots available
8725 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008726 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008727 // check compatibility with audio effects.
8728 Mutex::Autolock _l(mLock);
8729 // Do not accept FAST flag if the session has software effects
Andy Hungbd72c542023-06-20 18:56:17 -07008730 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008731 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008732 audio_input_flags_t old = *flags;
8733 chain->checkInputFlagCompatibility(flags);
8734 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008735 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8736 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008737 }
8738 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008739 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008740 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8741 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008742 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008743 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8744 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008745 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008746 this, frameCount, mFrameCount, mPipeFramesP2,
8747 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008748 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008749 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008750 }
8751 }
8752
Eric Laurentf14db3c2017-12-08 14:20:36 -08008753 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8754 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8755 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8756 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8757 lStatus = BAD_TYPE;
8758 goto Exit;
8759 }
8760
Glenn Kasten74105912014-07-03 12:28:53 -07008761 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008762 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008763 // fast track: frame count is exactly the pipe depth
8764 frameCount = mPipeFramesP2;
8765 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008766 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008767 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008768 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8769 // or 20 ms if there is a fast capture
8770 // TODO This could be a roundupRatio inline, and const
8771 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8772 * sampleRate + mSampleRate - 1) / mSampleRate;
8773 // minimum number of notification periods is at least kMinNotifications,
8774 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8775 static const size_t kMinNotifications = 3;
8776 static const uint32_t kMinMs = 30;
8777 // TODO This could be a roundupRatio inline
8778 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8779 // TODO This could be a roundupRatio inline
8780 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8781 maxNotificationFrames;
8782 const size_t minFrameCount = maxNotificationFrames *
8783 max(kMinNotifications, minNotificationsByMs);
8784 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008785 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8786 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008787 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008788 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008789 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008790 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008791
8792 { // scope for mLock
8793 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008794 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008795 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008796 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008797 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008798 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008799 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008800 }
Eric Laurent81784c32012-11-19 14:55:58 -08008801
Andy Hung3ff4b552023-06-26 19:20:57 -07008802 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008803 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008804 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung3ff4b552023-06-26 19:20:57 -07008805 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008806 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008807
Glenn Kasten03003332013-08-06 15:40:54 -07008808 lStatus = track->initCheck();
8809 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008810 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008811 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008812 goto Exit;
8813 }
8814 mTracks.add(track);
8815
Eric Laurent05067782016-06-01 18:27:28 -07008816 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008817 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8818 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8819 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008820 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008821 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008822
8823 if (maxSharedAudioHistoryMs != 0) {
8824 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8825 }
Eric Laurent81784c32012-11-19 14:55:58 -08008826 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008827
Eric Laurent81784c32012-11-19 14:55:58 -08008828 lStatus = NO_ERROR;
8829
8830Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008831 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008832 return track;
8833}
8834
Andy Hung71742ab2023-07-07 13:47:37 -07008835status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08008836 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008837 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008838{
8839 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8840 sp<ThreadBase> strongMe = this;
8841 status_t status = NO_ERROR;
8842
8843 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008844 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008845 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008846 recordTrack->synchronizedRecordState().startRecording(
Andy Hung2cbc2722023-07-17 17:05:00 -07008847 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07008848 event, triggerSession,
8849 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08008850 }
8851
8852 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008853 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008854 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008855 if (recordTrack->isInvalid()) {
8856 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008857 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8858 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008859 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008860 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008861 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008862 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8863 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008864 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung3ff4b552023-06-26 19:20:57 -07008865 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008866 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07008867 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008868 }
8869 return status;
8870 }
8871
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008872 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8873 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8874 // or using a separate command thread
Andy Hung3ff4b552023-06-26 19:20:57 -07008875 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08008876 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008877 if (recordTrack->isExternalTrack()) {
8878 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008879 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008880 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008881 if (recordTrack->isInvalid()) {
8882 recordTrack->clearSyncStartEvent();
Andy Hung3ff4b552023-06-26 19:20:57 -07008883 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
8884 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07008885 // STARTING_2 forces destroy to call stopInput.
8886 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008887 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8888 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008889 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008890 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07008891 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung3ff4b552023-06-26 19:20:57 -07008892 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07008893 // Someone else has changed state, let them take over,
8894 // leave mState in the new state.
8895 recordTrack->clearSyncStartEvent();
8896 return INVALID_OPERATION;
8897 }
8898 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008899 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008900 ALOGW("%s(%d): startInput failed, status %d",
8901 __func__, recordTrack->id(), status);
8902 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8903 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008904 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008905 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008906 return status;
8907 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008908 sendIoConfigEvent_l(
8909 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008910 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008911
8912 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8913
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008914 // Catch up with current buffer indices if thread is already running.
8915 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8916 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8917 // see previously buffered data before it called start(), but with greater risk of overrun.
8918
Andy Hung3ff4b552023-06-26 19:20:57 -07008919 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008920 if (!recordTrack->isDirect()) {
8921 // clear any converter state as new data will be discontinuous
Andy Hung3ff4b552023-06-26 19:20:57 -07008922 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008923 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008924 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08008925 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008926 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008927 return status;
8928 }
Eric Laurent81784c32012-11-19 14:55:58 -08008929}
8930
Andy Hung71742ab2023-07-07 13:47:37 -07008931void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08008932{
Andy Hung71742ab2023-07-07 13:47:37 -07008933 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08008934
8935 if (strongEvent != 0) {
Andy Hung02a6c4e2023-06-23 19:27:19 -07008936 sp<IAfTrackBase> ptr =
8937 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
8938 if (ptr != nullptr) {
Andy Hung56126702023-07-14 11:00:08 -07008939 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hung02a6c4e2023-06-23 19:27:19 -07008940 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08008941 }
Eric Laurent81784c32012-11-19 14:55:58 -08008942 }
8943}
8944
Andy Hung71742ab2023-07-07 13:47:37 -07008945bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008946 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008947 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008948 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung3ff4b552023-06-26 19:20:57 -07008949 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008950 return false;
8951 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008952 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung3ff4b552023-06-26 19:20:57 -07008953 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07008954
Andy Hungabfab202019-03-07 19:45:54 -08008955 // NOTE: Waiting here is important to keep stop synchronous.
8956 // This is needed for proper patchRecord peer release.
Andy Hung3ff4b552023-06-26 19:20:57 -07008957 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungce685402018-10-05 17:23:27 -07008958 mWaitWorkCV.broadcast(); // signal thread to stop
8959 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008960 }
Andy Hungce685402018-10-05 17:23:27 -07008961
Andy Hung3ff4b552023-06-26 19:20:57 -07008962 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008963 ALOGV("Record stopped OK");
8964 return true;
8965 }
Andy Hungce685402018-10-05 17:23:27 -07008966
8967 // don't handle anything - we've been invalidated or restarted and in a different state
8968 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung3ff4b552023-06-26 19:20:57 -07008969 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008970 return false;
8971}
8972
Andy Hung71742ab2023-07-07 13:47:37 -07008973bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08008974{
8975 return false;
8976}
8977
Andy Hung71742ab2023-07-07 13:47:37 -07008978status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08008979{
8980#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8981 if (!isValidSyncEvent(event)) {
8982 return BAD_VALUE;
8983 }
8984
Glenn Kastend848eb42016-03-08 13:42:11 -08008985 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008986 status_t ret = NAME_NOT_FOUND;
8987
8988 Mutex::Autolock _l(mLock);
8989
8990 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008991 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08008992 if (eventSession == track->sessionId()) {
8993 (void) track->setSyncEvent(event);
8994 ret = NO_ERROR;
8995 }
8996 }
8997 return ret;
8998#else
8999 return BAD_VALUE;
9000#endif
9001}
9002
Andy Hung71742ab2023-07-07 13:47:37 -07009003status_t RecordThread::getActiveMicrophones(
Andy Hung44f27182023-07-06 20:56:16 -07009004 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009005{
9006 ALOGV("RecordThread::getActiveMicrophones");
9007 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009008 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009009 return NO_INIT;
9010 }
jiabin9ff780e2018-03-19 18:19:52 -07009011 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9012 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009013}
9014
Andy Hung71742ab2023-07-07 13:47:37 -07009015status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009016 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009017{
Paul McLean12340082019-03-19 09:35:05 -06009018 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009019 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009020 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009021 return NO_INIT;
9022 }
Paul McLean12340082019-03-19 09:35:05 -06009023 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009024}
9025
Andy Hung71742ab2023-07-07 13:47:37 -07009026status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009027{
Paul McLean12340082019-03-19 09:35:05 -06009028 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009029 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009030 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009031 return NO_INIT;
9032 }
Paul McLean12340082019-03-19 09:35:05 -06009033 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009034}
9035
Andy Hung71742ab2023-07-07 13:47:37 -07009036status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009037 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9038 int64_t sharedAudioStartMs) {
9039 AutoMutex _l(mLock);
9040 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9041}
9042
Andy Hung71742ab2023-07-07 13:47:37 -07009043status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009044 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9045 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009046
Eric Laurentec376dc2021-04-08 20:41:22 +02009047 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9048 return BAD_VALUE;
9049 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009050
9051 if (sharedAudioStartMs < 0
9052 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009053 return BAD_VALUE;
9054 }
9055
Eric Laurent2407ce32021-04-26 14:56:03 +02009056 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9057 // As we cannot detect more than one wraparound, only accept values up current write position
9058 // after one wraparound
9059 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9060 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009061 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009062 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9063 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009064 // Bring the start frame position within the input buffer to match the documented
9065 // "best effort" behavior of the API.
9066 if (sharedOffset < 0) {
9067 sharedAudioStartFrames = mRsmpInRear;
Andy Hung71ba4b32022-10-06 12:09:49 -07009068 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009069 sharedAudioStartFrames =
9070 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009071 }
9072
Eric Laurentec376dc2021-04-08 20:41:22 +02009073 mSharedAudioPackageName = sharedAudioPackageName;
9074 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009075 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009076 } else {
9077 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009078 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009079 }
9080 return NO_ERROR;
9081}
9082
Andy Hung71742ab2023-07-07 13:47:37 -07009083void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009084 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9085 mSharedAudioStartFrames = -1;
9086 mSharedAudioPackageName = "";
9087}
9088
Andy Hung71742ab2023-07-07 13:47:37 -07009089ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009090{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009091 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009092 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009093 }
9094 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009095 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung3ff4b552023-06-26 19:20:57 -07009096 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009097 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009098 }
9099 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009100 MetadataUpdate change;
9101 change.recordMetadataUpdate = metadata.tracks;
9102 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009103}
9104
Eric Laurent81784c32012-11-19 14:55:58 -08009105// destroyTrack_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07009106void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009107{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009108 track->terminate();
Andy Hung3ff4b552023-06-26 19:20:57 -07009109 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009110
Eric Laurent81784c32012-11-19 14:55:58 -08009111 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009112 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009113 removeTrack_l(track);
9114 }
9115}
9116
Andy Hung71742ab2023-07-07 13:47:37 -07009117void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009118{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009119 String8 result;
9120 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00009121 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009122
Eric Laurent81784c32012-11-19 14:55:58 -08009123 mTracks.remove(track);
9124 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009125 if (track->isFastTrack()) {
9126 ALOG_ASSERT(!mFastTrackAvail);
9127 mFastTrackAvail = true;
9128 }
Eric Laurent81784c32012-11-19 14:55:58 -08009129}
9130
Andy Hung71742ab2023-07-07 13:47:37 -07009131void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009132{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009133 AudioStreamIn *input = mInput;
9134 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9135 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009136 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009137 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009138 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009139 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009140 }
Andy Hungbfa64962017-06-12 14:43:19 -07009141
9142 if (input != nullptr) {
9143 dprintf(fd, " Hal stream dump:\n");
9144 (void)input->stream->dump(fd);
9145 }
9146
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009147 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009148 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009149
Glenn Kasten2f90c512015-12-02 11:40:09 -08009150 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9151 // while we are dumping it. It may be inconsistent, but it won't mutate!
9152 // This is a large object so we place it on the heap.
9153 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009154 const std::unique_ptr<FastCaptureDumpState> copy =
9155 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009156 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009157}
9158
Andy Hung71742ab2023-07-07 13:47:37 -07009159void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009160{
Eric Laurent81784c32012-11-19 14:55:58 -08009161 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009162 size_t numtracks = mTracks.size();
9163 size_t numactive = mActiveTracks.size();
9164 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009165 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009166 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009167 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009168 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009169 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009170 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009171 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009172 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009173 if (track != 0) {
9174 bool active = mActiveTracks.indexOf(track) >= 0;
9175 if (active) {
9176 numactiveseen++;
9177 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009178 result.append(prefix);
9179 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009180 }
Eric Laurent81784c32012-11-19 14:55:58 -08009181 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009182 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009183 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009184 }
9185
Marco Nelissenb2208842014-02-07 14:00:50 -08009186 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009187 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009188 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009189 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009190 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009191 for (size_t i = 0; i < numactive; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009192 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009193 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009194 result.append(prefix);
9195 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009196 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009197 }
Eric Laurent81784c32012-11-19 14:55:58 -08009198
9199 }
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00009200 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009201}
9202
Andy Hung71742ab2023-07-07 13:47:37 -07009203void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009204{
9205 Mutex::Autolock _l(mLock);
9206 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009207 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009208 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009209 track->setSilenced(silenced);
9210 }
9211 }
9212}
Andy Hung73c02e42015-03-29 01:13:58 -07009213
Andy Hung3ff4b552023-06-26 19:20:57 -07009214void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009215{
Andy Hung44f27182023-07-06 20:56:16 -07009216 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung71742ab2023-07-07 13:47:37 -07009217 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009218 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009219 const int32_t rear = recordThread->mRsmpInRear;
9220 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009221 if (mRecordTrack->startFrames() >= 0) {
9222 int32_t startFrames = mRecordTrack->startFrames();
9223 // Accept a recent wraparound of mRsmpInRear
9224 if (startFrames <= rear) {
9225 deltaFrames = rear - startFrames;
9226 } else {
9227 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009228 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009229 // start frame cannot be further in the past than start of resampling buffer
9230 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9231 deltaFrames = recordThread->mRsmpInFrames;
9232 }
9233 }
9234 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009235}
9236
Andy Hung3ff4b552023-06-26 19:20:57 -07009237void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009238 size_t *framesAvailable, bool *hasOverrun)
9239{
Andy Hung44f27182023-07-06 20:56:16 -07009240 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung71742ab2023-07-07 13:47:37 -07009241 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009242 const int32_t rear = recordThread->mRsmpInRear;
9243 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009244 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009245
9246 size_t framesIn;
9247 bool overrun = false;
9248 if (filled < 0) {
9249 // should not happen, but treat like a massive overrun and re-sync
9250 framesIn = 0;
9251 mRsmpInFront = rear;
9252 overrun = true;
9253 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9254 framesIn = (size_t) filled;
9255 } else {
9256 // client is not keeping up with server, but give it latest data
9257 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009258 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9259 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009260 overrun = true;
9261 }
9262 if (framesAvailable != NULL) {
9263 *framesAvailable = framesIn;
9264 }
9265 if (hasOverrun != NULL) {
9266 *hasOverrun = overrun;
9267 }
9268}
9269
Eric Laurent81784c32012-11-19 14:55:58 -08009270// AudioBufferProvider interface
Andy Hung3ff4b552023-06-26 19:20:57 -07009271status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009272 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009273{
Andy Hung44f27182023-07-06 20:56:16 -07009274 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009275 if (threadBase == 0) {
9276 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009277 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009278 return NOT_ENOUGH_DATA;
9279 }
Andy Hung71742ab2023-07-07 13:47:37 -07009280 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009281 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009282 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009283 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009284 // FIXME should not be P2 (don't want to increase latency)
9285 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009286 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009287 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009288
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009289 front &= recordThread->mRsmpInFramesP2 - 1;
9290 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009291 if (part1 > (size_t) filled) {
9292 part1 = filled;
9293 }
9294 size_t ask = buffer->frameCount;
9295 ALOG_ASSERT(ask > 0);
9296 if (part1 > ask) {
9297 part1 = ask;
9298 }
9299 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009300 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009301 buffer->raw = NULL;
9302 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009303 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009304 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009305 }
9306
Andy Hung57446612015-04-19 23:56:46 -07009307 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009308 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009309 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009310 return NO_ERROR;
9311}
9312
9313// AudioBufferProvider interface
Andy Hung3ff4b552023-06-26 19:20:57 -07009314void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009315 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009316{
Hongwei Wang95e37682019-04-12 11:13:36 -07009317 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009318 if (stepCount == 0) {
9319 return;
9320 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009321 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009322 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009323 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009324 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009325 buffer->frameCount = 0;
9326}
9327
Andy Hung71742ab2023-07-07 13:47:37 -07009328void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009329{
9330 Mutex::Autolock _l(mLock);
9331 checkBtNrec_l();
9332}
9333
Andy Hung71742ab2023-07-07 13:47:37 -07009334void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009335{
9336 // disable AEC and NS if the device is a BT SCO headset supporting those
9337 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009338 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Andy Hung2cbc2722023-07-17 17:05:00 -07009339 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009340 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9341 for (size_t i = 0; i < mEffectChains.size(); i++) {
9342 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9343 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9344 }
9345 }
9346}
9347
Andy Hung97a893e2015-03-29 01:03:07 -07009348
Andy Hung71742ab2023-07-07 13:47:37 -07009349bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009350 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009351{
9352 bool reconfig = false;
9353
Eric Laurent10351942014-05-08 18:49:52 -07009354 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009355
Eric Laurent10351942014-05-08 18:49:52 -07009356 audio_format_t reqFormat = mFormat;
9357 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009358 // TODO this may change if we want to support capture from HDMI PCM multi channel (e.g on TVs).
Jing Mike537412f2023-03-12 11:01:47 +08009359 [[maybe_unused]] audio_channel_mask_t channelMask =
9360 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009361
9362 AudioParameter param = AudioParameter(keyValuePair);
9363 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009364
9365 // scope for AutoPark extends to end of method
9366 AutoPark<FastCapture> park(mFastCapture);
9367
Eric Laurent10351942014-05-08 18:49:52 -07009368 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9369 // channel count change can be requested. Do we mandate the first client defines the
9370 // HAL sampling rate and channel count or do we allow changes on the fly?
9371 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9372 samplingRate = value;
9373 reconfig = true;
9374 }
9375 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009376 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009377 status = BAD_VALUE;
9378 } else {
9379 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009380 reconfig = true;
9381 }
Eric Laurent10351942014-05-08 18:49:52 -07009382 }
9383 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9384 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009385 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009386 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009387 status = BAD_VALUE;
9388 } else {
9389 channelMask = mask;
9390 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009391 }
Eric Laurent10351942014-05-08 18:49:52 -07009392 }
9393 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9394 // do not accept frame count changes if tracks are open as the track buffer
9395 // size depends on frame count and correct behavior would not be guaranteed
9396 // if frame count is changed after track creation
9397 if (mActiveTracks.size() > 0) {
9398 status = INVALID_OPERATION;
9399 } else {
9400 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009401 }
Eric Laurent10351942014-05-08 18:49:52 -07009402 }
9403 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009404 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009405 }
9406 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9407 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009408 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009409 }
Glenn Kastene198c362013-08-13 09:13:36 -07009410
Eric Laurent10351942014-05-08 18:49:52 -07009411 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009412 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009413 if (status == INVALID_OPERATION) {
9414 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009415 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009416 }
9417 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009418 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009419 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9420 if (mInput->stream->getAudioProperties(&config) == OK &&
9421 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9422 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009423 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009424 status = NO_ERROR;
9425 }
Eric Laurent81784c32012-11-19 14:55:58 -08009426 }
Eric Laurent10351942014-05-08 18:49:52 -07009427 if (status == NO_ERROR) {
9428 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009429 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009430 }
9431 }
Eric Laurent81784c32012-11-19 14:55:58 -08009432 }
Eric Laurent10351942014-05-08 18:49:52 -07009433
Eric Laurent81784c32012-11-19 14:55:58 -08009434 return reconfig;
9435}
9436
Andy Hung71742ab2023-07-07 13:47:37 -07009437String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009438{
Eric Laurent81784c32012-11-19 14:55:58 -08009439 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009440 if (initCheck() == NO_ERROR) {
9441 String8 out_s8;
9442 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9443 return out_s8;
9444 }
Eric Laurent81784c32012-11-19 14:55:58 -08009445 }
Andy Hung71ba4b32022-10-06 12:09:49 -07009446 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009447}
9448
Andy Hung71742ab2023-07-07 13:47:37 -07009449void RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009450 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009451 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009452 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009453 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009454 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009455 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009456 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9457 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009458 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009459 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009460 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009461 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009462 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009463 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009464 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009465 break;
9466 }
Andy Hung2cbc2722023-07-17 17:05:00 -07009467 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009468}
9469
Andy Hung71742ab2023-07-07 13:47:37 -07009470void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009471{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009472 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9473 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009474 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009475 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9476 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009477 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9478 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009479 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009480 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009481 ALOGI("HAL format %#x is not linear pcm", mFormat);
9482 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009483 result = mInput->stream->getFrameSize(&mFrameSize);
9484 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009485 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9486 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009487 result = mInput->stream->getBufferSize(&mBufferSize);
9488 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009489 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009490 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9491 "mBufferSize=%zu, mFrameCount=%zu",
9492 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009493
Eric Laurentec376dc2021-04-08 20:41:22 +02009494 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9495 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009496 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009497
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009498 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9499 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009500
9501 audio_input_flags_t flags = mInput->flags;
9502 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9503 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9504 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9505 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9506 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9507 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9508 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9509 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9510 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009511}
9512
Andy Hung71742ab2023-07-07 13:47:37 -07009513uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009514{
9515 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009516 uint32_t result;
9517 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9518 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009519 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009520 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009521}
9522
Andy Hung71742ab2023-07-07 13:47:37 -07009523KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009524{
Glenn Kastend848eb42016-03-08 13:42:11 -08009525 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009526 Mutex::Autolock _l(mLock);
9527 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009528 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009529 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009530 if (ids.indexOfKey(sessionId) < 0) {
9531 ids.add(sessionId, true);
9532 }
9533 }
9534 return ids;
9535}
9536
Andy Hung71742ab2023-07-07 13:47:37 -07009537AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009538{
9539 Mutex::Autolock _l(mLock);
9540 AudioStreamIn *input = mInput;
9541 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009542 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009543 return input;
9544}
9545
9546// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hung71742ab2023-07-07 13:47:37 -07009547sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009548{
9549 if (mInput == NULL) {
9550 return NULL;
9551 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009552 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009553}
9554
Andy Hung71742ab2023-07-07 13:47:37 -07009555status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009556{
Eric Laurent81784c32012-11-19 14:55:58 -08009557 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009558 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009559 chain->setInBuffer(NULL);
9560 chain->setOutBuffer(NULL);
9561
9562 checkSuspendOnAddEffectChain_l(chain);
9563
Eric Laurent1b928682014-10-02 19:41:47 -07009564 // make sure enabled pre processing effects state is communicated to the HAL as we
9565 // just moved them to a new input stream.
9566 chain->syncHalEffectsState();
9567
Eric Laurent81784c32012-11-19 14:55:58 -08009568 mEffectChains.add(chain);
9569
9570 return NO_ERROR;
9571}
9572
Andy Hung71742ab2023-07-07 13:47:37 -07009573size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009574{
9575 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009576
9577 for (size_t i = 0; i < mEffectChains.size(); i++) {
9578 if (chain == mEffectChains[i]) {
9579 mEffectChains.removeAt(i);
9580 break;
9581 }
Eric Laurent81784c32012-11-19 14:55:58 -08009582 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009583 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009584}
9585
Andy Hung71742ab2023-07-07 13:47:37 -07009586status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009587 audio_patch_handle_t *handle)
9588{
9589 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009590
9591 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009592 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009593 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009594 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009595 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009596 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009597 }
9598
Eric Laurentd8365c52017-07-16 15:27:05 -07009599 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009600
9601 // store new source and send to effects
9602 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9603 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009604 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009605 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009606 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009607 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009608
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009609 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009610 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9611 status = hwDevice->createAudioPatch(patch->num_sources,
9612 patch->sources,
9613 patch->num_sinks,
9614 patch->sinks,
9615 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009616 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009617 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9618 patch->sinks[0].ext.mix.usecase.source,
9619 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009620 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009621 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009622
jiabinc52b1ff2019-10-31 17:20:42 -07009623 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009624 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009625 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009626 }
Eric Laurent296fb132015-05-01 11:38:42 -07009627
Andy Hungc2b11cb2020-04-22 09:04:01 -07009628 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009629 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009630 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009631 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009632 // also dispatch to active AudioRecords
9633 for (const auto &track : mActiveTracks) {
9634 track->logEndInterval();
9635 track->logBeginInterval(pathSourcesAsString);
9636 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009637 // Force meteadata update after a route change
9638 mActiveTracks.setHasChanged();
9639
Eric Laurent1c333e22014-05-20 10:48:17 -07009640 return status;
9641}
9642
Andy Hung71742ab2023-07-07 13:47:37 -07009643status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009644{
9645 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009646
jiabinc52b1ff2019-10-31 17:20:42 -07009647 mPatch = audio_patch{};
9648 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009649
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009650 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009651 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9652 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009653 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009654 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009655 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009656 // Force meteadata update after a route change
9657 mActiveTracks.setHasChanged();
9658
Eric Laurent1c333e22014-05-20 10:48:17 -07009659 return status;
9660}
9661
Andy Hung71742ab2023-07-07 13:47:37 -07009662void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009663{
wendy lin56aa82b2020-12-02 15:19:55 +08009664 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009665 mOutDevices = outDevices;
9666 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9667 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009668 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009669 }
9670}
9671
Andy Hung71742ab2023-07-07 13:47:37 -07009672int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009673{
9674 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009675 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009676 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009677 int32_t oldestFront = mRsmpInRear;
9678 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009679 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009680 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009681 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009682 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009683 if (filled > maxFilled) {
9684 oldestFront = front;
9685 maxFilled = filled;
9686 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009687 }
Andy Hung71ba4b32022-10-06 12:09:49 -07009688 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009689 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9690 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009691 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009692}
9693
Andy Hung71742ab2023-07-07 13:47:37 -07009694void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009695{
9696 if (offset == 0) {
9697 return;
9698 }
9699 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009700 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009701 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung3ff4b552023-06-26 19:20:57 -07009702 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009703 }
9704}
9705
Andy Hung71742ab2023-07-07 13:47:37 -07009706void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009707{
9708 // This is the formula for calculating the temporary buffer size.
9709 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9710 // 1 full output buffer, regardless of the alignment of the available input.
9711 // The value is somewhat arbitrary, and could probably be even larger.
9712 // A larger value should allow more old data to be read after a track calls start(),
9713 // without increasing latency.
9714 //
9715 // Note this is independent of the maximum downsampling ratio permitted for capture.
9716 size_t minRsmpInFrames = mFrameCount * 7;
9717
9718 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9719 // capture history available to another client using the same session ID:
9720 // dimension the resampler input buffer accordingly.
9721
9722 // Get oldest client read position: getOldestFront_l() must be called before altering
9723 // mRsmpInRear, or mRsmpInFrames
9724 int32_t previousFront = getOldestFront_l();
9725 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9726 int32_t previousRear = mRsmpInRear;
9727 mRsmpInRear = 0;
9728
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009729 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hung71742ab2023-07-07 13:47:37 -07009730 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009731 "resizeInputBuffer_l() called with invalid max shared history %d",
9732 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009733 if (maxSharedAudioHistoryMs != 0) {
9734 // resizeInputBuffer_l should never be called with a non zero shared history if the
9735 // buffer was not already allocated
9736 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9737 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9738 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9739 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009740 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009741 return;
9742 }
9743 mRsmpInFrames = rsmpInFrames;
9744 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009745 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009746 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9747 // initialized
9748 if (mRsmpInFrames < minRsmpInFrames) {
9749 mRsmpInFrames = minRsmpInFrames;
9750 }
9751 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9752
9753 // TODO optimize audio capture buffer sizes ...
9754 // Here we calculate the size of the sliding buffer used as a source
9755 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9756 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9757 // be better to have it derived from the pipe depth in the long term.
9758 // The current value is higher than necessary. However it should not add to latency.
9759
9760 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9761 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9762
9763 void *rsmpInBuffer;
9764 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9765 // if posix_memalign fails, will segv here.
9766 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9767
9768 // Copy audio history if any from old buffer before freeing it
9769 if (previousRear != 0) {
9770 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9771 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9772
9773 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9774 previousFront &= previousRsmpInFramesP2 - 1;
9775 size_t part1 = previousRsmpInFramesP2 - previousFront;
9776 if (part1 > (size_t) unread) {
9777 part1 = unread;
9778 }
9779 if (part1 != 0) {
9780 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9781 part1 * mFrameSize);
9782 mRsmpInRear = part1;
9783 part1 = unread - part1;
9784 if (part1 != 0) {
9785 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9786 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9787 mRsmpInRear += part1;
9788 }
9789 }
9790 // Update front for all clients according to new rear
9791 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9792 } else {
9793 mRsmpInRear = 0;
9794 }
9795 free(mRsmpInBuffer);
9796 mRsmpInBuffer = rsmpInBuffer;
9797}
9798
Andy Hung71742ab2023-07-07 13:47:37 -07009799void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009800{
9801 Mutex::Autolock _l(mLock);
9802 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009803 if (record->getSource()) {
9804 mSource = record->getSource();
9805 }
Eric Laurent83b88082014-06-20 18:31:16 -07009806}
9807
Andy Hung71742ab2023-07-07 13:47:37 -07009808void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009809{
9810 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009811 if (mSource == record->getSource()) {
9812 mSource = mInput;
9813 }
Eric Laurent83b88082014-06-20 18:31:16 -07009814 destroyTrack_l(record);
9815}
9816
Andy Hung71742ab2023-07-07 13:47:37 -07009817void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07009818{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009819 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009820 config->role = AUDIO_PORT_ROLE_SINK;
9821 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9822 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009823 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9824 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9825 config->flags.input = mInput->flags;
9826 }
Eric Laurent83b88082014-06-20 18:31:16 -07009827}
Eric Laurent1c333e22014-05-20 10:48:17 -07009828
Eric Laurent6acd1d42017-01-04 14:23:29 -08009829// ----------------------------------------------------------------------------
9830// Mmap
9831// ----------------------------------------------------------------------------
9832
Andy Hung667dec42023-07-07 15:58:48 -07009833// Mmap stream control interface implementation. Each MmapThreadHandle controls one
9834// MmapPlaybackThread or MmapCaptureThread instance.
9835class MmapThreadHandle : public MmapStreamInterface {
9836public:
9837 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
9838 ~MmapThreadHandle() override;
9839
9840 // MmapStreamInterface virtuals
9841 status_t createMmapBuffer(int32_t minSizeFrames,
9842 struct audio_mmap_buffer_info* info) final;
9843 status_t getMmapPosition(struct audio_mmap_position* position) final;
9844 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
9845 status_t start(const AudioClient& client,
9846 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
9847 status_t stop(audio_port_handle_t handle) final;
9848 status_t standby() final;
9849 status_t reportData(const void* buffer, size_t frameCount) final;
9850private:
9851 const sp<IAfMmapThread> mThread;
9852};
9853
9854/* static */
9855sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
9856 const sp<IAfMmapThread>& mmapThread) {
9857 return sp<MmapThreadHandle>::make(mmapThread);
9858}
9859
9860MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009861 : mThread(thread)
9862{
Phil Burk9fabbf82017-08-03 12:02:00 -07009863 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009864}
9865
Andy Hung667dec42023-07-07 15:58:48 -07009866// MmapStreamInterface could be directly implemented by MmapThread excepting this
9867// special handling on adapter dtor.
9868MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009869{
Phil Burk9fabbf82017-08-03 12:02:00 -07009870 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009871}
9872
Andy Hung667dec42023-07-07 15:58:48 -07009873status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009874 struct audio_mmap_buffer_info *info)
9875{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009876 return mThread->createMmapBuffer(minSizeFrames, info);
9877}
9878
Andy Hung667dec42023-07-07 15:58:48 -07009879status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009880{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009881 return mThread->getMmapPosition(position);
9882}
9883
Andy Hung667dec42023-07-07 15:58:48 -07009884status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -07009885 int64_t *timeNanos) {
9886 return mThread->getExternalPosition(position, timeNanos);
9887}
9888
Andy Hung667dec42023-07-07 15:58:48 -07009889status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009890 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009891{
jiabind1f1cb62020-03-24 11:57:57 -07009892 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009893}
9894
Andy Hung667dec42023-07-07 15:58:48 -07009895status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009896{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009897 return mThread->stop(handle);
9898}
9899
Andy Hung667dec42023-07-07 15:58:48 -07009900status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -08009901{
Eric Laurent18b57012017-02-13 16:23:52 -08009902 return mThread->standby();
9903}
9904
Andy Hung667dec42023-07-07 15:58:48 -07009905status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
9906{
jiabinfc791ee2023-02-15 19:43:40 +00009907 return mThread->reportData(buffer, frameCount);
9908}
9909
Eric Laurent6acd1d42017-01-04 14:23:29 -08009910
Andy Hung71742ab2023-07-07 13:47:37 -07009911MmapThread::MmapThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07009912 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung71ba4b32022-10-06 12:09:49 -07009913 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung2cbc2722023-07-17 17:05:00 -07009914 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009915 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009916 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009917 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009918 mActiveTracks(&this->mLocalLog),
9919 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9920 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009921{
Eric Laurent18b57012017-02-13 16:23:52 -08009922 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009923 readHalParameters_l();
9924}
9925
Andy Hung71742ab2023-07-07 13:47:37 -07009926void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009927{
9928 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9929}
9930
Andy Hung71742ab2023-07-07 13:47:37 -07009931void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009932{
Andy Hung3ff4b552023-06-26 19:20:57 -07009933 ActiveTracks<IAfMmapTrack> activeTracks;
Eric Laurent331679c2018-04-16 17:03:16 -07009934 {
9935 Mutex::Autolock _l(mLock);
Andy Hung3ff4b552023-06-26 19:20:57 -07009936 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -07009937 activeTracks.add(t);
9938 }
9939 }
Andy Hung3ff4b552023-06-26 19:20:57 -07009940 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009941 stop(t->portId());
9942 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009943 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009944 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009945 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009946 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009947 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009948 }
9949}
9950
9951
Andy Hung71742ab2023-07-07 13:47:37 -07009952void MmapThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009953 audio_stream_type_t streamType __unused,
9954 audio_session_t sessionId,
9955 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009956 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009957 audio_port_handle_t portId)
9958{
9959 mAttr = *attr;
9960 mSessionId = sessionId;
9961 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009962 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009963 mPortId = portId;
9964}
9965
Andy Hung71742ab2023-07-07 13:47:37 -07009966status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009967 struct audio_mmap_buffer_info *info)
9968{
9969 if (mHalStream == 0) {
9970 return NO_INIT;
9971 }
Eric Laurent18b57012017-02-13 16:23:52 -08009972 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009973 return mHalStream->createMmapBuffer(minSizeFrames, info);
9974}
9975
Andy Hung71742ab2023-07-07 13:47:37 -07009976status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -08009977{
9978 if (mHalStream == 0) {
9979 return NO_INIT;
9980 }
9981 return mHalStream->getMmapPosition(position);
9982}
9983
Andy Hung71742ab2023-07-07 13:47:37 -07009984status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -07009985{
Eric Laurentdda206a2022-07-08 17:28:35 +02009986 // The HAL must receive track metadata before starting the stream
9987 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -07009988 status_t ret = mHalStream->start();
9989 if (ret != NO_ERROR) {
9990 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9991 return ret;
9992 }
Andy Hungcf10d742020-04-28 15:38:24 -07009993 if (mStandby) {
9994 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009995 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07009996 mStandby = false;
9997 }
Eric Laurent331679c2018-04-16 17:03:16 -07009998 return NO_ERROR;
9999}
10000
Andy Hung71742ab2023-07-07 13:47:37 -070010001status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010002 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010003 audio_port_handle_t *handle)
10004{
Eric Laurenta54f1282017-07-01 19:39:32 -070010005 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010006 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010007 if (mHalStream == 0) {
10008 return NO_INIT;
10009 }
10010
10011 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010012
Eric Laurentdda206a2022-07-08 17:28:35 +020010013 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010014 if (*handle == mPortId) {
Eric Laurentdda206a2022-07-08 17:28:35 +020010015 acquireWakeLock();
10016 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010017 }
10018
10019 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10020
10021 audio_io_handle_t io = mId;
Atneya Nairf59db5c2023-05-10 21:37:41 -070010022 AttributionSourceState adjAttributionSource = AudioFlinger::checkAttributionSourcePackage(
10023 client.attributionSource);
10024
Eric Laurenta54f1282017-07-01 19:39:32 -070010025 if (isOutput()) {
10026 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10027 config.sample_rate = mSampleRate;
10028 config.channel_mask = mChannelMask;
10029 config.format = mFormat;
10030 audio_stream_type_t stream = streamType();
10031 audio_output_flags_t flags =
10032 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010033 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010034 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010035 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010036 bool isBitPerfect;
Eric Laurenta54f1282017-07-01 19:39:32 -070010037 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
10038 mSessionId,
10039 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010040 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010041 &config,
10042 flags,
10043 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010044 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010045 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010046 &isSpatialized,
10047 &isBitPerfect);
Kevin Rocard153f92d2018-12-18 18:33:28 -080010048 ALOGD_IF(!secondaryOutputs.empty(),
10049 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010050 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010051 audio_config_base_t config;
10052 config.sample_rate = mSampleRate;
10053 config.channel_mask = mChannelMask;
10054 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010055 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -070010056 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010057 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -070010058 mSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010059 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010060 &config,
10061 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10062 &deviceId,
10063 &portId);
10064 }
10065 // APM should not chose a different input or output stream for the same set of attributes
10066 // and audo configuration
10067 if (ret != NO_ERROR || io != mId) {
10068 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10069 __FUNCTION__, ret, io, mId);
10070 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010071 }
10072
10073 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010074 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010075 } else {
jiabincfc10a42022-06-15 19:26:01 +000010076 {
10077 // Add the track record before starting input so that the silent status for the
10078 // client can be cached.
10079 Mutex::Autolock _l(mLock);
10080 setClientSilencedState_l(portId, false /*silenced*/);
10081 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010082 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010083 }
10084
Eric Laurent331679c2018-04-16 17:03:16 -070010085 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010086 // abort if start is rejected by audio policy manager
10087 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010088 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010089 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -070010090 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010091 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010092 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010093 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010094 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010095 }
Eric Laurent331679c2018-04-16 17:03:16 -070010096 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010097 } else {
10098 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010099 }
jiabincfc10a42022-06-15 19:26:01 +000010100 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010101 return PERMISSION_DENIED;
10102 }
10103
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010104 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung3ff4b552023-06-26 19:20:57 -070010105 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10106 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010107 mChannelMask, mSessionId, isOutput(),
10108 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010109 IPCThreadState::self()->getCallingPid(), portId);
jiabincfc10a42022-06-15 19:26:01 +000010110 if (!isOutput()) {
10111 track->setSilenced_l(isClientSilenced_l(portId));
10112 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010113
Eric Laurent4eb58f12018-12-07 16:41:02 -080010114 if (isOutput()) {
10115 // force volume update when a new track is added
10116 mHalVolFloat = -1.0f;
10117 } else if (!track->isSilenced_l()) {
Andy Hung3ff4b552023-06-26 19:20:57 -070010118 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung71ba4b32022-10-06 12:09:49 -070010119 if (t->isSilenced_l()
10120 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010121 t->invalidate();
Andy Hung71ba4b32022-10-06 12:09:49 -070010122 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010123 }
10124 }
10125
Eric Laurent6acd1d42017-01-04 14:23:29 -080010126 mActiveTracks.add(track);
Andy Hungbd72c542023-06-20 18:56:17 -070010127 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010128 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +020010129 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010130 chain->incTrackCnt();
10131 chain->incActiveTrackCnt();
10132 }
10133
Andy Hungc2b11cb2020-04-22 09:04:01 -070010134 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010135 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010136
10137 if (mActiveTracks.size() == 1) {
10138 ret = exitStandby_l();
10139 }
10140
Eric Laurent6acd1d42017-01-04 14:23:29 -080010141 broadcast_l();
10142
Eric Laurentdda206a2022-07-08 17:28:35 +020010143 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010144
Eric Laurentdda206a2022-07-08 17:28:35 +020010145 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010146}
10147
Andy Hung71742ab2023-07-07 13:47:37 -070010148status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010149{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010150 ALOGV("%s handle %d", __FUNCTION__, handle);
10151
10152 if (mHalStream == 0) {
10153 return NO_INIT;
10154 }
10155
Eric Laurenta54f1282017-07-01 19:39:32 -070010156 if (handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +000010157 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -070010158 return NO_ERROR;
10159 }
10160
Eric Laurent331679c2018-04-16 17:03:16 -070010161 Mutex::Autolock _l(mLock);
10162
Andy Hung3ff4b552023-06-26 19:20:57 -070010163 sp<IAfMmapTrack> track;
10164 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010165 if (handle == t->portId()) {
10166 track = t;
10167 break;
10168 }
10169 }
10170 if (track == 0) {
10171 return BAD_VALUE;
10172 }
10173
10174 mActiveTracks.remove(track);
jiabincfc10a42022-06-15 19:26:01 +000010175 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010176
Eric Laurent331679c2018-04-16 17:03:16 -070010177 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010178 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010179 AudioSystem::stopOutput(track->portId());
10180 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010181 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010182 AudioSystem::stopInput(track->portId());
10183 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010184 }
Eric Laurent331679c2018-04-16 17:03:16 -070010185 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010186
Andy Hungbd72c542023-06-20 18:56:17 -070010187 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010188 if (chain != 0) {
10189 chain->decActiveTrackCnt();
10190 chain->decTrackCnt();
10191 }
10192
Eric Laurentdda206a2022-07-08 17:28:35 +020010193 if (mActiveTracks.isEmpty()) {
10194 mHalStream->stop();
10195 }
10196
Eric Laurent6acd1d42017-01-04 14:23:29 -080010197 broadcast_l();
10198
Eric Laurent6acd1d42017-01-04 14:23:29 -080010199 return NO_ERROR;
10200}
10201
Andy Hung71742ab2023-07-07 13:47:37 -070010202status_t MmapThread::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010203{
10204 ALOGV("%s", __FUNCTION__);
10205
10206 if (mHalStream == 0) {
10207 return NO_INIT;
10208 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010209 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010210 return INVALID_OPERATION;
10211 }
10212 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010213 if (!mStandby) {
10214 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010215 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010216 mStandby = true;
10217 }
Eric Laurent18b57012017-02-13 16:23:52 -080010218 releaseWakeLock();
10219 return NO_ERROR;
10220}
10221
Andy Hung71742ab2023-07-07 13:47:37 -070010222status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010223 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10224 return INVALID_OPERATION;
10225}
Eric Laurent6acd1d42017-01-04 14:23:29 -080010226
Andy Hung71742ab2023-07-07 13:47:37 -070010227void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010228{
10229 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10230 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10231 mFormat = mHALFormat;
10232 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10233 result = mHalStream->getFrameSize(&mFrameSize);
10234 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010235 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10236 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010237 result = mHalStream->getBufferSize(&mBufferSize);
10238 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10239 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010240
Andy Hungcf10d742020-04-28 15:38:24 -070010241 // TODO: make a readHalParameters call?
10242 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010243 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
10244 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
10245 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10246 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10247 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10248 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10249 /*
10250 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10251 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10252 (int32_t)mHapticChannelMask)
10253 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10254 (int32_t)mHapticChannelCount)
10255 */
10256 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
10257 formatToString(mHALFormat).c_str())
10258 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10259 (int32_t)mFrameCount) // sic - added HAL
10260 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010261}
10262
Andy Hung71742ab2023-07-07 13:47:37 -070010263bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010264{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010265 checkSilentMode_l();
10266
10267 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10268
10269 while (!exitPending())
10270 {
Andy Hungbd72c542023-06-20 18:56:17 -070010271 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010272
Andy Hung13850be2019-03-14 11:33:09 -070010273 { // under Thread lock
10274 Mutex::Autolock _l(mLock);
10275
Eric Laurent6acd1d42017-01-04 14:23:29 -080010276 if (mSignalPending) {
10277 // A signal was raised while we were unlocked
10278 mSignalPending = false;
10279 } else {
10280 if (mConfigEvents.isEmpty()) {
10281 // we're about to wait, flush the binder command buffer
10282 IPCThreadState::self()->flushCommands();
10283
10284 if (exitPending()) {
10285 break;
10286 }
10287
Eric Laurent6acd1d42017-01-04 14:23:29 -080010288 // wait until we have something to do...
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010289 ALOGV("%s going to sleep", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010290 mWaitWorkCV.wait(mLock);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010291 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010292
10293 checkSilentMode_l();
10294
10295 continue;
10296 }
10297 }
10298
10299 processConfigEvents_l();
10300
10301 processVolume_l();
10302
10303 checkInvalidTracks_l();
10304
10305 mActiveTracks.updatePowerState(this);
10306
Kevin Rocard069c2712018-03-29 19:09:14 -070010307 updateMetadata_l();
10308
Eric Laurent6acd1d42017-01-04 14:23:29 -080010309 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010310 } // release Thread lock
10311
Eric Laurent6acd1d42017-01-04 14:23:29 -080010312 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010313 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010314 }
Andy Hung13850be2019-03-14 11:33:09 -070010315
10316 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010317 unlockEffectChains(effectChains);
10318 // Effect chains will be actually deleted here if they were removed from
10319 // mEffectChains list during mixing or effects processing
10320 }
10321
10322 threadLoop_exit();
10323
10324 if (!mStandby) {
10325 threadLoop_standby();
10326 mStandby = true;
10327 }
10328
Eric Laurent6acd1d42017-01-04 14:23:29 -080010329 ALOGV("Thread %p type %d exiting", this, mType);
10330 return false;
10331}
10332
10333// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -070010334bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010335 status_t& status)
10336{
10337 AudioParameter param = AudioParameter(keyValuePair);
10338 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010339 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010340 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010341 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010342 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010343 if (sendToHal) {
10344 status = mHalStream->setParameters(keyValuePair);
10345 } else {
10346 status = NO_ERROR;
10347 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010348
10349 return false;
10350}
10351
Andy Hung71742ab2023-07-07 13:47:37 -070010352String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010353{
10354 Mutex::Autolock _l(mLock);
10355 String8 out_s8;
10356 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10357 return out_s8;
10358 }
Andy Hung71ba4b32022-10-06 12:09:49 -070010359 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010360}
10361
Andy Hung71742ab2023-07-07 13:47:37 -070010362void MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010363 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010364 sp<AudioIoDescriptor> desc;
10365 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010366 switch (event) {
10367 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010368 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010369 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010370 isInput = true;
10371 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010372 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010373 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010374 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010375 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10376 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010377 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010378 case AUDIO_INPUT_CLOSED:
10379 case AUDIO_OUTPUT_CLOSED:
10380 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010381 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010382 break;
10383 }
Andy Hung2cbc2722023-07-17 17:05:00 -070010384 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010385}
10386
Andy Hung71742ab2023-07-07 13:47:37 -070010387status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010388 audio_patch_handle_t *handle)
Andy Hung71ba4b32022-10-06 12:09:49 -070010389NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010390{
10391 status_t status = NO_ERROR;
10392
10393 // store new device and send to effects
10394 audio_devices_t type = AUDIO_DEVICE_NONE;
10395 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010396 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10397 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10398 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010399 if (isOutput()) {
10400 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010401 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10402 && !mAudioHwDev->supportsAudioPatches(),
10403 "Enumerated device type(%#x) must not be used "
10404 "as it does not support audio patches",
10405 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010406 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung71ba4b32022-10-06 12:09:49 -070010407 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10408 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010409 }
10410 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010411 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010412 } else {
10413 type = patch->sources[0].ext.device.type;
10414 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010415 numDevices = mPatch.num_sources;
10416 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010417 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010418 }
10419
10420 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010421 if (isOutput()) {
10422 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10423 } else {
10424 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10425 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010426 }
10427
jiabinc52b1ff2019-10-31 17:20:42 -070010428 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010429 // store new source and send to effects
10430 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10431 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10432 for (size_t i = 0; i < mEffectChains.size(); i++) {
10433 mEffectChains[i]->setAudioSource_l(mAudioSource);
10434 }
10435 }
10436 }
10437
10438 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010439 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10440 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010441 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010442 audio_port_config port;
10443 std::optional<audio_source_t> source;
10444 if (isOutput()) {
10445 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010446 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010447 port = patch->sources[0];
10448 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010449 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010450 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010451 *handle = AUDIO_PATCH_HANDLE_NONE;
10452 }
10453
jiabinc52b1ff2019-10-31 17:20:42 -070010454 if (numDevices == 0 || mDeviceId != deviceId) {
10455 if (isOutput()) {
10456 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10457 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010458 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010459 } else {
10460 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10461 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10462 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010463 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010464 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010465 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010466 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -070010467 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010468 }
jiabinc52b1ff2019-10-31 17:20:42 -070010469 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010470 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010471 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010472 // Force meteadata update after a route change
10473 mActiveTracks.setHasChanged();
10474
Eric Laurent6acd1d42017-01-04 14:23:29 -080010475 return status;
10476}
10477
Andy Hung71742ab2023-07-07 13:47:37 -070010478status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010479{
10480 status_t status = NO_ERROR;
10481
jiabinc52b1ff2019-10-31 17:20:42 -070010482 mPatch = audio_patch{};
10483 mOutDeviceTypeAddrs.clear();
10484 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010485
10486 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10487 supportsAudioPatches : false;
10488
10489 if (supportsAudioPatches) {
10490 status = mHalDevice->releaseAudioPatch(handle);
10491 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010492 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010493 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010494 // Force meteadata update after a route change
10495 mActiveTracks.setHasChanged();
10496
Eric Laurent6acd1d42017-01-04 14:23:29 -080010497 return status;
10498}
10499
Andy Hung71742ab2023-07-07 13:47:37 -070010500void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010501{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010502 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010503 if (isOutput()) {
10504 config->role = AUDIO_PORT_ROLE_SOURCE;
10505 config->ext.mix.hw_module = mAudioHwDev->handle();
10506 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10507 } else {
10508 config->role = AUDIO_PORT_ROLE_SINK;
10509 config->ext.mix.hw_module = mAudioHwDev->handle();
10510 config->ext.mix.usecase.source = mAudioSource;
10511 }
10512}
10513
Andy Hung71742ab2023-07-07 13:47:37 -070010514status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010515{
10516 audio_session_t session = chain->sessionId();
10517
10518 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10519 // Attach all tracks with same session ID to this chain.
10520 // indicate all active tracks in the chain
Andy Hung3ff4b552023-06-26 19:20:57 -070010521 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010522 if (session == track->sessionId()) {
10523 chain->incTrackCnt();
10524 chain->incActiveTrackCnt();
10525 }
10526 }
10527
10528 chain->setThread(this);
10529 chain->setInBuffer(nullptr);
10530 chain->setOutBuffer(nullptr);
10531 chain->syncHalEffectsState();
10532
10533 mEffectChains.add(chain);
10534 checkSuspendOnAddEffectChain_l(chain);
10535 return NO_ERROR;
10536}
10537
Andy Hung71742ab2023-07-07 13:47:37 -070010538size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010539{
10540 audio_session_t session = chain->sessionId();
10541
10542 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10543
10544 for (size_t i = 0; i < mEffectChains.size(); i++) {
10545 if (chain == mEffectChains[i]) {
10546 mEffectChains.removeAt(i);
10547 // detach all active tracks from the chain
10548 // detach all tracks with same session ID from this chain
Andy Hung3ff4b552023-06-26 19:20:57 -070010549 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010550 if (session == track->sessionId()) {
10551 chain->decActiveTrackCnt();
10552 chain->decTrackCnt();
10553 }
10554 }
10555 break;
10556 }
10557 }
10558 return mEffectChains.size();
10559}
10560
Andy Hung71742ab2023-07-07 13:47:37 -070010561void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010562{
10563 mHalStream->standby();
10564}
10565
Andy Hung71742ab2023-07-07 13:47:37 -070010566void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010567{
Phil Burk7dce7282017-09-27 13:51:41 -070010568 // Do not call callback->onTearDown() because it is redundant for thread exit
10569 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010570}
10571
Andy Hung71742ab2023-07-07 13:47:37 -070010572status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010573{
10574 return BAD_VALUE;
10575}
10576
Andy Hung71742ab2023-07-07 13:47:37 -070010577bool MmapThread::isValidSyncEvent(
10578 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010579{
10580 return false;
10581}
10582
Andy Hung71742ab2023-07-07 13:47:37 -070010583status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010584 const effect_descriptor_t *desc, audio_session_t sessionId)
10585{
10586 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010587 if (audio_is_global_session(sessionId)) {
10588 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010589 desc->name, mThreadName);
10590 return BAD_VALUE;
10591 }
10592
10593 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10594 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10595 desc->name);
10596 return BAD_VALUE;
10597 }
10598 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010599 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10600 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010601 return BAD_VALUE;
10602 }
10603
10604 // Only allow effects without processing load or latency
10605 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10606 return BAD_VALUE;
10607 }
10608
Andy Hungbd72c542023-06-20 18:56:17 -070010609 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010610 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10611 return BAD_VALUE;
10612 }
10613
Eric Laurent6acd1d42017-01-04 14:23:29 -080010614 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010615}
10616
Andy Hung71742ab2023-07-07 13:47:37 -070010617void MmapThread::checkInvalidTracks_l()
Andy Hung71ba4b32022-10-06 12:09:49 -070010618NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010619{
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010620 sp<MmapStreamCallback> callback;
Andy Hung3ff4b552023-06-26 19:20:57 -070010621 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010622 if (track->isInvalid()) {
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010623 callback = mCallback.promote();
10624 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10625 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
Eric Laurent331679c2018-04-16 17:03:16 -070010626 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010627 }
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010628 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010629 }
10630 }
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010631 if (callback != 0) {
10632 mLock.unlock();
10633 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10634 mLock.lock();
10635 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010636}
10637
Andy Hung71742ab2023-07-07 13:47:37 -070010638void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010639{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010640 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10641 mAttr.content_type, mAttr.usage, mAttr.source);
10642 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010643 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010644 dprintf(fd, " No active clients\n");
10645 }
10646}
10647
Andy Hung71742ab2023-07-07 13:47:37 -070010648void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010649{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010650 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010651 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010652 dprintf(fd, " %zu Tracks\n", numtracks);
10653 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010654 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010655 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010656 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010657 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -070010658 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010659 result.append(prefix);
10660 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010661 }
10662 } else {
10663 dprintf(fd, "\n");
10664 }
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010665 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010666}
10667
Andy Hung71742ab2023-07-07 13:47:37 -070010668/* static */
10669sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung2cbc2722023-07-17 17:05:00 -070010670 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung71742ab2023-07-07 13:47:37 -070010671 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -070010672 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -070010673}
10674
10675MmapPlaybackThread::MmapPlaybackThread(
Andy Hung2cbc2722023-07-17 17:05:00 -070010676 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010677 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -070010678 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010679 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010680 mStreamVolume(1.0),
10681 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010682 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010683{
10684 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10685 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung2cbc2722023-07-17 17:05:00 -070010686 mMasterVolume = afThreadCallback->masterVolume_l();
10687 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010688 if (mAudioHwDev) {
10689 if (mAudioHwDev->canSetMasterVolume()) {
10690 mMasterVolume = 1.0;
10691 }
10692
10693 if (mAudioHwDev->canSetMasterMute()) {
10694 mMasterMute = false;
10695 }
10696 }
10697}
10698
Andy Hung71742ab2023-07-07 13:47:37 -070010699void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010700 audio_stream_type_t streamType,
10701 audio_session_t sessionId,
10702 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010703 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010704 audio_port_handle_t portId)
10705{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010706 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010707 mStreamType = streamType;
10708}
10709
Andy Hung71742ab2023-07-07 13:47:37 -070010710AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010711{
10712 Mutex::Autolock _l(mLock);
10713 AudioStreamOut *output = mOutput;
10714 mOutput = NULL;
10715 return output;
10716}
10717
Andy Hung71742ab2023-07-07 13:47:37 -070010718void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010719{
10720 Mutex::Autolock _l(mLock);
10721 // Don't apply master volume in SW if our HAL can do it for us.
10722 if (mAudioHwDev &&
10723 mAudioHwDev->canSetMasterVolume()) {
10724 mMasterVolume = 1.0;
10725 } else {
10726 mMasterVolume = value;
10727 }
10728}
10729
Andy Hung71742ab2023-07-07 13:47:37 -070010730void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010731{
10732 Mutex::Autolock _l(mLock);
10733 // Don't apply master mute in SW if our HAL can do it for us.
10734 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10735 mMasterMute = false;
10736 } else {
10737 mMasterMute = muted;
10738 }
10739}
10740
Andy Hung71742ab2023-07-07 13:47:37 -070010741void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010742{
10743 Mutex::Autolock _l(mLock);
10744 if (stream == mStreamType) {
10745 mStreamVolume = value;
10746 broadcast_l();
10747 }
10748}
10749
Andy Hung71742ab2023-07-07 13:47:37 -070010750float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010751{
10752 Mutex::Autolock _l(mLock);
10753 if (stream == mStreamType) {
10754 return mStreamVolume;
10755 }
10756 return 0.0f;
10757}
10758
Andy Hung71742ab2023-07-07 13:47:37 -070010759void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010760{
10761 Mutex::Autolock _l(mLock);
10762 if (stream == mStreamType) {
10763 mStreamMute= muted;
10764 broadcast_l();
10765 }
10766}
10767
Andy Hung71742ab2023-07-07 13:47:37 -070010768void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010769{
10770 Mutex::Autolock _l(mLock);
10771 if (streamType == mStreamType) {
Andy Hung3ff4b552023-06-26 19:20:57 -070010772 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010773 track->invalidate();
10774 }
10775 broadcast_l();
10776 }
10777}
10778
Andy Hung71742ab2023-07-07 13:47:37 -070010779void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010780{
10781 Mutex::Autolock _l(mLock);
10782 bool trackMatch = false;
Andy Hung3ff4b552023-06-26 19:20:57 -070010783 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010784 if (portIds.find(track->portId()) != portIds.end()) {
10785 track->invalidate();
10786 trackMatch = true;
10787 portIds.erase(track->portId());
10788 }
10789 if (portIds.empty()) {
10790 break;
10791 }
10792 }
10793 if (trackMatch) {
10794 broadcast_l();
10795 }
10796}
10797
Andy Hung71742ab2023-07-07 13:47:37 -070010798void MmapPlaybackThread::processVolume_l()
Andy Hung71ba4b32022-10-06 12:09:49 -070010799NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080010800{
10801 float volume;
10802
10803 if (mMasterMute || mStreamMute) {
10804 volume = 0;
10805 } else {
10806 volume = mMasterVolume * mStreamVolume;
10807 }
10808
10809 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010810
10811 // Convert volumes from float to 8.24
10812 uint32_t vol = (uint32_t)(volume * (1 << 24));
10813
10814 // Delegate volume control to effect in track effect chain if needed
10815 // only one effect chain can be present on DirectOutputThread, so if
10816 // there is one, the track is connected to it
10817 if (!mEffectChains.isEmpty()) {
10818 mEffectChains[0]->setVolume_l(&vol, &vol);
10819 volume = (float)vol / (1 << 24);
10820 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010821 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010822 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10823 mHalVolFloat = volume; // HW volume control worked, so update value.
10824 mNoCallbackWarningCount = 0;
10825 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010826 sp<MmapStreamCallback> callback = mCallback.promote();
10827 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010828 mHalVolFloat = volume; // SW volume control worked, so update value.
10829 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010830 mLock.unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010831 callback->onVolumeChanged(volume);
Eric Laurent734046e2018-04-16 14:50:52 -070010832 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010833 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010834 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10835 ALOGW("Could not set MMAP stream volume: no volume callback!");
10836 mNoCallbackWarningCount++;
10837 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010838 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010839 }
Andy Hung3ff4b552023-06-26 19:20:57 -070010840 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010841 track->setMetadataHasChanged();
Andy Hung2cbc2722023-07-17 17:05:00 -070010842 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010843 /*muteState=*/{mMasterMute,
10844 mStreamVolume == 0.f,
10845 mStreamMute,
10846 // TODO(b/241533526): adjust logic to include mute from AppOps
10847 false /*muteFromPlaybackRestricted*/,
10848 false /*muteFromClientVolume*/,
10849 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010850 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010851 }
10852}
10853
Andy Hung71742ab2023-07-07 13:47:37 -070010854ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070010855{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010856 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010010857 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010858 }
10859 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung3ff4b552023-06-26 19:20:57 -070010860 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070010861 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010862 playback_track_metadata_v7_t trackMetadata;
10863 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010864 .usage = track->attributes().usage,
10865 .content_type = track->attributes().content_type,
10866 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010867 };
10868 trackMetadata.channel_mask = track->channelMask(),
10869 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10870 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010871 }
10872 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010010873
10874 MetadataUpdate change;
10875 change.playbackMetadataUpdate = metadata.tracks;
10876 return change;
10877};
Kevin Rocard069c2712018-03-29 19:09:14 -070010878
Andy Hung71742ab2023-07-07 13:47:37 -070010879void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010880{
10881 if (!mMasterMute) {
10882 char value[PROPERTY_VALUE_MAX];
10883 if (property_get("ro.audio.silent", value, "0") > 0) {
10884 char *endptr;
10885 unsigned long ul = strtoul(value, &endptr, 0);
10886 if (*endptr == '\0' && ul != 0) {
10887 ALOGD("Silence is golden");
10888 // The setprop command will not allow a property to be changed after
10889 // the first time it is set, so we don't have to worry about un-muting.
10890 setMasterMute_l(true);
10891 }
10892 }
10893 }
10894}
10895
Andy Hung71742ab2023-07-07 13:47:37 -070010896void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010897{
10898 MmapThread::toAudioPortConfig(config);
10899 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10900 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10901 config->flags.output = mOutput->flags;
10902 }
10903}
10904
Andy Hung71742ab2023-07-07 13:47:37 -070010905status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung4989d312023-06-29 21:19:25 -070010906 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070010907{
10908 if (mOutput == nullptr) {
10909 return NO_INIT;
10910 }
10911 struct timespec timestamp;
10912 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10913 if (status == NO_ERROR) {
10914 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10915 }
10916 return status;
10917}
10918
Andy Hung71742ab2023-07-07 13:47:37 -070010919status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010920 // Send to MelProcessor for sound dose measurement.
10921 auto processor = mMelProcessor.load();
10922 if (processor) {
10923 processor->process(buffer, frameCount * mFrameSize);
10924 }
10925
jiabinfc791ee2023-02-15 19:43:40 +000010926 return NO_ERROR;
10927}
10928
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010929// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -070010930void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010931 const sp<audio_utils::MelProcessor>& processor)
10932{
10933 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010934 mMelProcessor.store(processor);
10935 if (processor) {
10936 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010937 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010938
10939 // no need to update output format for MMapPlaybackThread since it is
10940 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010941}
10942
10943// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -070010944void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010945{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010946 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
10947 auto melProcessor = mMelProcessor.load();
10948 if (melProcessor != nullptr) {
10949 melProcessor->pause();
10950 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010951}
10952
Andy Hung71742ab2023-07-07 13:47:37 -070010953void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010954{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010955 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010956
Glenn Kastend3bb6452016-12-05 18:14:37 -080010957 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10958 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010959 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10960}
10961
Andy Hung71742ab2023-07-07 13:47:37 -070010962/* static */
10963sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung2cbc2722023-07-17 17:05:00 -070010964 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung71742ab2023-07-07 13:47:37 -070010965 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -070010966 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -070010967}
10968
10969MmapCaptureThread::MmapCaptureThread(
Andy Hung2cbc2722023-07-17 17:05:00 -070010970 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010971 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -070010972 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010973 mInput(input)
10974{
10975 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10976 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10977}
10978
Andy Hung71742ab2023-07-07 13:47:37 -070010979status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010980{
Phil Burkf054fc32018-12-06 09:45:59 -080010981 {
10982 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080010983 if (mInput != nullptr && mInput->stream != nullptr) {
10984 mInput->stream->setGain(1.0f);
10985 }
10986 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010987 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010988}
10989
Andy Hung71742ab2023-07-07 13:47:37 -070010990AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010991{
10992 Mutex::Autolock _l(mLock);
10993 AudioStreamIn *input = mInput;
10994 mInput = NULL;
10995 return input;
10996}
Kevin Rocard069c2712018-03-29 19:09:14 -070010997
Andy Hung71742ab2023-07-07 13:47:37 -070010998void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010999{
11000 bool changed = false;
11001 bool silenced = false;
11002
11003 sp<MmapStreamCallback> callback = mCallback.promote();
11004 if (callback == 0) {
11005 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11006 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11007 mNoCallbackWarningCount++;
11008 }
11009 }
11010
11011 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11012 // track is silenced and unmute otherwise
11013 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11014 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11015 changed = true;
11016 silenced = mActiveTracks[i]->isSilenced_l();
11017 }
11018 }
11019
11020 if (changed) {
11021 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11022 }
11023}
11024
Andy Hung71742ab2023-07-07 13:47:37 -070011025ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011026{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011027 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011028 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011029 }
11030 StreamInHalInterface::SinkMetadata metadata;
Andy Hung3ff4b552023-06-26 19:20:57 -070011031 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011032 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011033 record_track_metadata_v7_t trackMetadata;
11034 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011035 .source = track->attributes().source,
11036 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011037 };
11038 trackMetadata.channel_mask = track->channelMask(),
11039 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11040 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011041 }
11042 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011043 MetadataUpdate change;
11044 change.recordMetadataUpdate = metadata.tracks;
11045 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011046}
11047
Andy Hung71742ab2023-07-07 13:47:37 -070011048void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011049{
11050 Mutex::Autolock _l(mLock);
11051 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011052 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011053 mActiveTracks[i]->setSilenced_l(silenced);
11054 broadcast_l();
11055 }
11056 }
jiabincfc10a42022-06-15 19:26:01 +000011057 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011058}
11059
Andy Hung71742ab2023-07-07 13:47:37 -070011060void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011061{
11062 MmapThread::toAudioPortConfig(config);
11063 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11064 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11065 config->flags.input = mInput->flags;
11066 }
11067}
11068
Andy Hung71742ab2023-07-07 13:47:37 -070011069status_t MmapCaptureThread::getExternalPosition(
Andy Hung4989d312023-06-29 21:19:25 -070011070 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011071{
11072 if (mInput == nullptr) {
11073 return NO_INIT;
11074 }
11075 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11076}
11077
jiabinc658e452022-10-21 20:52:21 +000011078// ----------------------------------------------------------------------------
11079
Andy Hung71742ab2023-07-07 13:47:37 -070011080/* static */
11081sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung2cbc2722023-07-17 17:05:00 -070011082 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -070011083 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -070011084 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -070011085}
11086
Andy Hung2cbc2722023-07-17 17:05:00 -070011087BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011088 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -070011089 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011090
Andy Hung71742ab2023-07-07 13:47:37 -070011091PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -070011092 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011093 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11094 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011095 float volumeLeft = 1.0f;
11096 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011097 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11098 const int trackId = mActiveTracks[0]->id();
11099 mAudioMixer->setParameter(
11100 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11101 mAudioMixer->setParameter(
11102 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11103 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011104 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011105 mIsBitPerfect = true;
11106 } else {
11107 mIsBitPerfect = false;
11108 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11109 // active.
11110 for (const auto& track : mActiveTracks) {
11111 const int trackId = track->id();
11112 mAudioMixer->setParameter(
11113 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11114 }
11115 }
jiabin76d94692022-12-15 21:51:21 +000011116 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11117 mVolumeLeft = volumeLeft;
11118 mVolumeRight = volumeRight;
11119 setVolumeForOutput_l(volumeLeft, volumeRight);
11120 }
jiabinc658e452022-10-21 20:52:21 +000011121 return result;
11122}
11123
Andy Hung71742ab2023-07-07 13:47:37 -070011124void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011125 MixerThread::threadLoop_mix();
11126 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11127}
11128
Glenn Kasten63238ef2015-03-02 15:50:29 -080011129} // namespace android