blob: 1d4767b791150be6495c90740893c1bf0987fe8d [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 Hung4b17e882023-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 Hungd69d9f12023-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 Hungf2f5d642023-07-18 20:54:44 -070097#include <afutils/DumpTryLock.h>
Andy Hungc3af0112023-07-19 16:56:19 -070098#include <afutils/Permission.h>
Andy Hung0077d8c2023-05-24 11:53:47 -070099#include <afutils/TypedLogger.h>
Andy Hung76cb9152023-07-20 21:23:42 -0700100#include <afutils/Vibrator.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800101
Eric Laurent81784c32012-11-19 14:55:58 -0800102// ----------------------------------------------------------------------------
103
104// Note: the following macro is used for extremely verbose logging message. In
105// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
106// 0; but one side effect of this is to turn all LOGV's as well. Some messages
107// are so verbose that we want to suppress them even when we have ALOG_ASSERT
108// turned on. Do not uncomment the #def below unless you really know what you
109// are doing and want to see all of the extremely verbose messages.
110//#define VERY_VERY_VERBOSE_LOGGING
111#ifdef VERY_VERY_VERBOSE_LOGGING
112#define ALOGVV ALOGV
113#else
114#define ALOGVV(a...) do { } while(0)
115#endif
116
Andy Hung6770c6f2015-04-07 13:43:36 -0700117// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700118#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700119
Andy Hung6770c6f2015-04-07 13:43:36 -0700120template <typename T>
121static inline T min(const T& a, const T& b)
122{
123 return a < b ? a : b;
124}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700125
Eric Laurent81784c32012-11-19 14:55:58 -0800126namespace android {
127
Andy Hung4b17e882023-07-07 13:47:37 -0700128using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700129using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000130using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700131
Eric Laurent81784c32012-11-19 14:55:58 -0800132// retry counts for buffer fill timeout
133// 50 * ~20msecs = 1 second
134static const int8_t kMaxTrackRetries = 50;
135static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700136
Eric Laurent81784c32012-11-19 14:55:58 -0800137// allow less retry attempts on direct output thread.
138// direct outputs can be a scarce resource in audio hardware and should
139// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700140// Notes:
141// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
142// in case the data write is bursty for the AudioTrack. The application
143// should endeavor to write at least once every kMaxTrackRetriesDirectMs
144// to prevent an underrun situation. If the data is bursty, then
145// the application can also throttle the data sent to be even.
146// 2) For compressed audio data, any data present in the AudioTrack buffer
147// will be sent and reset the retry count. This delivers data as
148// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
149// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
150// of data to be available, then any remaining data is delivered.
151// This is required to ensure the last bit of data is delivered before underrun.
152//
153// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
154// or the size of the HAL period for proportional / linear PCM tracks.
155static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800156
157// don't warn about blocked writes or record buffer overflows more often than this
158static const nsecs_t kWarningThrottleNs = seconds(5);
159
160// RecordThread loop sleep time upon application overrun or audio HAL read error
161static const int kRecordThreadSleepUs = 5000;
162
Eric Laurent10351942014-05-08 18:49:52 -0700163// maximum time to wait in sendConfigEvent_l() for a status to be received
164static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800165
166// minimum sleep time for the mixer thread loop when tracks are active but in underrun
167static const uint32_t kMinThreadSleepTimeUs = 5000;
168// maximum divider applied to the active sleep time in the mixer thread loop
169static const uint32_t kMaxThreadSleepTimeShift = 2;
170
Andy Hung09a50072014-02-27 14:30:47 -0800171// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700172// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800173static const uint32_t kMinNormalSinkBufferSizeMs = 20;
174// maximum normal sink buffer size
175static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800176
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700177// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
178// FIXME This should be based on experimentally observed scheduling jitter
179static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
180
Eric Laurent972a1732013-09-04 09:42:59 -0700181// Offloaded output thread standby delay: allows track transition without going to standby
182static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
183
Eric Laurent51716182016-02-29 18:00:56 -0800184// Direct output thread minimum sleep time in idle or active(underrun) state
185static const nsecs_t kDirectMinSleepTimeUs = 10000;
186
Brian Lindahl65e90012022-07-27 18:01:07 +0200187// Minimum amount of time between checking to see if the timestamp is advancing
188// for underrun detection. If we check too frequently, we may not detect a
189// timestamp update and will falsely detect underrun.
190static const nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1000;
191
Glenn Kasten1b291842016-07-18 14:55:21 -0700192// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
193// balance between power consumption and latency, and allows threads to be scheduled reliably
194// by the CFS scheduler.
195// FIXME Express other hardcoded references to 20ms with references to this constant and move
196// it appropriately.
197#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800198
Eric Laurent81784c32012-11-19 14:55:58 -0800199// Whether to use fast mixer
200static const enum {
201 FastMixer_Never, // never initialize or use: for debugging only
202 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
203 // normal mixer multiplier is 1
204 FastMixer_Static, // initialize if needed, then use all the time if initialized,
205 // multiplier is calculated based on min & max normal mixer buffer size
206 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
207 // multiplier is calculated based on min & max normal mixer buffer size
208 // FIXME for FastMixer_Dynamic:
209 // Supporting this option will require fixing HALs that can't handle large writes.
210 // For example, one HAL implementation returns an error from a large write,
211 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
212 // We could either fix the HAL implementations, or provide a wrapper that breaks
213 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
214} kUseFastMixer = FastMixer_Static;
215
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700216// Whether to use fast capture
217static const enum {
218 FastCapture_Never, // never initialize or use: for debugging only
219 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
220 FastCapture_Static, // initialize if needed, then use all the time if initialized
221} kUseFastCapture = FastCapture_Static;
222
Eric Laurent81784c32012-11-19 14:55:58 -0800223// Priorities for requestPriority
224static const int kPriorityAudioApp = 2;
225static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700226static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800227
Glenn Kastenea38ee72016-04-18 11:08:01 -0700228// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
229// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
230// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700231
232// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800233static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800234
Glenn Kasten03490092014-05-27 12:30:54 -0700235// The minimum and maximum allowed values
236static const int kFastTrackMultiplierMin = 1;
237static const int kFastTrackMultiplierMax = 2;
238
239// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
240static int sFastTrackMultiplier = kFastTrackMultiplier;
241
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700242// See Thread::readOnlyHeap().
243// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
244// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
245// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700246static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700247
Eric Laurent81784c32012-11-19 14:55:58 -0800248// ----------------------------------------------------------------------------
249
Andy Hungb68f5eb2019-12-03 16:49:17 -0800250// TODO: move all toString helpers to audio.h
251// under #ifdef __cplusplus #endif
252static std::string patchSinksToString(const struct audio_patch *patch)
253{
254 std::stringstream ss;
255 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700256 if (i > 0) {
257 ss << "|";
258 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800259 ss << "(" << toString(patch->sinks[i].ext.device.type)
260 << ", " << patch->sinks[i].ext.device.address << ")";
261 }
262 return ss.str();
263}
264
265static std::string patchSourcesToString(const struct audio_patch *patch)
266{
267 std::stringstream ss;
268 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700269 if (i > 0) {
270 ss << "|";
271 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800272 ss << "(" << toString(patch->sources[i].ext.device.type)
273 << ", " << patch->sources[i].ext.device.address << ")";
274 }
275 return ss.str();
276}
277
Andy Hung4bd53e72022-11-17 17:21:45 -0800278static std::string toString(audio_latency_mode_t mode) {
279 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000280 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
281 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800282}
283
284// Could be made a template, but other toString overloads for std::vector are confused.
285static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
286 std::string s("{ ");
287 for (const auto& e : elements) {
288 s.append(toString(e));
289 s.append(" ");
290 }
291 s.append("}");
292 return s;
293}
294
Glenn Kasten03490092014-05-27 12:30:54 -0700295static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
296
297static void sFastTrackMultiplierInit()
298{
299 char value[PROPERTY_VALUE_MAX];
300 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
301 char *endptr;
302 unsigned long ul = strtoul(value, &endptr, 0);
303 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
304 sFastTrackMultiplier = (int) ul;
305 }
306 }
307}
308
309// ----------------------------------------------------------------------------
310
Eric Laurent81784c32012-11-19 14:55:58 -0800311#ifdef ADD_BATTERY_DATA
312// To collect the amplifier usage
313static void addBatteryData(uint32_t params) {
314 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
315 if (service == NULL) {
316 // it already logged
317 return;
318 }
319
320 service->addBatteryData(params);
321}
322#endif
323
Andy Hung3f0c9022016-01-15 17:49:46 -0800324// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
325struct {
326 // call when you acquire a partial wakelock
327 void acquire(const sp<IBinder> &wakeLockToken) {
328 pthread_mutex_lock(&mLock);
329 if (wakeLockToken.get() == nullptr) {
330 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
331 } else {
332 if (mCount == 0) {
333 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
334 }
335 ++mCount;
336 }
337 pthread_mutex_unlock(&mLock);
338 }
339
340 // call when you release a partial wakelock.
341 void release(const sp<IBinder> &wakeLockToken) {
342 if (wakeLockToken.get() == nullptr) {
343 return;
344 }
345 pthread_mutex_lock(&mLock);
346 if (--mCount < 0) {
347 ALOGE("negative wakelock count");
348 mCount = 0;
349 }
350 pthread_mutex_unlock(&mLock);
351 }
352
353 // retrieves the boottime timebase offset from monotonic.
354 int64_t getBoottimeOffset() {
355 pthread_mutex_lock(&mLock);
356 int64_t boottimeOffset = mBoottimeOffset;
357 pthread_mutex_unlock(&mLock);
358 return boottimeOffset;
359 }
360
361 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
362 // and the selected timebase.
363 // Currently only TIMEBASE_BOOTTIME is allowed.
364 //
365 // This only needs to be called upon acquiring the first partial wakelock
366 // after all other partial wakelocks are released.
367 //
368 // We do an empirical measurement of the offset rather than parsing
369 // /proc/timer_list since the latter is not a formal kernel ABI.
370 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
371 int clockbase;
372 switch (timebase) {
373 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
374 clockbase = SYSTEM_TIME_BOOTTIME;
375 break;
376 default:
377 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
378 break;
379 }
380 // try three times to get the clock offset, choose the one
381 // with the minimum gap in measurements.
382 const int tries = 3;
Andy Hung920f6572022-10-06 12:09:49 -0700383 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800384 for (int i = 0; i < tries; ++i) {
385 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
386 const nsecs_t tbase = systemTime(clockbase);
387 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
388 const nsecs_t gap = tmono2 - tmono;
389 if (i == 0 || gap < bestGap) {
390 bestGap = gap;
391 measured = tbase - ((tmono + tmono2) >> 1);
392 }
393 }
394
395 // to avoid micro-adjusting, we don't change the timebase
396 // unless it is significantly different.
397 //
398 // Assumption: It probably takes more than toleranceNs to
399 // suspend and resume the device.
400 static int64_t toleranceNs = 10000; // 10 us
401 if (llabs(*offset - measured) > toleranceNs) {
402 ALOGV("Adjusting timebase offset old: %lld new: %lld",
403 (long long)*offset, (long long)measured);
404 *offset = measured;
405 }
406 }
407
408 pthread_mutex_t mLock;
409 int32_t mCount;
410 int64_t mBoottimeOffset;
411} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800412
413// ----------------------------------------------------------------------------
414// CPU Stats
415// ----------------------------------------------------------------------------
416
417class CpuStats {
418public:
419 CpuStats();
420 void sample(const String8 &title);
421#ifdef DEBUG_CPU_USAGE
422private:
423 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700424 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800425
Andy Hung16698b82018-08-01 10:48:38 -0700426 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800427
428 int mCpuNum; // thread's current CPU number
429 int mCpukHz; // frequency of thread's current CPU in kHz
430#endif
431};
432
433CpuStats::CpuStats()
434#ifdef DEBUG_CPU_USAGE
435 : mCpuNum(-1), mCpukHz(-1)
436#endif
437{
438}
439
Glenn Kasten0f11b512014-01-31 16:18:54 -0800440void CpuStats::sample(const String8 &title
441#ifndef DEBUG_CPU_USAGE
442 __unused
443#endif
444 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800445#ifdef DEBUG_CPU_USAGE
446 // get current thread's delta CPU time in wall clock ns
447 double wcNs;
448 bool valid = mCpuUsage.sampleAndEnable(wcNs);
449
450 // record sample for wall clock statistics
451 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700452 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800453 }
454
455 // get the current CPU number
456 int cpuNum = sched_getcpu();
457
458 // get the current CPU frequency in kHz
459 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
460
461 // check if either CPU number or frequency changed
462 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
463 mCpuNum = cpuNum;
464 mCpukHz = cpukHz;
465 // ignore sample for purposes of cycles
466 valid = false;
467 }
468
469 // if no change in CPU number or frequency, then record sample for cycle statistics
470 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700471 const double cycles = wcNs * cpukHz * 0.000001;
472 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800473 }
474
Eric Tan5b13ff82018-07-27 11:20:17 -0700475 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800476 // mCpuUsage.elapsed() is expensive, so don't call it every loop
477 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700478 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800479 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700480 const double perLoop = elapsed / (double) n;
481 const double perLoop100 = perLoop * 0.01;
482 const double perLoop1k = perLoop * 0.001;
483 const double mean = mWcStats.getMean();
484 const double stddev = mWcStats.getStdDev();
485 const double minimum = mWcStats.getMin();
486 const double maximum = mWcStats.getMax();
487 const double meanCycles = mHzStats.getMean();
488 const double stddevCycles = mHzStats.getStdDev();
489 const double minCycles = mHzStats.getMin();
490 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800491 mCpuUsage.resetElapsed();
492 mWcStats.reset();
493 mHzStats.reset();
494 ALOGD("CPU usage for %s over past %.1f secs\n"
495 " (%u mixer loops at %.1f mean ms per loop):\n"
496 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
497 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
498 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
499 title.string(),
500 elapsed * .000000001, n, perLoop * .000001,
501 mean * .001,
502 stddev * .001,
503 minimum * .001,
504 maximum * .001,
505 mean / perLoop100,
506 stddev / perLoop100,
507 minimum / perLoop100,
508 maximum / perLoop100,
509 meanCycles / perLoop1k,
510 stddevCycles / perLoop1k,
511 minCycles / perLoop1k,
512 maxCycles / perLoop1k);
513
514 }
515 }
516#endif
517};
518
519// ----------------------------------------------------------------------------
520// ThreadBase
521// ----------------------------------------------------------------------------
522
Glenn Kasten97b7b752014-09-28 13:04:24 -0700523// static
Andy Hung4b17e882023-07-07 13:47:37 -0700524const char* ThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700525{
526 switch (type) {
527 case MIXER:
528 return "MIXER";
529 case DIRECT:
530 return "DIRECT";
531 case DUPLICATING:
532 return "DUPLICATING";
533 case RECORD:
534 return "RECORD";
535 case OFFLOAD:
536 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700537 case MMAP_PLAYBACK:
538 return "MMAP_PLAYBACK";
539 case MMAP_CAPTURE:
540 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200541 case SPATIALIZER:
542 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000543 case BIT_PERFECT:
544 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700545 default:
546 return "unknown";
547 }
548}
549
Andy Hung7535ed92023-07-17 17:05:00 -0700550ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700551 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800552 : Thread(false /*canCallJava*/),
553 mType(type),
Andy Hung7535ed92023-07-17 17:05:00 -0700554 mAfThreadCallback(afThreadCallback),
Andy Hungcf10d742020-04-28 15:38:24 -0700555 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
556 isOut),
557 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700558 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800559 // are set by PlaybackThread::readOutputParameters_l() or
560 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700561 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700562 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700563 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800564 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700565 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800566 mSystemReady(systemReady),
567 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800568{
Andy Hungcf10d742020-04-28 15:38:24 -0700569 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700570 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800571}
572
Andy Hung4b17e882023-07-07 13:47:37 -0700573ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800574{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700575 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700576 mConfigEvents.clear();
577
Eric Laurent81784c32012-11-19 14:55:58 -0800578 // do not lock the mutex in destructor
579 releaseWakeLock_l();
580 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800581 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800582 binder->unlinkToDeath(mDeathRecipient);
583 }
Andy Hungd0979812019-02-21 15:51:44 -0800584
585 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800586}
587
Andy Hung4b17e882023-07-07 13:47:37 -0700588status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700589{
590 status_t status = initCheck();
591 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800592 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700593 } else {
594 ALOGE("No working audio driver found.");
595 }
596 return status;
597}
598
Andy Hung4b17e882023-07-07 13:47:37 -0700599void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800600{
601 ALOGV("ThreadBase::exit");
602 // do any cleanup required for exit to succeed
603 preExit();
604 {
605 // This lock prevents the following race in thread (uniprocessor for illustration):
606 // if (!exitPending()) {
607 // // context switch from here to exit()
608 // // exit() calls requestExit(), what exitPending() observes
609 // // exit() calls signal(), which is dropped since no waiters
610 // // context switch back from exit() to here
611 // mWaitWorkCV.wait(...);
612 // // now thread is hung
613 // }
614 AutoMutex lock(mLock);
615 requestExit();
616 mWaitWorkCV.broadcast();
617 }
618 // When Thread::requestExitAndWait is made virtual and this method is renamed to
619 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
620 requestExitAndWait();
621}
622
Andy Hung4b17e882023-07-07 13:47:37 -0700623status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800624{
Eric Laurent81784c32012-11-19 14:55:58 -0800625 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
626 Mutex::Autolock _l(mLock);
627
Eric Laurent10351942014-05-08 18:49:52 -0700628 return sendSetParameterConfigEvent_l(keyValuePairs);
629}
630
631// sendConfigEvent_l() must be called with ThreadBase::mLock held
632// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hung4b17e882023-07-07 13:47:37 -0700633status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700634NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700635{
636 status_t status = NO_ERROR;
637
Eric Laurent72e3f392015-05-20 14:43:50 -0700638 if (event->mRequiresSystemReady && !mSystemReady) {
639 event->mWaitStatus = false;
640 mPendingConfigEvents.add(event);
641 return status;
642 }
Eric Laurent10351942014-05-08 18:49:52 -0700643 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700644 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800645 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700646 mLock.unlock();
647 {
648 Mutex::Autolock _l(event->mLock);
649 while (event->mWaitStatus) {
650 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
651 event->mStatus = TIMED_OUT;
652 event->mWaitStatus = false;
653 }
654 }
655 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800656 }
Eric Laurent10351942014-05-08 18:49:52 -0700657 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800658 return status;
659}
660
Andy Hung4b17e882023-07-07 13:47:37 -0700661void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700662 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800663{
664 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700665 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800666}
667
668// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -0700669void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700670 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800671{
Andy Hungd0979812019-02-21 15:51:44 -0800672 // The audio statistics history is exponentially weighted to forget events
673 // about five or more seconds in the past. In order to have
674 // crisper statistics for mediametrics, we reset the statistics on
675 // an IoConfigEvent, to reflect different properties for a new device.
676 mIoJitterMs.reset();
677 mLatencyMs.reset();
678 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000679 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100680 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800681
Eric Laurent09f1ed22019-04-24 17:45:17 -0700682 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700683 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800684}
685
Andy Hung4b17e882023-07-07 13:47:37 -0700686void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700687{
688 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800689 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700690}
691
Eric Laurent81784c32012-11-19 14:55:58 -0800692// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -0700693void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800694 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800695{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800696 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700697 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800698}
699
Eric Laurent10351942014-05-08 18:49:52 -0700700// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -0700701status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800702{
Andy Hung2ddee192015-12-18 17:34:44 -0800703 sp<ConfigEvent> configEvent;
704 AudioParameter param(keyValuePair);
705 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700706 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800707 setMasterMono_l(value != 0);
708 if (param.size() == 1) {
709 return NO_ERROR; // should be a solo parameter - we don't pass down
710 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700711 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800712 configEvent = new SetParameterConfigEvent(param.toString());
713 } else {
714 configEvent = new SetParameterConfigEvent(keyValuePair);
715 }
Eric Laurent10351942014-05-08 18:49:52 -0700716 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700717}
718
Andy Hung4b17e882023-07-07 13:47:37 -0700719status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700720 const struct audio_patch *patch,
721 audio_patch_handle_t *handle)
722{
723 Mutex::Autolock _l(mLock);
724 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
725 status_t status = sendConfigEvent_l(configEvent);
726 if (status == NO_ERROR) {
727 CreateAudioPatchConfigEventData *data =
728 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
729 *handle = data->mHandle;
730 }
731 return status;
732}
733
Andy Hung4b17e882023-07-07 13:47:37 -0700734status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700735 const audio_patch_handle_t handle)
736{
737 Mutex::Autolock _l(mLock);
738 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
739 return sendConfigEvent_l(configEvent);
740}
741
Andy Hung4b17e882023-07-07 13:47:37 -0700742status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700743 const DeviceDescriptorBaseVector& outDevices)
744{
745 if (type() != RECORD) {
746 // The update out device operation is only for record thread.
747 return INVALID_OPERATION;
748 }
749 Mutex::Autolock _l(mLock);
750 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
751 return sendConfigEvent_l(configEvent);
752}
753
Andy Hung4b17e882023-07-07 13:47:37 -0700754void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200755{
756 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
757 sp<ConfigEvent> configEvent =
758 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
759 sendConfigEvent_l(configEvent);
760}
Eric Laurent1c333e22014-05-20 10:48:17 -0700761
Andy Hung4b17e882023-07-07 13:47:37 -0700762void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200763{
764 Mutex::Autolock _l(mLock);
765 sendCheckOutputStageEffectsEvent_l();
766}
767
Andy Hung4b17e882023-07-07 13:47:37 -0700768void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200769{
770 sp<ConfigEvent> configEvent =
771 (ConfigEvent *)new CheckOutputStageEffectsEvent();
772 sendConfigEvent_l(configEvent);
773}
774
Andy Hung4b17e882023-07-07 13:47:37 -0700775void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200776{
777 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
778 sendConfigEvent_l(configEvent);
779}
780
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700781// post condition: mConfigEvents.isEmpty()
Andy Hung4b17e882023-07-07 13:47:37 -0700782void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700783{
Eric Laurent10351942014-05-08 18:49:52 -0700784 bool configChanged = false;
785
Eric Laurent81784c32012-11-19 14:55:58 -0800786 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700787 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700788 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800789 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700790 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700791 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700792 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
793 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800794 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700795 true /*asynchronous*/);
796 if (err != 0) {
797 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700798 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700799 }
800 } break;
801 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700802 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700803 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700804 } break;
805 case CFG_EVENT_SET_PARAMETER: {
806 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
807 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
808 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700809 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
810 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700811 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700812 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700813 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700814 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700815 CreateAudioPatchConfigEventData *data =
816 (CreateAudioPatchConfigEventData *)event->mData.get();
817 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700818 const DeviceTypeSet newDevices = getDeviceTypes();
Eric Laurent52568142022-10-28 11:23:28 +0200819 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700820 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
821 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
822 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700823 } break;
824 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700825 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700826 ReleaseAudioPatchConfigEventData *data =
827 (ReleaseAudioPatchConfigEventData *)event->mData.get();
828 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700829 const DeviceTypeSet newDevices = getDeviceTypes();
Eric Laurent52568142022-10-28 11:23:28 +0200830 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700831 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
832 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
833 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
834 } break;
835 case CFG_EVENT_UPDATE_OUT_DEVICE: {
836 UpdateOutDevicesConfigEventData *data =
837 (UpdateOutDevicesConfigEventData *)event->mData.get();
838 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700839 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200840 case CFG_EVENT_RESIZE_BUFFER: {
841 ResizeBufferConfigEventData *data =
842 (ResizeBufferConfigEventData *)event->mData.get();
843 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
844 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200845
846 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
847 setCheckOutputStageEffects();
848 } break;
849
Eric Laurent68a40a82022-05-03 18:15:04 +0200850 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
851 onHalLatencyModesChanged_l();
852 } break;
853
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700854 default:
Eric Laurent10351942014-05-08 18:49:52 -0700855 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700856 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800857 }
Eric Laurent10351942014-05-08 18:49:52 -0700858 {
859 Mutex::Autolock _l(event->mLock);
860 if (event->mWaitStatus) {
861 event->mWaitStatus = false;
862 event->mCond.signal();
863 }
864 }
865 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
866 }
867
868 if (configChanged) {
869 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800870 }
Eric Laurent81784c32012-11-19 14:55:58 -0800871}
872
Marco Nelissenb2208842014-02-07 14:00:50 -0800873String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
874 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700875 const audio_channel_representation_t representation =
876 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700877
878 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800879 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700880 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
881 if (output) {
882 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
883 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
884 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700885 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700886 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
887 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
888 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
889 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
890 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
891 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
892 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
893 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
894 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
895 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
896 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
897 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700898 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
899 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
900 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
901 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
902 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
903 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
904 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700905 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700906 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
907 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700908 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
909 } else {
910 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
911 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
912 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
913 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
914 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
915 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
916 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
917 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
918 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
919 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
920 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
921 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700922 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
923 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
924 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700925 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700926 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
927 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700928 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
929 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
930 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
931 }
932 const int len = s.length();
933 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700934 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700935 s.unlockBuffer(len - 2); // remove trailing ", "
936 }
937 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800938 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700939 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
940 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
941 return s;
942 default:
943 s.appendFormat("unknown mask, representation:%d bits:%#x",
944 representation, audio_channel_mask_get_bits(mask));
945 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800946 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800947}
948
Andy Hung4b17e882023-07-07 13:47:37 -0700949void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -0700950NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -0800951{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800952 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
953 this, mThreadName, getTid(), type(), threadTypeToString(type()));
954
Andy Hungf2f5d642023-07-18 20:54:44 -0700955 const bool locked = afutils::dumpTryLock(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800956 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800957 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800958 }
959
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700960 dumpBase_l(fd, args);
961 dumpInternals_l(fd, args);
962 dumpTracks_l(fd, args);
963 dumpEffectChains_l(fd, args);
964
965 if (locked) {
966 mLock.unlock();
967 }
968
969 dprintf(fd, " Local log:\n");
970 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -0700971
972 // --all does the statistics
973 bool dumpAll = false;
974 for (const auto &arg : args) {
975 if (arg == String16("--all")) {
976 dumpAll = true;
977 }
978 }
979 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -0700980 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -0700981 if (!sched.empty()) {
982 (void)write(fd, sched.c_str(), sched.size());
983 }
984 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700985}
986
Andy Hung4b17e882023-07-07 13:47:37 -0700987void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700988{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700989 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700990 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700991 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700992 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700993 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700994 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700995 dprintf(fd, " Channel count: %u\n", mChannelCount);
996 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800997 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700998 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700999 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001000 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001001 size_t numConfig = mConfigEvents.size();
1002 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001003 const size_t SIZE = 256;
1004 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001005 for (size_t i = 0; i < numConfig; i++) {
1006 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001007 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001008 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001009 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001010 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001011 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001012 }
Andy Hung293558a2017-03-21 12:19:20 -07001013 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001014 dprintf(fd, " Output devices: %s (%s)\n",
1015 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
1016 dprintf(fd, " Input device: %#x (%s)\n",
1017 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001018 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001019
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001020 // Dump timestamp statistics for the Thread types that support it.
1021 if (mType == RECORD
1022 || mType == MIXER
1023 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001024 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001025 || mType == OFFLOAD
1026 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001027 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -07001028 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001029 }
1030
Andy Hung446f4df2019-02-21 12:26:41 -08001031 if (mLastIoBeginNs > 0) { // MMAP may not set this
1032 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1033 isOutput() ? "write" : "read",
1034 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1035 }
1036
1037 if (mProcessTimeMs.getN() > 0) {
1038 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1039 }
1040
1041 if (mIoJitterMs.getN() > 0) {
1042 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1043 isOutput() ? "write" : "read",
1044 mIoJitterMs.toString().c_str());
1045 }
1046
Andy Hunge6c37112019-02-26 17:38:10 -08001047 if (mLatencyMs.getN() > 0) {
1048 dprintf(fd, " Threadloop %s latency stats: %s\n",
1049 isOutput() ? "write" : "read",
1050 mLatencyMs.toString().c_str());
1051 }
Robert Wu06db0a32021-08-10 19:05:34 +00001052
1053 if (mMonopipePipeDepthStats.getN() > 0) {
1054 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1055 isOutput() ? "write" : "read",
1056 mMonopipePipeDepthStats.toString().c_str());
1057 }
Eric Laurent81784c32012-11-19 14:55:58 -08001058}
1059
Andy Hung4b17e882023-07-07 13:47:37 -07001060void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001061{
1062 const size_t SIZE = 256;
1063 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001064
Marco Nelissenb2208842014-02-07 14:00:50 -08001065 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001066 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001067 write(fd, buffer, strlen(buffer));
1068
Marco Nelissenb2208842014-02-07 14:00:50 -08001069 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001070 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001071 if (chain != 0) {
1072 chain->dump(fd, args);
1073 }
1074 }
1075}
1076
Andy Hung4b17e882023-07-07 13:47:37 -07001077void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001078{
1079 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07001080 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001081}
1082
Andy Hung4b17e882023-07-07 13:47:37 -07001083String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001084{
1085 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001086 case MIXER:
1087 return String16("AudioMix");
1088 case DIRECT:
1089 return String16("AudioDirectOut");
1090 case DUPLICATING:
1091 return String16("AudioDup");
1092 case RECORD:
1093 return String16("AudioIn");
1094 case OFFLOAD:
1095 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001096 case MMAP_PLAYBACK:
1097 return String16("MmapPlayback");
1098 case MMAP_CAPTURE:
1099 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001100 case SPATIALIZER:
1101 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001102 default:
1103 ALOG_ASSERT(false);
1104 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001105 }
1106}
1107
Andy Hung4b17e882023-07-07 13:47:37 -07001108void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001109{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001110 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001111 if (mPowerManager != 0) {
1112 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001113 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001114 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1115 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001116 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001117 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001118 {} /* workSource */,
1119 {} /* historyTag */);
1120 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001121 mWakeLockToken = binder;
1122 }
Chris Ye6597d732020-02-28 22:38:25 -08001123 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001124 }
Wei Jia3f273d12015-11-24 09:06:49 -08001125
Andy Hung3f0c9022016-01-15 17:49:46 -08001126 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001127 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1128 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001129}
1130
Andy Hung4b17e882023-07-07 13:47:37 -07001131void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001132{
1133 Mutex::Autolock _l(mLock);
1134 releaseWakeLock_l();
1135}
1136
Andy Hung4b17e882023-07-07 13:47:37 -07001137void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001138{
Andy Hung3f0c9022016-01-15 17:49:46 -08001139 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001140 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001141 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001142 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001143 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001144 }
1145 mWakeLockToken.clear();
1146 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001147}
1148
Andy Hung4b17e882023-07-07 13:47:37 -07001149void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001150 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001151 // use checkService() to avoid blocking if power service is not up yet
1152 sp<IBinder> binder =
1153 defaultServiceManager()->checkService(String16("power"));
1154 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001155 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001156 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001157 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001158 binder->linkToDeath(mDeathRecipient);
1159 }
1160 }
1161}
1162
Andy Hung4b17e882023-07-07 13:47:37 -07001163void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001164 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001165
1166#if !LOG_NDEBUG
1167 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001168 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001169 s << uid << " ";
1170 }
1171 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1172#endif
1173
Andy Hung438e7572015-12-14 15:51:17 -08001174 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1175 if (mSystemReady) {
1176 ALOGE("no wake lock to update, but system ready!");
1177 } else {
1178 ALOGW("no wake lock to update, system not ready yet");
1179 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001180 return;
1181 }
1182 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001183 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001184 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1185 mWakeLockToken, uidsAsInt);
1186 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001187 }
1188}
1189
Andy Hung4b17e882023-07-07 13:47:37 -07001190void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001191{
1192 Mutex::Autolock _l(mLock);
1193 releaseWakeLock_l();
1194 mPowerManager.clear();
1195}
1196
Andy Hung4b17e882023-07-07 13:47:37 -07001197void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001198 const DeviceDescriptorBaseVector& outDevices __unused)
1199{
1200 ALOGE("%s should only be called in RecordThread", __func__);
1201}
1202
Andy Hung4b17e882023-07-07 13:47:37 -07001203void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001204{
1205 ALOGE("%s should only be called in RecordThread", __func__);
1206}
1207
Andy Hung4b17e882023-07-07 13:47:37 -07001208void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001209{
1210 sp<ThreadBase> thread = mThread.promote();
1211 if (thread != 0) {
1212 thread->clearPowerManager();
1213 }
1214 ALOGW("power manager service died !!!");
1215}
1216
Andy Hung4b17e882023-07-07 13:47:37 -07001217void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001218 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001219{
Andy Hung116bc262023-06-20 18:56:17 -07001220 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001221 if (chain != 0) {
1222 if (type != NULL) {
1223 chain->setEffectSuspended_l(type, suspend);
1224 } else {
1225 chain->setEffectSuspendedAll_l(suspend);
1226 }
1227 }
1228
1229 updateSuspendedSessions_l(type, suspend, sessionId);
1230}
1231
Andy Hung4b17e882023-07-07 13:47:37 -07001232void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001233{
1234 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1235 if (index < 0) {
1236 return;
1237 }
1238
1239 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1240 mSuspendedSessions.valueAt(index);
1241
1242 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001243 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001244 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001245 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001246 chain->setEffectSuspendedAll_l(true);
1247 } else {
1248 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1249 desc->mType.timeLow);
1250 chain->setEffectSuspended_l(&desc->mType, true);
1251 }
1252 }
1253 }
1254}
1255
Andy Hung4b17e882023-07-07 13:47:37 -07001256void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001257 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001258 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001259{
1260 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1261
1262 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1263
1264 if (suspend) {
1265 if (index >= 0) {
1266 sessionEffects = mSuspendedSessions.valueAt(index);
1267 } else {
1268 mSuspendedSessions.add(sessionId, sessionEffects);
1269 }
1270 } else {
1271 if (index < 0) {
1272 return;
1273 }
1274 sessionEffects = mSuspendedSessions.valueAt(index);
1275 }
1276
1277
Andy Hung116bc262023-06-20 18:56:17 -07001278 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001279 if (type != NULL) {
1280 key = type->timeLow;
1281 }
1282 index = sessionEffects.indexOfKey(key);
1283
1284 sp<SuspendedSessionDesc> desc;
1285 if (suspend) {
1286 if (index >= 0) {
1287 desc = sessionEffects.valueAt(index);
1288 } else {
1289 desc = new SuspendedSessionDesc();
1290 if (type != NULL) {
1291 desc->mType = *type;
1292 }
1293 sessionEffects.add(key, desc);
1294 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1295 }
1296 desc->mRefCount++;
1297 } else {
1298 if (index < 0) {
1299 return;
1300 }
1301 desc = sessionEffects.valueAt(index);
1302 if (--desc->mRefCount == 0) {
1303 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1304 sessionEffects.removeItemsAt(index);
1305 if (sessionEffects.isEmpty()) {
1306 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1307 sessionId);
1308 mSuspendedSessions.removeItem(sessionId);
1309 }
1310 }
1311 }
1312 if (!sessionEffects.isEmpty()) {
1313 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1314 }
1315}
1316
Andy Hung4b17e882023-07-07 13:47:37 -07001317void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001318 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001319 bool threadLocked)
1320NO_THREAD_SAFETY_ANALYSIS // manual locking
1321{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001322 if (!threadLocked) {
1323 mLock.lock();
1324 }
Eric Laurent81784c32012-11-19 14:55:58 -08001325
Eric Laurent81784c32012-11-19 14:55:58 -08001326 if (mType != RECORD) {
1327 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1328 // another session. This gives the priority to well behaved effect control panels
1329 // and applications not using global effects.
1330 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1331 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001332 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001333 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1334 }
1335 }
1336
Eric Laurent6b446ce2019-12-13 10:56:31 -08001337 if (!threadLocked) {
1338 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001339 }
1340}
1341
Eric Laurent4c415062016-06-17 16:14:16 -07001342// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07001343status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001344 const effect_descriptor_t *desc, audio_session_t sessionId)
1345{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001346 // No global output effect sessions on record threads
1347 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1348 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001349 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1350 desc->name, mThreadName);
1351 return BAD_VALUE;
1352 }
1353 // only pre processing effects on record thread
1354 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1355 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1356 desc->name, mThreadName);
1357 return BAD_VALUE;
1358 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001359
1360 // always allow effects without processing load or latency
1361 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1362 return NO_ERROR;
1363 }
1364
Eric Laurent4c415062016-06-17 16:14:16 -07001365 audio_input_flags_t flags = mInput->flags;
1366 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1367 if (flags & AUDIO_INPUT_FLAG_RAW) {
1368 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1369 desc->name, mThreadName);
1370 return BAD_VALUE;
1371 }
1372 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1373 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1374 desc->name, mThreadName);
1375 return BAD_VALUE;
1376 }
1377 }
jiabineb3bda02020-06-30 14:07:03 -07001378
Andy Hung116bc262023-06-20 18:56:17 -07001379 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001380 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1381 return BAD_VALUE;
1382 }
Eric Laurent4c415062016-06-17 16:14:16 -07001383 return NO_ERROR;
1384}
1385
1386// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07001387status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001388 const effect_descriptor_t *desc, audio_session_t sessionId)
1389{
1390 // no preprocessing on playback threads
1391 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001392 ALOGW("%s: pre processing effect %s created on playback"
1393 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001394 return BAD_VALUE;
1395 }
1396
Eric Laurent3e4de772017-07-16 16:55:08 -07001397 // always allow effects without processing load or latency
1398 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1399 return NO_ERROR;
1400 }
1401
Andy Hung116bc262023-06-20 18:56:17 -07001402 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
jiabineb3bda02020-06-30 14:07:03 -07001403 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1404 __func__);
1405 return BAD_VALUE;
1406 }
1407
Eric Laurentf690c462021-09-17 14:47:03 +02001408 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1409 && mType != SPATIALIZER) {
1410 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1411 __func__, mType);
1412 return BAD_VALUE;
1413 }
1414
Eric Laurent4c415062016-06-17 16:14:16 -07001415 switch (mType) {
1416 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001417 audio_output_flags_t flags = mOutput->flags;
1418 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1419 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1420 // global effects are applied only to non fast tracks if they are SW
1421 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1422 break;
1423 }
1424 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1425 // only post processing on output stage session
1426 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001427 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1428 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001429 return BAD_VALUE;
1430 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001431 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1432 // only post processing on output stage session
1433 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001434 ALOGW("%s: non post processing effect %s not allowed on device session",
1435 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001436 return BAD_VALUE;
1437 }
Eric Laurent4c415062016-06-17 16:14:16 -07001438 } else {
1439 // no restriction on effects applied on non fast tracks
1440 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1441 break;
1442 }
1443 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001444
Eric Laurent4c415062016-06-17 16:14:16 -07001445 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001446 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001447 return BAD_VALUE;
1448 }
1449 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001450 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1451 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001452 return BAD_VALUE;
1453 }
1454 }
1455 } break;
1456 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001457 // nothing actionable on offload threads, if the effect:
1458 // - is offloadable: the effect can be created
1459 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1460 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001461 break;
1462 case DIRECT:
1463 // Reject any effect on Direct output threads for now, since the format of
1464 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001465 ALOGW("%s: effect %s on DIRECT output thread %s",
1466 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001467 return BAD_VALUE;
1468 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001469 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001470 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1471 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001472 return BAD_VALUE;
1473 }
1474 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001475 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1476 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001477 return BAD_VALUE;
1478 }
1479 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001480 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1481 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001482 return BAD_VALUE;
1483 }
1484 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001485 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001486 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1487 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1488 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1489 // are supported and added after the spatializer.
1490 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1491 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1492 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001493 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001494 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1495 // only post processing , downmixer or spatializer effects on output stage session
1496 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1497 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1498 break;
1499 }
1500 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1501 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1502 __func__, desc->name);
1503 return BAD_VALUE;
1504 }
1505 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1506 // only post processing on output stage session
1507 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1508 ALOGW("%s: non post processing effect %s not allowed on device session",
1509 __func__, desc->name);
1510 return BAD_VALUE;
1511 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001512 }
1513 break;
jiabinc658e452022-10-21 20:52:21 +00001514 case BIT_PERFECT:
1515 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1516 // Allow HW accelerated effects of tunnel type
1517 break;
1518 }
1519 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1520 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1521 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1522 // 3) there is any bit-perfect track with the given session id.
1523 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1524 sessionId == AUDIO_SESSION_DEVICE) {
1525 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1526 __func__, desc->name, mThreadName);
1527 return BAD_VALUE;
1528 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1529 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1530 __func__, desc->name, sessionId);
1531 return BAD_VALUE;
1532 }
1533 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001534 default:
1535 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1536 }
1537
1538 return NO_ERROR;
1539}
1540
Eric Laurent81784c32012-11-19 14:55:58 -08001541// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07001542sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001543 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001544 const sp<IEffectClient>& effectClient,
1545 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001546 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001547 effect_descriptor_t *desc,
1548 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001549 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001550 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001551 bool probe,
1552 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001553{
Andy Hung116bc262023-06-20 18:56:17 -07001554 sp<IAfEffectModule> effect;
1555 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001556 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001557 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001558 bool chainCreated = false;
1559 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001560 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001561
1562 lStatus = initCheck();
1563 if (lStatus != NO_ERROR) {
1564 ALOGW("createEffect_l() Audio driver not initialized.");
1565 goto Exit;
1566 }
1567
Eric Laurent81784c32012-11-19 14:55:58 -08001568 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1569
1570 { // scope for mLock
1571 Mutex::Autolock _l(mLock);
1572
Eric Laurent4c415062016-06-17 16:14:16 -07001573 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001574 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001575 goto Exit;
1576 }
1577
Eric Laurent81784c32012-11-19 14:55:58 -08001578 // check for existing effect chain with the requested audio session
1579 chain = getEffectChain_l(sessionId);
1580 if (chain == 0) {
1581 // create a new chain for this session
1582 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001583 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001584 addEffectChain_l(chain);
1585 chain->setStrategy(getStrategyForSession_l(sessionId));
1586 chainCreated = true;
1587 } else {
1588 effect = chain->getEffectFromDesc_l(desc);
1589 }
1590
1591 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1592
1593 if (effect == 0) {
Andy Hung7535ed92023-07-17 17:05:00 -07001594 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001595 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001596 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001597 if (lStatus != NO_ERROR) {
1598 goto Exit;
1599 }
1600 effectCreated = true;
1601
jiabinc52b1ff2019-10-31 17:20:42 -07001602 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001603 effect->setDevices(outDeviceTypeAddrs());
1604 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung7535ed92023-07-17 17:05:00 -07001605 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001606 effect->setAudioSource(mAudioSource);
1607 }
jiabin1319f5a2021-03-30 22:21:24 +00001608 if (effect->isHapticGenerator()) {
1609 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1610 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001611 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung7535ed92023-07-17 17:05:00 -07001612 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001613 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001614 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001615 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001616 }
1617 }
Eric Laurent81784c32012-11-19 14:55:58 -08001618 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001619 handle = IAfEffectHandle::create(
1620 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001621 lStatus = handle->initCheck();
1622 if (lStatus == OK) {
1623 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001624 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001625 }
Eric Laurent81784c32012-11-19 14:55:58 -08001626 if (enabled != NULL) {
1627 *enabled = (int)effect->isEnabled();
1628 }
1629 }
1630
1631Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001632 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001633 Mutex::Autolock _l(mLock);
1634 if (effectCreated) {
1635 chain->removeEffect_l(effect);
1636 }
Eric Laurent81784c32012-11-19 14:55:58 -08001637 if (chainCreated) {
1638 removeEffectChain_l(chain);
1639 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001640 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001641 }
1642
Glenn Kasten9156ef32013-08-06 15:39:08 -07001643 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001644 return handle;
1645}
1646
Andy Hung4b17e882023-07-07 13:47:37 -07001647void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001648 bool unpinIfLast)
1649{
1650 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001651 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001652 {
1653 Mutex::Autolock _l(mLock);
Andy Hung116bc262023-06-20 18:56:17 -07001654 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001655 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001656 return;
1657 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001658 effect = effectBase->asEffectModule();
1659 if (effect == nullptr) {
1660 return;
1661 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001662 // restore suspended effects if the disconnected handle was enabled and the last one.
1663 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1664 if (remove) {
1665 removeEffect_l(effect, true);
1666 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001667 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001668 }
1669 if (remove) {
Andy Hung7535ed92023-07-17 17:05:00 -07001670 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001671 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001672 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001673 }
1674 }
1675}
1676
Andy Hung4b17e882023-07-07 13:47:37 -07001677void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001678 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001679 Mutex::Autolock _l(mLock);
1680 broadcast_l();
1681 }
1682 if (!effect->isOffloadable()) {
1683 if (mType == ThreadBase::OFFLOAD) {
1684 PlaybackThread *t = (PlaybackThread *)this;
1685 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1686 }
1687 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung7535ed92023-07-17 17:05:00 -07001688 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001689 }
1690 }
1691}
1692
Andy Hung4b17e882023-07-07 13:47:37 -07001693void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001694 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001695 Mutex::Autolock _l(mLock);
1696 broadcast_l();
1697 }
1698}
1699
Andy Hung4b17e882023-07-07 13:47:37 -07001700sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung3e4c8742023-06-29 21:19:25 -07001701 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001702{
1703 Mutex::Autolock _l(mLock);
1704 return getEffect_l(sessionId, effectId);
1705}
1706
Andy Hung4b17e882023-07-07 13:47:37 -07001707sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung3e4c8742023-06-29 21:19:25 -07001708 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001709{
Andy Hung116bc262023-06-20 18:56:17 -07001710 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001711 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1712}
1713
Andy Hung4b17e882023-07-07 13:47:37 -07001714std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001715{
Andy Hung116bc262023-06-20 18:56:17 -07001716 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent6c796322019-04-09 14:13:17 -07001717 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1718}
1719
Eric Laurent81784c32012-11-19 14:55:58 -08001720// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1721// PlaybackThread::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07001722status_t ThreadBase::addEffect_l(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001723{
1724 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001725 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001726 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001727 bool chainCreated = false;
1728
Eric Laurent5baf2af2013-09-12 17:37:00 -07001729 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001730 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001731 this, effect->desc().name, effect->desc().flags);
1732
Eric Laurent81784c32012-11-19 14:55:58 -08001733 if (chain == 0) {
1734 // create a new chain for this session
1735 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001736 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001737 addEffectChain_l(chain);
1738 chain->setStrategy(getStrategyForSession_l(sessionId));
1739 chainCreated = true;
1740 }
1741 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1742
1743 if (chain->getEffectFromId_l(effect->id()) != 0) {
1744 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1745 this, effect->desc().name, chain.get());
1746 return BAD_VALUE;
1747 }
1748
Eric Laurent5baf2af2013-09-12 17:37:00 -07001749 effect->setOffloaded(mType == OFFLOAD, mId);
1750
Eric Laurent81784c32012-11-19 14:55:58 -08001751 status_t status = chain->addEffect_l(effect);
1752 if (status != NO_ERROR) {
1753 if (chainCreated) {
1754 removeEffectChain_l(chain);
1755 }
1756 return status;
1757 }
1758
jiabin8f278ee2019-11-11 12:16:27 -08001759 effect->setDevices(outDeviceTypeAddrs());
1760 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung7535ed92023-07-17 17:05:00 -07001761 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001762 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001763
Eric Laurent81784c32012-11-19 14:55:58 -08001764 return NO_ERROR;
1765}
1766
Andy Hung4b17e882023-07-07 13:47:37 -07001767void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001768
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001769 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001770 effect_descriptor_t desc = effect->desc();
1771 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1772 detachAuxEffect_l(effect->id());
1773 }
1774
Andy Hung116bc262023-06-20 18:56:17 -07001775 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001776 if (chain != 0) {
1777 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001778 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001779 removeEffectChain_l(chain);
1780 }
1781 } else {
1782 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1783 }
1784}
1785
Andy Hung4b17e882023-07-07 13:47:37 -07001786void ThreadBase::lockEffectChains_l(
Andy Hung116bc262023-06-20 18:56:17 -07001787 Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-10-06 12:09:49 -07001788NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001789{
1790 effectChains = mEffectChains;
1791 for (size_t i = 0; i < mEffectChains.size(); i++) {
1792 mEffectChains[i]->lock();
1793 }
1794}
1795
Andy Hung4b17e882023-07-07 13:47:37 -07001796void ThreadBase::unlockEffectChains(
Andy Hung116bc262023-06-20 18:56:17 -07001797 const Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-10-06 12:09:49 -07001798NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001799{
1800 for (size_t i = 0; i < effectChains.size(); i++) {
1801 effectChains[i]->unlock();
1802 }
1803}
1804
Andy Hung4b17e882023-07-07 13:47:37 -07001805sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001806{
1807 Mutex::Autolock _l(mLock);
1808 return getEffectChain_l(sessionId);
1809}
1810
Andy Hung4b17e882023-07-07 13:47:37 -07001811sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001812 const
Eric Laurent81784c32012-11-19 14:55:58 -08001813{
1814 size_t size = mEffectChains.size();
1815 for (size_t i = 0; i < size; i++) {
1816 if (mEffectChains[i]->sessionId() == sessionId) {
1817 return mEffectChains[i];
1818 }
1819 }
1820 return 0;
1821}
1822
Andy Hung4b17e882023-07-07 13:47:37 -07001823void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001824{
1825 Mutex::Autolock _l(mLock);
1826 size_t size = mEffectChains.size();
1827 for (size_t i = 0; i < size; i++) {
1828 mEffectChains[i]->setMode_l(mode);
1829 }
1830}
1831
Andy Hung4b17e882023-07-07 13:47:37 -07001832void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001833{
1834 config->type = AUDIO_PORT_TYPE_MIX;
1835 config->ext.mix.handle = mId;
1836 config->sample_rate = mSampleRate;
1837 config->format = mFormat;
1838 config->channel_mask = mChannelMask;
1839 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1840 AUDIO_PORT_CONFIG_FORMAT;
1841}
1842
Andy Hung4b17e882023-07-07 13:47:37 -07001843void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001844{
1845 Mutex::Autolock _l(mLock);
1846 if (mSystemReady) {
1847 return;
1848 }
1849 mSystemReady = true;
1850
1851 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1852 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1853 }
1854 mPendingConfigEvents.clear();
1855}
1856
Andy Hungdae27702016-10-31 14:01:16 -07001857template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001858ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001859 ssize_t index = mActiveTracks.indexOf(track);
1860 if (index >= 0) {
1861 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1862 return index;
1863 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001864 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001865 mActiveTracksGeneration++;
1866 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001867 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001868 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001869 return mActiveTracks.add(track);
1870}
1871
1872template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001873ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001874 ssize_t index = mActiveTracks.remove(track);
1875 if (index < 0) {
1876 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1877 return index;
1878 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001879 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001880 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001881 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001882 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001883 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001884#ifdef TEE_SINK
1885 track->dumpTee(-1 /* fd */, "_REMOVE");
1886#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001887 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001888 return index;
1889}
1890
1891template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001892void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001893 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001894 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001895 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001896 }
1897 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001898 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001899 mActiveTracks.clear();
1900 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001901}
1902
1903template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001904void ThreadBase::ActiveTracks<T>::updatePowerState(
Andy Hung920f6572022-10-06 12:09:49 -07001905 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001906 // Updates ActiveTracks client uids to the thread wakelock.
1907 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1908 thread->updateWakeLockUids_l(getWakeLockUids());
1909 mLastActiveTracksGeneration = mActiveTracksGeneration;
1910 }
Andy Hungdae27702016-10-31 14:01:16 -07001911}
Eric Laurent83b88082014-06-20 18:31:16 -07001912
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001913template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001914bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001915 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001916 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001917
1918 for (const sp<T> &track : mActiveTracks) {
1919 // Do not short-circuit as all hasChanged states must be reset
1920 // as all the metadata are going to be sent
1921 hasChanged |= track->readAndClearHasChanged();
1922 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001923 return hasChanged;
1924}
1925
1926template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001927void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001928 const char *funcName, const sp<T> &track) const {
1929 if (mLocalLog != nullptr) {
1930 String8 result;
1931 track->appendDump(result, false /* active */);
1932 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1933 }
1934}
1935
Andy Hung4b17e882023-07-07 13:47:37 -07001936void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08001937{
1938 // Thread could be blocked waiting for async
1939 // so signal it to handle state changes immediately
1940 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1941 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1942 mSignalPending = true;
1943 mWaitWorkCV.broadcast();
1944}
1945
Andy Hungd0979812019-02-21 15:51:44 -08001946// Call only from threadLoop() or when it is idle.
1947// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hung4b17e882023-07-07 13:47:37 -07001948void ThreadBase::sendStatistics(bool force)
Andy Hungd0979812019-02-21 15:51:44 -08001949{
1950 // Do not log if we have no stats.
1951 // We choose the timestamp verifier because it is the most likely item to be present.
1952 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1953 if (nstats == 0) {
1954 return;
1955 }
1956
1957 // Don't log more frequently than once per 12 hours.
1958 // We use BOOTTIME to include suspend time.
1959 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1960 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1961 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1962 return;
1963 }
1964
1965 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1966 mLastRecordedTimeNs = timeNs;
1967
Ray Essickf27e9872019-12-07 06:28:46 -08001968 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001969
1970#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1971
1972 // thread configuration
1973 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1974 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1975 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1976 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1977 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1978 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1979 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001980 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1981 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001982
1983 // thread statistics
1984 if (mIoJitterMs.getN() > 0) {
1985 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1986 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1987 }
1988 if (mProcessTimeMs.getN() > 0) {
1989 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1990 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1991 }
1992 const auto tsjitter = mTimestampVerifier.getJitterMs();
1993 if (tsjitter.getN() > 0) {
1994 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1995 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1996 }
1997 if (mLatencyMs.getN() > 0) {
1998 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1999 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2000 }
Robert Wu06db0a32021-08-10 19:05:34 +00002001 if (mMonopipePipeDepthStats.getN() > 0) {
2002 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2003 mMonopipePipeDepthStats.getMean());
2004 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2005 mMonopipePipeDepthStats.getStdDev());
2006 }
Andy Hungd0979812019-02-21 15:51:44 -08002007
2008 item->selfrecord();
2009}
2010
Andy Hung4b17e882023-07-07 13:47:37 -07002011product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002012{
Andy Hung7535ed92023-07-17 17:05:00 -07002013 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002014 return PRODUCT_STRATEGY_NONE;
2015 }
2016 return AudioSystem::getStrategyForStream(stream);
2017}
2018
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002019// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07002020void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002021 const sp<audio_utils::MelProcessor>& /*processor*/)
2022{
2023 // Do nothing
2024 ALOGW("%s: ThreadBase does not support CSD", __func__);
2025}
2026
2027// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07002028void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002029{
2030 // Do nothing
2031 ALOGW("%s: ThreadBase does not support CSD", __func__);
2032}
2033
Eric Laurent81784c32012-11-19 14:55:58 -08002034// ----------------------------------------------------------------------------
2035// Playback
2036// ----------------------------------------------------------------------------
2037
Andy Hung7535ed92023-07-17 17:05:00 -07002038PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002039 AudioStreamOut* output,
2040 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002041 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002042 bool systemReady,
2043 audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07002044 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002045 mNormalFrameCount(0), mSinkBuffer(NULL),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002046 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002047 mMixerBuffer(NULL),
2048 mMixerBufferSize(0),
2049 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2050 mMixerBufferValid(false),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002051 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002052 mEffectBuffer(NULL),
2053 mEffectBufferSize(0),
2054 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2055 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002056 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002057 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002058 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002059 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002060 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002061 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002062 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002063 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002064 mMixerStatus(MIXER_IDLE),
2065 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002066 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002067 mBytesRemaining(0),
2068 mCurrentWriteLength(0),
2069 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002070 mWriteAckSequence(0),
2071 mDrainSequence(0),
Andy Hung1b6d46a2023-07-19 16:22:58 -07002072 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002073 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002074 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002075 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002076 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002077 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002078 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002079{
Glenn Kastend7dca052015-03-05 16:05:54 -08002080 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung7535ed92023-07-17 17:05:00 -07002081 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002082
2083 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2084 // it would be safer to explicitly pass initial masterVolume/masterMute as
2085 // parameter.
2086 //
2087 // If the HAL we are using has support for master volume or master mute,
2088 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2089 // and the mute set to false).
Andy Hung7535ed92023-07-17 17:05:00 -07002090 mMasterVolume = afThreadCallback->masterVolume_l();
2091 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002092 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002093 if (mOutput->audioHwDev->canSetMasterVolume()) {
2094 mMasterVolume = 1.0;
2095 }
2096
2097 if (mOutput->audioHwDev->canSetMasterMute()) {
2098 mMasterMute = false;
2099 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002100 mIsMsdDevice = strcmp(
2101 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002102 }
2103
Eric Laurentf1f22e72021-07-13 14:04:14 +02002104 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2105 mMixerChannelMask = mixerConfig->channel_mask;
2106 }
2107
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002108 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002109
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002110 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002111 && mMixerChannelMask != mChannelMask) {
2112 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2113 mChannelMask, mMixerChannelMask);
2114 }
2115
Andy Hungc8fddf32018-08-08 18:32:37 -07002116 // TODO: We may also match on address as well as device type for
2117 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002118 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002119 // TODO: This property should be ensure that only contains one single device type.
2120 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2121 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002122 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2123 : AUDIO_DEVICE_NONE));
2124 }
2125
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002126 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2127 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002128 mStreamTypes[stream].volume = 0.0f;
Andy Hung7535ed92023-07-17 17:05:00 -07002129 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002130 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002131 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002132 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2133 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002134 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2135 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002136}
2137
Andy Hung4b17e882023-07-07 13:47:37 -07002138PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002139{
Andy Hung7535ed92023-07-17 17:05:00 -07002140 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002141 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002142 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002143 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002144 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002145}
2146
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002147// Thread virtuals
2148
Andy Hung4b17e882023-07-07 13:47:37 -07002149void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002150{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002151 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002152 ALOGE("The stream is not open yet"); // This should not happen.
2153 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002154 // Callbacks take strong or weak pointers as a parameter.
2155 // Since PlaybackThread passes itself as a callback handler, it can only
2156 // be done outside of the constructor. Creating weak and especially strong
2157 // pointers to a refcounted object in its own constructor is strongly
2158 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2159 // Even if a function takes a weak pointer, it is possible that it will
2160 // need to convert it to a strong pointer down the line.
2161 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2162 mOutput->stream->setCallback(this) == OK) {
2163 mUseAsyncWrite = true;
Andy Hung4b17e882023-07-07 13:47:37 -07002164 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002165 }
2166
jiabinf6eb4c32020-02-25 14:06:25 -08002167 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002168 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002169 }
2170 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002171 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002172 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002173}
2174
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002175// ThreadBase virtuals
Andy Hung4b17e882023-07-07 13:47:37 -07002176void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002177{
2178 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002179 status_t result = mOutput->stream->exit();
2180 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002181}
2182
Andy Hung4b17e882023-07-07 13:47:37 -07002183void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002184{
Eric Laurent81784c32012-11-19 14:55:58 -08002185 String8 result;
2186
Marco Nelissenb2208842014-02-07 14:00:50 -08002187 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002188 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2189 const stream_type_t *st = &mStreamTypes[i];
2190 if (i > 0) {
2191 result.appendFormat(", ");
2192 }
2193 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2194 if (st->mute) {
2195 result.append("M");
2196 }
2197 }
2198 result.append("\n");
2199 write(fd, result.string(), result.length());
2200 result.clear();
2201
Eric Laurent81784c32012-11-19 14:55:58 -08002202 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2203 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002204 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002205 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002206
2207 size_t numtracks = mTracks.size();
2208 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002209 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002210 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002211 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002212 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002213 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002214 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002215 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002216 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002217 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002218 if (track != 0) {
2219 bool active = mActiveTracks.indexOf(track) >= 0;
2220 if (active) {
2221 numactiveseen++;
2222 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002223 result.append(prefix);
2224 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002225 }
2226 }
2227 } else {
2228 result.append("\n");
2229 }
2230 if (numactiveseen != numactive) {
2231 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002232 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002233 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002234 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002235 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002236 for (size_t i = 0; i < numactive; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002237 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002238 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002239 result.append(prefix);
2240 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002241 }
2242 }
2243 }
2244
2245 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002246}
2247
Andy Hung4b17e882023-07-07 13:47:37 -07002248void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002249{
Andy Hung04cb8f72020-03-20 13:44:33 -07002250 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002251 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002252 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2253 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002254 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2255 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2256 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2257 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002258 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002259 dprintf(fd, " Total writes: %d\n", mNumWrites);
2260 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2261 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2262 dprintf(fd, " Suspend count: %d\n", mSuspended);
2263 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2264 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2265 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2266 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002267 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002268 AudioStreamOut *output = mOutput;
2269 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002270 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002271 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002272 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2273 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2274 if (mPipeSink.get() != nullptr) {
2275 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2276 }
2277 if (output != nullptr) {
2278 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002279 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002280 }
Eric Laurent81784c32012-11-19 14:55:58 -08002281}
2282
Eric Laurent81784c32012-11-19 14:55:58 -08002283// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07002284sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002285 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002286 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002287 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002288 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002289 audio_format_t format,
2290 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002291 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002292 size_t *pNotificationFrameCount,
2293 uint32_t notificationsPerBuffer,
2294 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002295 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002296 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002297 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002298 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002299 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002300 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002301 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002302 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002303 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002304 bool isSpatialized,
2305 bool isBitPerfect)
Eric Laurent81784c32012-11-19 14:55:58 -08002306{
Glenn Kasten74935e42013-12-19 08:56:45 -08002307 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002308 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung11e74242023-06-26 19:20:57 -07002309 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002310 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002311 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002312 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002313 uint32_t sampleRate;
2314
2315 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2316 lStatus = BAD_VALUE;
2317 goto Exit;
2318 }
Eric Laurent21da6472017-11-09 16:29:26 -08002319
2320 if (*pSampleRate == 0) {
2321 *pSampleRate = mSampleRate;
2322 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002323 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002324
2325 // special case for FAST flag considered OK if fast mixer is present
2326 if (hasFastMixer()) {
2327 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2328 }
2329
2330 // Check if requested flags are compatible with output stream flags
2331 if ((*flags & outputFlags) != *flags) {
2332 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2333 *flags, outputFlags);
2334 *flags = (audio_output_flags_t)(*flags & outputFlags);
2335 }
Eric Laurent81784c32012-11-19 14:55:58 -08002336
jiabinc658e452022-10-21 20:52:21 +00002337 if (isBitPerfect) {
Andy Hung116bc262023-06-20 18:56:17 -07002338 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002339 if (chain.get() != nullptr) {
2340 // Bit-perfect is required according to the configuration and preferred mixer
2341 // attributes, but it is not in the output flag from the client's request. Explicitly
2342 // adding bit-perfect flag to check the compatibility
2343 audio_output_flags_t flagsToCheck =
2344 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2345 chain->checkOutputFlagCompatibility(&flagsToCheck);
2346 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2347 ALOGE("%s cannot create track as there is data-processing effect attached to "
2348 "given session id(%d)", __func__, sessionId);
2349 lStatus = BAD_VALUE;
2350 goto Exit;
2351 }
2352 *flags = flagsToCheck;
2353 }
2354 }
2355
Eric Laurent81784c32012-11-19 14:55:58 -08002356 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002357 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002358 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002359 // PCM data
2360 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002361 // TODO: extract as a data library function that checks that a computationally
2362 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002363 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002364 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2365 (channelMask == AUDIO_CHANNEL_OUT_MONO
2366 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002367 // hardware sample rate
2368 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002369 // normal mixer has an associated fast mixer
2370 hasFastMixer() &&
2371 // there are sufficient fast track slots available
2372 (mFastTrackAvailMask != 0)
2373 // FIXME test that MixerThread for this fast track has a capable output HAL
2374 // FIXME add a permission test also?
2375 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002376 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2377 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002378 // read the fast track multiplier property the first time it is needed
2379 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2380 if (ok != 0) {
2381 ALOGE("%s pthread_once failed: %d", __func__, ok);
2382 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002383 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002384 }
Eric Laurent4c415062016-06-17 16:14:16 -07002385
2386 // check compatibility with audio effects.
2387 { // scope for mLock
2388 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002389 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002390 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002391 AUDIO_SESSION_OUTPUT_STAGE,
2392 AUDIO_SESSION_OUTPUT_MIX,
2393 sessionId,
2394 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002395 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002396 if (chain.get() != nullptr) {
2397 audio_output_flags_t old = *flags;
2398 chain->checkOutputFlagCompatibility(flags);
2399 if (old != *flags) {
2400 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2401 (int)session, (int)old, (int)*flags);
2402 }
Eric Laurent4c415062016-06-17 16:14:16 -07002403 }
2404 }
2405 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002406 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002407 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2408 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002409 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002410 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002411 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002412 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002413 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002414 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002415 audio_is_linear_pcm(format), channelMask, sampleRate,
2416 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002417 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002418 }
2419 }
Eric Laurent21da6472017-11-09 16:29:26 -08002420
2421 if (!audio_has_proportional_frames(format)) {
2422 if (sharedBuffer != 0) {
2423 // Same comment as below about ignoring frameCount parameter for set()
2424 frameCount = sharedBuffer->size();
2425 } else if (frameCount == 0) {
2426 frameCount = mNormalFrameCount;
2427 }
2428 if (notificationFrameCount != frameCount) {
2429 notificationFrameCount = frameCount;
2430 }
2431 } else if (sharedBuffer != 0) {
2432 // FIXME: Ensure client side memory buffers need
2433 // not have additional alignment beyond sample
2434 // (e.g. 16 bit stereo accessed as 32 bit frame).
2435 size_t alignment = audio_bytes_per_sample(format);
2436 if (alignment & 1) {
2437 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2438 alignment = 1;
2439 }
2440 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2441 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2442 if (channelCount > 1) {
2443 // More than 2 channels does not require stronger alignment than stereo
2444 alignment <<= 1;
2445 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002446 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002447 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002448 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002449 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002450 goto Exit;
2451 }
Eric Laurent21da6472017-11-09 16:29:26 -08002452
2453 // When initializing a shared buffer AudioTrack via constructors,
2454 // there's no frameCount parameter.
2455 // But when initializing a shared buffer AudioTrack via set(),
2456 // there _is_ a frameCount parameter. We silently ignore it.
2457 frameCount = sharedBuffer->size() / frameSize;
2458 } else {
2459 size_t minFrameCount = 0;
2460 // For fast tracks we try to respect the application's request for notifications per buffer.
2461 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2462 if (notificationsPerBuffer > 0) {
2463 // Avoid possible arithmetic overflow during multiplication.
2464 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2465 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2466 notificationsPerBuffer, mFrameCount);
2467 } else {
2468 minFrameCount = mFrameCount * notificationsPerBuffer;
2469 }
2470 }
2471 } else {
2472 // For normal PCM streaming tracks, update minimum frame count.
2473 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2474 // cover audio hardware latency.
2475 // This is probably too conservative, but legacy application code may depend on it.
2476 // If you change this calculation, also review the start threshold which is related.
2477 uint32_t latencyMs = latency_l();
2478 if (latencyMs == 0) {
2479 ALOGE("Error when retrieving output stream latency");
2480 lStatus = UNKNOWN_ERROR;
2481 goto Exit;
2482 }
2483
2484 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2485 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2486
Eric Laurent81784c32012-11-19 14:55:58 -08002487 }
Eric Laurent21da6472017-11-09 16:29:26 -08002488 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002489 frameCount = minFrameCount;
2490 }
Eric Laurent81784c32012-11-19 14:55:58 -08002491 }
Eric Laurent21da6472017-11-09 16:29:26 -08002492
2493 // Make sure that application is notified with sufficient margin before underrun.
2494 // The client can divide the AudioTrack buffer into sub-buffers,
2495 // and expresses its desire to server as the notification frame count.
2496 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2497 size_t maxNotificationFrames;
2498 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2499 // notify every HAL buffer, regardless of the size of the track buffer
2500 maxNotificationFrames = mFrameCount;
2501 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002502 // Triple buffer the notification period for a triple buffered mixer period;
2503 // otherwise, double buffering for the notification period is fine.
2504 //
2505 // TODO: This should be moved to AudioTrack to modify the notification period
2506 // on AudioTrack::setBufferSizeInFrames() changes.
2507 const int nBuffering =
2508 (uint64_t{frameCount} * mSampleRate)
2509 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2510
Eric Laurent21da6472017-11-09 16:29:26 -08002511 maxNotificationFrames = frameCount / nBuffering;
2512 // If client requested a fast track but this was denied, then use the smaller maximum.
2513 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2514 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2515 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2516 maxNotificationFrames = maxNotificationFramesFastDenied;
2517 }
2518 }
2519 }
2520 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2521 if (notificationFrameCount == 0) {
2522 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2523 maxNotificationFrames, frameCount);
2524 } else {
2525 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2526 notificationFrameCount, maxNotificationFrames, frameCount);
2527 }
2528 notificationFrameCount = maxNotificationFrames;
2529 }
2530 }
2531
Glenn Kasten74935e42013-12-19 08:56:45 -08002532 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002533 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002534
Glenn Kastenc3df8382014-03-13 15:05:25 -07002535 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002536 case BIT_PERFECT:
2537 if (isBitPerfect) {
2538 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2539 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2540 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2541 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2542 mChannelMask);
2543 lStatus = BAD_VALUE;
2544 goto Exit;
2545 }
2546 }
2547 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002548
2549 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002550 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002551 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002552 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2553 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002554 sampleRate, format, channelMask, mOutput, mFormat);
2555 lStatus = BAD_VALUE;
2556 goto Exit;
2557 }
2558 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002559 break;
2560
2561 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002562 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002563 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2564 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002565 sampleRate, format, channelMask, mOutput, mFormat);
2566 lStatus = BAD_VALUE;
2567 goto Exit;
2568 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002569 break;
2570
2571 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002572 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002573 ALOGE("createTrack_l() Bad parameter: format %#x \""
2574 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002575 format, mOutput, mFormat);
2576 lStatus = BAD_VALUE;
2577 goto Exit;
2578 }
Andy Hungcd044842014-08-07 11:04:34 -07002579 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002580 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2581 lStatus = BAD_VALUE;
2582 goto Exit;
2583 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002584 break;
2585
Eric Laurent81784c32012-11-19 14:55:58 -08002586 }
2587
2588 lStatus = initCheck();
2589 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002590 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002591 goto Exit;
2592 }
2593
2594 { // scope for mLock
2595 Mutex::Autolock _l(mLock);
2596
2597 // all tracks in same audio session must share the same routing strategy otherwise
2598 // conflicts will happen when tracks are moved from one output to another by audio policy
2599 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002600 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002601 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002602 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002603 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002604 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002605 if (sessionId == t->sessionId() && strategy != actual) {
2606 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2607 strategy, actual);
2608 lStatus = BAD_VALUE;
2609 goto Exit;
2610 }
2611 }
2612 }
2613
yucliuc9c49cd2020-07-13 16:25:21 -07002614 // Set DIRECT flag if current thread is DirectOutputThread. This can
2615 // happen when the playback is rerouted to direct output thread by
2616 // dynamic audio policy.
2617 // Do NOT report the flag changes back to client, since the client
2618 // doesn't explicitly request a direct flag.
2619 audio_output_flags_t trackFlags = *flags;
2620 if (mType == DIRECT) {
2621 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2622 }
2623
Andy Hung11e74242023-06-26 19:20:57 -07002624 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002625 channelMask, frameCount,
2626 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002627 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung11e74242023-06-26 19:20:57 -07002628 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002629 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002630
Glenn Kasten03003332013-08-06 15:40:54 -07002631 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2632 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002633 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002634 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002635 goto Exit;
2636 }
2637 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002638 {
2639 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2640 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002641 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002642 }
2643 }
Eric Laurent81784c32012-11-19 14:55:58 -08002644
Andy Hung116bc262023-06-20 18:56:17 -07002645 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002646 if (chain != 0) {
2647 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2648 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002649 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002650 chain->incTrackCnt();
2651 }
2652
Eric Laurent05067782016-06-01 18:27:28 -07002653 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002654 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2655 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2656 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002657 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002658 }
2659 }
2660
2661 lStatus = NO_ERROR;
2662
2663Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002664 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002665 return track;
2666}
2667
Andy Hung1bc088a2018-02-09 15:57:31 -08002668template<typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07002669ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002670{
Andy Hungc0691382018-09-12 18:01:57 -07002671 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002672 const ssize_t index = mTracks.remove(track);
2673 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002674 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002675 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002676 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002677 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002678 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002679 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002680 }
2681 return index;
2682}
2683
Andy Hung4b17e882023-07-07 13:47:37 -07002684uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002685{
2686 return latency;
2687}
2688
Andy Hung4b17e882023-07-07 13:47:37 -07002689uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002690{
2691 Mutex::Autolock _l(mLock);
2692 return latency_l();
2693}
Andy Hung4b17e882023-07-07 13:47:37 -07002694uint32_t PlaybackThread::latency_l() const
Eric Laurent81784c32012-11-19 14:55:58 -08002695{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002696 uint32_t latency;
2697 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2698 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002699 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002700 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002701}
2702
Andy Hung4b17e882023-07-07 13:47:37 -07002703void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002704{
2705 Mutex::Autolock _l(mLock);
2706 // Don't apply master volume in SW if our HAL can do it for us.
2707 if (mOutput && mOutput->audioHwDev &&
2708 mOutput->audioHwDev->canSetMasterVolume()) {
2709 mMasterVolume = 1.0;
2710 } else {
2711 mMasterVolume = value;
2712 }
2713}
2714
Andy Hung4b17e882023-07-07 13:47:37 -07002715void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002716{
2717 mMasterBalance.store(balance);
2718}
2719
Andy Hung4b17e882023-07-07 13:47:37 -07002720void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002721{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002722 if (isDuplicating()) {
2723 return;
2724 }
Eric Laurent81784c32012-11-19 14:55:58 -08002725 Mutex::Autolock _l(mLock);
2726 // Don't apply master mute in SW if our HAL can do it for us.
2727 if (mOutput && mOutput->audioHwDev &&
2728 mOutput->audioHwDev->canSetMasterMute()) {
2729 mMasterMute = false;
2730 } else {
2731 mMasterMute = muted;
2732 }
2733}
2734
Andy Hung4b17e882023-07-07 13:47:37 -07002735void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002736{
2737 Mutex::Autolock _l(mLock);
2738 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002739 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002740}
2741
Andy Hung4b17e882023-07-07 13:47:37 -07002742void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002743{
2744 Mutex::Autolock _l(mLock);
2745 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002746 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002747}
2748
Andy Hung4b17e882023-07-07 13:47:37 -07002749float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002750{
2751 Mutex::Autolock _l(mLock);
2752 return mStreamTypes[stream].volume;
2753}
2754
Andy Hung4b17e882023-07-07 13:47:37 -07002755void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002756{
2757 mOutput->stream->setVolume(left, right);
2758}
2759
Eric Laurent81784c32012-11-19 14:55:58 -08002760// addTrack_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07002761status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Andy Hung920f6572022-10-06 12:09:49 -07002762NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent81784c32012-11-19 14:55:58 -08002763{
2764 status_t status = ALREADY_EXISTS;
2765
Eric Laurent81784c32012-11-19 14:55:58 -08002766 if (mActiveTracks.indexOf(track) < 0) {
2767 // the track is newly added, make sure it fills up all its
2768 // buffers before playing. This is to ensure the client will
2769 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002770 if (track->isExternalTrack()) {
Andy Hung11e74242023-06-26 19:20:57 -07002771 IAfTrackBase::track_state state = track->state();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002772 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002773 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002774 mLock.lock();
2775 // abort track was stopped/paused while we released the lock
Andy Hung11e74242023-06-26 19:20:57 -07002776 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002777 if (status == NO_ERROR) {
2778 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002779 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002780 mLock.lock();
2781 }
2782 return INVALID_OPERATION;
2783 }
2784 // abort if start is rejected by audio policy manager
2785 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002786 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2787 // current playback thread is reopened, which may happen when clients set preferred
2788 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2789 // immediately.
2790 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002791 }
2792#ifdef ADD_BATTERY_DATA
2793 // to track the speaker usage
2794 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2795#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002796 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002797 }
2798
Eric Laurent51716182016-02-29 18:00:56 -08002799 // set retry count for buffer fill
2800 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002801 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07002802 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002803 } else {
Andy Hung11e74242023-06-26 19:20:57 -07002804 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002805 }
Andy Hung11e74242023-06-26 19:20:57 -07002806 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002807 } else {
Andy Hung11e74242023-06-26 19:20:57 -07002808 track->retryCount() = kMaxTrackStartupRetries;
2809 track->fillingStatus() =
2810 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002811 }
2812
Andy Hung116bc262023-06-20 18:56:17 -07002813 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002814 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2815 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2816 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002817 // Unlock due to VibratorService will lock for this call and will
2818 // call Tracks.mute/unmute which also require thread's lock.
2819 mLock.unlock();
Andy Hung76cb9152023-07-20 21:23:42 -07002820 const os::HapticScale intensity = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002821 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002822 std::optional<media::AudioVibratorInfo> vibratorInfo;
2823 {
2824 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2825 // used to play this track.
Andy Hung7535ed92023-07-17 17:05:00 -07002826 Mutex::Autolock _l(mAfThreadCallback->mutex());
2827 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002828 }
jiabin57303cc2018-12-18 15:45:57 -08002829 mLock.lock();
Simon Bowden62823412022-10-17 14:52:26 +00002830 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002831 if (vibratorInfo) {
2832 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2833 }
2834
jiabin57303cc2018-12-18 15:45:57 -08002835 // Haptic playback should be enabled by vibrator service.
2836 if (track->getHapticPlaybackEnabled()) {
2837 // Disable haptic playback of all active track to ensure only
2838 // one track playing haptic if current track should play haptic.
2839 for (const auto &t : mActiveTracks) {
2840 t->setHapticPlaybackEnabled(false);
2841 }
jiabin245cdd92018-12-07 17:55:15 -08002842 }
jiabine70bc7f2020-06-30 22:07:55 -07002843
2844 // Set haptic intensity for effect
2845 if (chain != nullptr) {
2846 chain->setHapticIntensity_l(track->id(), intensity);
2847 }
jiabin245cdd92018-12-07 17:55:15 -08002848 }
2849
Andy Hung11e74242023-06-26 19:20:57 -07002850 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002851 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002852 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002853 if (chain != 0) {
2854 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2855 track->sessionId());
2856 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002857 }
2858
Andy Hungc2b11cb2020-04-22 09:04:01 -07002859 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002860 status = NO_ERROR;
2861 }
2862
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002863 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002864 return status;
2865}
2866
Andy Hung4b17e882023-07-07 13:47:37 -07002867bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002868{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002869 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002870 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002871 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung11e74242023-06-26 19:20:57 -07002872 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002873 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002874 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002875 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002876 if (track->isPausePending()) {
2877 track->pauseAck();
2878 }
Andy Hung11e74242023-06-26 19:20:57 -07002879 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002880 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002881
2882 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002883}
2884
Andy Hung4b17e882023-07-07 13:47:37 -07002885void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002886{
2887 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002888
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002889 String8 result;
2890 track->appendDump(result, false /* active */);
2891 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002892
Eric Laurent81784c32012-11-19 14:55:58 -08002893 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002894 {
2895 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2896 mAudioTrackCallbacks.erase(track);
2897 }
Eric Laurent81784c32012-11-19 14:55:58 -08002898 if (track->isFastTrack()) {
Andy Hung11e74242023-06-26 19:20:57 -07002899 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002900 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002901 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2902 mFastTrackAvailMask |= 1 << index;
2903 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung11e74242023-06-26 19:20:57 -07002904 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002905 }
Andy Hung116bc262023-06-20 18:56:17 -07002906 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002907 if (chain != 0) {
2908 chain->decTrackCnt();
2909 }
2910}
2911
Andy Hung4b17e882023-07-07 13:47:37 -07002912String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08002913{
Eric Laurent81784c32012-11-19 14:55:58 -08002914 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002915 String8 out_s8;
2916 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2917 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002918 }
Andy Hung920f6572022-10-06 12:09:49 -07002919 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08002920}
2921
Andy Hung4b17e882023-07-07 13:47:37 -07002922status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002923 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002924 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002925 return NO_INIT;
2926 }
2927 return mOutput->stream->selectPresentation(presentationId, programId);
2928}
2929
Andy Hung4b17e882023-07-07 13:47:37 -07002930void PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002931 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002932 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07002933 sp<AudioIoDescriptor> desc;
2934 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002935 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002936 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002937 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002938 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002939 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
2940 mSampleRate, mFormat, mChannelMask,
2941 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
2942 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08002943 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002944 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002945 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07002946 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002947 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002948 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002949 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08002950 break;
2951 }
Andy Hung7535ed92023-07-17 17:05:00 -07002952 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002953}
2954
Andy Hung4b17e882023-07-07 13:47:37 -07002955void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002956{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002957 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002958}
2959
Andy Hung4b17e882023-07-07 13:47:37 -07002960void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002961{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002962 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002963}
2964
Andy Hung4b17e882023-07-07 13:47:37 -07002965void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002966{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002967 mCallbackThread->setAsyncError();
2968}
2969
Andy Hung4b17e882023-07-07 13:47:37 -07002970void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08002971 const std::basic_string<uint8_t>& metadataBs)
2972{
Andy Hung4b17e882023-07-07 13:47:37 -07002973 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08002974 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hung4b17e882023-07-07 13:47:37 -07002975 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08002976 if (playbackThread == nullptr) {
2977 ALOGW("PlaybackThread was destroyed, skip codec format change event");
2978 return;
2979 }
2980
jiabinf6eb4c32020-02-25 14:06:25 -08002981 audio_utils::metadata::Data metadata =
2982 audio_utils::metadata::dataFromByteString(metadataBs);
2983 if (metadata.empty()) {
2984 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2985 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2986 (int)metadataBs.size());
2987 return;
2988 }
2989
2990 audio_utils::metadata::ByteString metaDataStr =
2991 audio_utils::metadata::byteStringFromData(metadata);
2992 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2993 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002994 for (const auto& callbackPair : mAudioTrackCallbacks) {
2995 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002996 }
2997 }).detach();
2998}
2999
Andy Hung4b17e882023-07-07 13:47:37 -07003000void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003001{
3002 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003003 // reject out of sequence requests
3004 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3005 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003006 mWaitWorkCV.signal();
3007 }
3008}
3009
Andy Hung4b17e882023-07-07 13:47:37 -07003010void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003011{
3012 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003013 // reject out of sequence requests
3014 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003015 // Register discontinuity when HW drain is completed because that can cause
3016 // the timestamp frame position to reset to 0 for direct and offload threads.
3017 // (Out of sequence requests are ignored, since the discontinuity would be handled
3018 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003019 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003020 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003021 mWaitWorkCV.signal();
3022 }
3023}
3024
Andy Hung4b17e882023-07-07 13:47:37 -07003025void PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003026{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003027 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003028 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3029 mSampleRate = audioConfig.sample_rate;
3030 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003031 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003032 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003033 }
Andy Hung4b17e882023-07-07 13:47:37 -07003034 if (hasMixer() && !AudioFlinger::isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003035 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3036 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003037 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003038
3039 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3040 mMixerChannelMask = mChannelMask;
3041 }
3042
Andy Hunge5412692014-05-16 11:25:07 -07003043 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003044 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003045
Eric Laurentf1f22e72021-07-13 14:04:14 +02003046 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3047
Phil Burkca5e6142015-07-14 09:42:29 -07003048 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003049 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003050 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003051 // Get format from the shim, which will be different than the HAL format
3052 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003053 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003054 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003055 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003056 }
Andy Hung4b17e882023-07-07 13:47:37 -07003057 if (hasMixer() && !AudioFlinger::isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003058 LOG_FATAL("HAL format %#x not supported for mixed output",
3059 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003060 }
Phil Burk062e67a2015-02-11 13:40:50 -08003061 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003062 result = mOutput->stream->getBufferSize(&mBufferSize);
3063 LOG_ALWAYS_FATAL_IF(result != OK,
3064 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003065 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003066 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003067 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003068 mFrameCount);
3069 }
3070
Eric Laurentd1f69b02014-12-15 14:33:13 -08003071 mHwSupportsPause = false;
3072 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003073 bool supportsPause = false, supportsResume = false;
3074 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3075 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003076 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003077 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003078 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003079 } else if (supportsResume) {
3080 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003081 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003082 }
3083 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003084 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3085 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3086 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003087
Andy Hungfbfc3952015-01-15 13:33:51 -08003088 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3089 // For best precision, we use float instead of the associated output
3090 // device format (typically PCM 16 bit).
3091
3092 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3093 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3094 mBufferSize = mFrameSize * mFrameCount;
3095
3096 // TODO: We currently use the associated output device channel mask and sample rate.
3097 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3098 // (if a valid mask) to avoid premature downmix.
3099 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3100 // instead of the output device sample rate to avoid loss of high frequency information.
3101 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3102 }
3103
Andy Hung09a50072014-02-27 14:30:47 -08003104 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003105 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003106 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003107 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3108 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003109 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3110 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003111
Eric Laurent81784c32012-11-19 14:55:58 -08003112 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3113 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3114 maxNormalFrameCount = maxNormalFrameCount & ~15;
3115 if (maxNormalFrameCount < minNormalFrameCount) {
3116 maxNormalFrameCount = minNormalFrameCount;
3117 }
3118 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3119 if (multiplier <= 1.0) {
3120 multiplier = 1.0;
3121 } else if (multiplier <= 2.0) {
3122 if (2 * mFrameCount <= maxNormalFrameCount) {
3123 multiplier = 2.0;
3124 } else {
3125 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3126 }
3127 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003128 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003129 }
3130 }
3131 mNormalFrameCount = multiplier * mFrameCount;
3132 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003133 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003134 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3135 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003136 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003137 mNormalFrameCount);
3138
Andy Hung08fb1742015-05-31 23:22:10 -07003139 // Check if we want to throttle the processing to no more than 2x normal rate
3140 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003141 mThreadThrottleTimeMs = 0;
3142 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003143 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3144
Andy Hung010a1a12014-03-13 13:57:33 -07003145 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3146 // Originally this was int16_t[] array, need to remove legacy implications.
3147 free(mSinkBuffer);
3148 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003149
Andy Hung5b10a202014-03-13 13:59:29 -07003150 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3151 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3152 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003153 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003154
Andy Hung69aed5f2014-02-25 17:24:40 -08003155 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3156 // drives the output.
3157 free(mMixerBuffer);
3158 mMixerBuffer = NULL;
3159 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003160 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003161 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003162 * audio_bytes_per_sample(mMixerBufferFormat);
3163 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3164 }
Andy Hung98ef9782014-03-04 14:46:50 -08003165 free(mEffectBuffer);
3166 mEffectBuffer = NULL;
3167 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003168 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003169 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003170 * audio_bytes_per_sample(mEffectBufferFormat);
3171 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3172 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003173
Eric Laurentb62d0362021-10-26 17:40:18 +02003174 if (mType == SPATIALIZER) {
3175 free(mPostSpatializerBuffer);
3176 mPostSpatializerBuffer = nullptr;
3177 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3178 * audio_bytes_per_sample(mEffectBufferFormat);
3179 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3180 }
3181
Mikhail Naganov55773032020-10-01 15:08:13 -07003182 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3183 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003184 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3185 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003186 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003187
Eric Laurent81784c32012-11-19 14:55:58 -08003188 // force reconfiguration of effect chains and engines to take new buffer size and audio
3189 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003190 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003191 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3192 // matter.
3193 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003194 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003195 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung7535ed92023-07-17 17:05:00 -07003196 mAfThreadCallback->moveEffectChain_l(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003197 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003198 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003199
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003200 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003201 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003202 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3203 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3204 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3205 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3206 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3207 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3208 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3209 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3210 (int32_t)mHapticChannelMask)
3211 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3212 (int32_t)mHapticChannelCount)
3213 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3214 formatToString(mHALFormat).c_str())
3215 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3216 (int32_t)mFrameCount) // sic - added HAL
3217 ;
3218 uint32_t latencyMs;
3219 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3220 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3221 }
3222 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003223}
3224
Andy Hung4b17e882023-07-07 13:47:37 -07003225ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003226{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003227 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003228 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003229 }
3230 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003231 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung11e74242023-06-26 19:20:57 -07003232 for (const sp<IAfTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -07003233 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003234 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003235 }
Kevin Rocard12381092018-04-11 09:19:59 -07003236 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003237 MetadataUpdate change;
3238 change.playbackMetadataUpdate = metadata.tracks;
3239 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003240}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003241
Andy Hung4b17e882023-07-07 13:47:37 -07003242void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003243 const StreamOutHalInterface::SourceMetadata& metadata)
3244{
3245 mOutput->stream->updateSourceMetadata(metadata);
3246};
3247
Andy Hung4b17e882023-07-07 13:47:37 -07003248status_t PlaybackThread::getRenderPosition(
Andy Hung3e4c8742023-06-29 21:19:25 -07003249 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003250{
3251 if (halFrames == NULL || dspFrames == NULL) {
3252 return BAD_VALUE;
3253 }
3254 Mutex::Autolock _l(mLock);
3255 if (initCheck() != NO_ERROR) {
3256 return INVALID_OPERATION;
3257 }
Andy Hung818e7a32016-02-16 18:08:07 -08003258 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003259 *halFrames = framesWritten;
3260
3261 if (isSuspended()) {
3262 // return an estimation of rendered frames when the output is suspended
3263 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003264 *dspFrames = (uint32_t)
3265 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003266 return NO_ERROR;
3267 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003268 status_t status;
3269 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003270 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003271 *dspFrames = (size_t)frames;
3272 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003273 }
3274}
3275
Andy Hung4b17e882023-07-07 13:47:37 -07003276product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003277{
3278 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3279 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3280 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003281 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003282 }
3283 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003284 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003285 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003286 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003287 }
3288 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003289 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003290}
3291
3292
Andy Hung4b17e882023-07-07 13:47:37 -07003293AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003294{
3295 Mutex::Autolock _l(mLock);
3296 return mOutput;
3297}
3298
Andy Hung4b17e882023-07-07 13:47:37 -07003299AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003300{
3301 Mutex::Autolock _l(mLock);
3302 AudioStreamOut *output = mOutput;
3303 mOutput = NULL;
3304 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3305 // must push a NULL and wait for ack
3306 mOutputSink.clear();
3307 mPipeSink.clear();
3308 mNormalSink.clear();
3309 return output;
3310}
3311
3312// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hung4b17e882023-07-07 13:47:37 -07003313sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003314{
3315 if (mOutput == NULL) {
3316 return NULL;
3317 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003318 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003319}
3320
Andy Hung4b17e882023-07-07 13:47:37 -07003321uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003322{
3323 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3324}
3325
Andy Hung4b17e882023-07-07 13:47:37 -07003326status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003327{
3328 if (!isValidSyncEvent(event)) {
3329 return BAD_VALUE;
3330 }
3331
3332 Mutex::Autolock _l(mLock);
3333
3334 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003335 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003336 if (event->triggerSession() == track->sessionId()) {
3337 (void) track->setSyncEvent(event);
3338 return NO_ERROR;
3339 }
3340 }
3341
3342 return NAME_NOT_FOUND;
3343}
3344
Andy Hung4b17e882023-07-07 13:47:37 -07003345bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003346{
3347 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3348}
3349
Andy Hung4b17e882023-07-07 13:47:37 -07003350void PlaybackThread::threadLoop_removeTracks(
Andy Hung11e74242023-06-26 19:20:57 -07003351 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003352{
Andy Hungfe726a62018-09-27 15:17:25 -07003353 // Miscellaneous track cleanup when removed from the active list,
3354 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003355#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003356 for (const auto& track : tracksToRemove) {
3357 if (track->isExternalTrack()) {
3358 // to track the speaker usage
3359 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003360 }
3361 }
Andy Hungfe726a62018-09-27 15:17:25 -07003362#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003363}
3364
Andy Hung4b17e882023-07-07 13:47:37 -07003365void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003366{
3367 if (!mMasterMute) {
3368 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003369 if (mOutDeviceTypeAddrs.empty()) {
3370 ALOGD("ro.audio.silent is ignored since no output device is set");
3371 return;
3372 }
jiabinc52b1ff2019-10-31 17:20:42 -07003373 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003374 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3375 return;
3376 }
Eric Laurent81784c32012-11-19 14:55:58 -08003377 if (property_get("ro.audio.silent", value, "0") > 0) {
3378 char *endptr;
3379 unsigned long ul = strtoul(value, &endptr, 0);
3380 if (*endptr == '\0' && ul != 0) {
3381 ALOGD("Silence is golden");
3382 // The setprop command will not allow a property to be changed after
3383 // the first time it is set, so we don't have to worry about un-muting.
3384 setMasterMute_l(true);
3385 }
3386 }
3387 }
3388}
3389
3390// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung4b17e882023-07-07 13:47:37 -07003391ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003392{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003393 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003394 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003395 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003396 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003397
3398 // If an NBAIO sink is present, use it to write the normal mixer's submix
3399 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003400
Andy Hung010a1a12014-03-13 13:57:33 -07003401 const size_t count = mBytesRemaining / mFrameSize;
3402
Simon Wilson2d590962012-11-29 15:18:50 -08003403 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003404 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1b6d46a2023-07-19 16:22:58 -07003405 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003406 if (screenState != mScreenState) {
3407 mScreenState = screenState;
3408 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3409 if (pipe != NULL) {
3410 pipe->setAvgFrames((mScreenState & 1) ?
3411 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3412 }
3413 }
Andy Hung010a1a12014-03-13 13:57:33 -07003414 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003415 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003416
Eric Laurent81784c32012-11-19 14:55:58 -08003417 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003418 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003419
Andy Hung8946a282018-04-19 20:04:56 -07003420#ifdef TEE_SINK
3421 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3422#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003423 } else {
3424 bytesWritten = framesWritten;
3425 }
3426 // otherwise use the HAL / AudioStreamOut directly
3427 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003428 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003429
Eric Laurentbfb1b832013-01-07 09:53:42 -08003430 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003431 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3432 mWriteAckSequence += 2;
3433 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003434 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003435 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003436 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003437 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003438 // FIXME We should have an implementation of timestamps for direct output threads.
3439 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003440 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003441 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003442
Eric Laurentbfb1b832013-01-07 09:53:42 -08003443 if (mUseAsyncWrite &&
3444 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3445 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003446 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003447 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003448 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003449 }
Eric Laurent81784c32012-11-19 14:55:58 -08003450 }
3451
Eric Laurent81784c32012-11-19 14:55:58 -08003452 mNumWrites++;
3453 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003454 if (mStandby) {
3455 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003456 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003457 mStandby = false;
3458 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003459 return bytesWritten;
3460}
3461
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003462// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07003463void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003464 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003465{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003466 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003467 if (outputSink != nullptr) {
3468 outputSink->startMelComputation(processor);
3469 }
Vlad Popab042ee62022-10-20 18:05:00 +02003470}
3471
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003472// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07003473void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003474{
3475 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003476 if (outputSink != nullptr) {
3477 outputSink->stopMelComputation();
3478 }
Vlad Popab042ee62022-10-20 18:05:00 +02003479}
3480
Andy Hung4b17e882023-07-07 13:47:37 -07003481void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003482{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003483 bool supportsDrain = false;
3484 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003485 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3486 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003487 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3488 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003489 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003490 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003491 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003492 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003493 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003494 }
3495}
3496
Andy Hung4b17e882023-07-07 13:47:37 -07003497void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003498{
Eric Laurent275e8e92014-11-30 15:14:47 -08003499 {
3500 Mutex::Autolock _l(mLock);
3501 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003502 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003503 track->invalidate();
3504 }
Andy Hungdae27702016-10-31 14:01:16 -07003505 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3506 // After we exit there are no more track changes sent to BatteryNotifier
3507 // because that requires an active threadLoop.
3508 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3509 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003510 }
Eric Laurent81784c32012-11-19 14:55:58 -08003511}
3512
3513/*
3514The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003515 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003516 - mActiveSleepTimeUs from activeSleepTimeUs()
3517 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003518 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3519 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003520 - maxPeriod from frame count and sample rate (MIXER only)
3521
3522The parameters that affect these derived values are:
3523 - frame count
3524 - frame size
3525 - sample rate
3526 - device type: A2DP or not
3527 - device latency
3528 - format: PCM or not
3529 - active sleep time
3530 - idle sleep time
3531*/
3532
Andy Hung4b17e882023-07-07 13:47:37 -07003533void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003534{
Andy Hung25c2dac2014-02-27 14:56:00 -08003535 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003536 mActiveSleepTimeUs = activeSleepTimeUs();
3537 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003538
Eric Laurent52568142022-10-28 11:23:28 +02003539 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
Carter Hsu0ca47c22023-06-02 18:01:45 +08003540
Eric Laurent42537be2016-01-08 17:16:42 -08003541 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3542 // truncating audio when going to standby.
jiabinc52b1ff2019-10-31 17:20:42 -07003543 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003544 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3545 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3546 }
3547 }
Eric Laurent81784c32012-11-19 14:55:58 -08003548}
3549
Andy Hung4b17e882023-07-07 13:47:37 -07003550bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003551{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003552 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003553 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003554 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003555 size_t size = mTracks.size();
3556 for (size_t i = 0; i < size; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003557 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003558 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003559 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003560 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003561 }
3562 }
Eric Laurent13084622016-05-17 10:51:49 -07003563 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003564}
3565
Andy Hung4b17e882023-07-07 13:47:37 -07003566void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003567{
3568 Mutex::Autolock _l(mLock);
3569 invalidateTracks_l(streamType);
3570}
3571
Andy Hung4b17e882023-07-07 13:47:37 -07003572void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003573 Mutex::Autolock _l(mLock);
3574 invalidateTracks_l(portIds);
3575}
3576
Andy Hung4b17e882023-07-07 13:47:37 -07003577bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003578 bool trackMatch = false;
3579 const size_t size = mTracks.size();
3580 for (size_t i = 0; i < size; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003581 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003582 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3583 t->invalidate();
3584 portIds.erase(t->portId());
3585 trackMatch = true;
3586 }
3587 if (portIds.empty()) {
3588 break;
3589 }
3590 }
3591 return trackMatch;
3592}
3593
jiabinf042b9b2021-05-07 23:46:28 +00003594// getTrackById_l must be called with holding thread lock
Andy Hung4b17e882023-07-07 13:47:37 -07003595IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003596 audio_port_handle_t trackPortId) {
3597 for (size_t i = 0; i < mTracks.size(); i++) {
3598 if (mTracks[i]->portId() == trackPortId) {
3599 return mTracks[i].get();
3600 }
3601 }
3602 return nullptr;
3603}
3604
Andy Hung4b17e882023-07-07 13:47:37 -07003605status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003606{
Glenn Kastend848eb42016-03-08 13:42:11 -08003607 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003608 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003609 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003610
Andy Hungd3639922022-04-28 18:00:49 -07003611 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003612 if (!audio_is_global_session(session)) {
3613 // player sessions on a spatializer output will use a dedicated input buffer and
3614 // will either output multi channel to mEffectBuffer if the track is spatilaized
3615 // or stereo to mPostSpatializerBuffer if not spatialized.
3616 uint32_t channelMask;
3617 bool isSessionSpatialized =
3618 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3619 if (isSessionSpatialized) {
3620 channelMask = mMixerChannelMask;
3621 } else {
3622 channelMask = mChannelMask;
3623 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003624 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003625 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung7535ed92023-07-17 17:05:00 -07003626 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003627 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003628 &halInBuffer);
3629 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003630
Andy Hung7535ed92023-07-17 17:05:00 -07003631 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003632 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3633 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3634 &halOutBuffer);
3635 if (result != OK) return result;
3636
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003637 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003638
Mikhail Naganov022b9952017-01-04 16:36:51 -08003639 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3640 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003641 } else {
3642 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3643 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3644 // mPostSpatializerBuffer as output buffer
3645 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung7535ed92023-07-17 17:05:00 -07003646 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003647 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3648 if (result != OK) return result;
Andy Hung7535ed92023-07-17 17:05:00 -07003649 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003650 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3651 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003652
Eric Laurentb62d0362021-10-26 17:40:18 +02003653 if (session == AUDIO_SESSION_DEVICE) {
3654 halInBuffer = halOutBuffer;
3655 }
3656 }
3657 } else {
Andy Hung7535ed92023-07-17 17:05:00 -07003658 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003659 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3660 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3661 &halInBuffer);
3662 if (result != OK) return result;
3663 halOutBuffer = halInBuffer;
3664 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3665 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003666 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003667 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003668 // Only one effect chain can be present in direct output thread and it uses
3669 // the sink buffer as input
3670 if (mType != DIRECT) {
3671 size_t numSamples = mNormalFrameCount
3672 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3673 + mHapticChannelCount);
Andy Hung7535ed92023-07-17 17:05:00 -07003674 const status_t allocateStatus =
3675 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003676 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003677 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003678 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003679
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003680 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003681 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3682 buffer, session);
3683 }
3684 }
3685 }
3686
3687 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003688 // Attach all tracks with same session ID to this chain.
3689 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003690 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003691 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003692 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3693 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003694 track->setMainBuffer(buffer);
3695 chain->incTrackCnt();
3696 }
3697 }
3698
3699 // indicate all active tracks in the chain
Andy Hung11e74242023-06-26 19:20:57 -07003700 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003701 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003702 ALOGV("addEffectChain_l() activating track %p on session %d",
3703 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003704 chain->incActiveTrackCnt();
3705 }
3706 }
3707 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003708
Eric Laurentaaa44472014-09-12 17:41:50 -07003709 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003710 chain->setInBuffer(halInBuffer);
3711 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003712 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3713 // chains list in order to be processed last as it contains output device effects.
3714 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3715 // processing effects specific to an output stream before effects applied to all streams
3716 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003717 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3718 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003719 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003720 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003721 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003722 // Effect chain for other sessions are inserted at beginning of effect
3723 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003724 // sessions is not important.
3725 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003726 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3727 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003728 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003729 size_t size = mEffectChains.size();
3730 size_t i = 0;
3731 for (i = 0; i < size; i++) {
3732 if (mEffectChains[i]->sessionId() < session) {
3733 break;
3734 }
3735 }
3736 mEffectChains.insertAt(chain, i);
3737 checkSuspendOnAddEffectChain_l(chain);
3738
3739 return NO_ERROR;
3740}
3741
Andy Hung4b17e882023-07-07 13:47:37 -07003742size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003743{
Glenn Kastend848eb42016-03-08 13:42:11 -08003744 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003745
3746 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3747
3748 for (size_t i = 0; i < mEffectChains.size(); i++) {
3749 if (chain == mEffectChains[i]) {
3750 mEffectChains.removeAt(i);
3751 // detach all active tracks from the chain
Andy Hung11e74242023-06-26 19:20:57 -07003752 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003753 if (session == track->sessionId()) {
3754 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3755 chain.get(), session);
3756 chain->decActiveTrackCnt();
3757 }
3758 }
3759
3760 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003761 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung11e74242023-06-26 19:20:57 -07003762 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003763 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003764 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003765 chain->decTrackCnt();
3766 }
3767 }
3768 break;
3769 }
3770 }
3771 return mEffectChains.size();
3772}
3773
Andy Hung4b17e882023-07-07 13:47:37 -07003774status_t PlaybackThread::attachAuxEffect(
Andy Hung11e74242023-06-26 19:20:57 -07003775 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003776{
3777 Mutex::Autolock _l(mLock);
3778 return attachAuxEffect_l(track, EffectId);
3779}
3780
Andy Hung4b17e882023-07-07 13:47:37 -07003781status_t PlaybackThread::attachAuxEffect_l(
Andy Hung11e74242023-06-26 19:20:57 -07003782 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003783{
3784 status_t status = NO_ERROR;
3785
3786 if (EffectId == 0) {
3787 track->setAuxBuffer(0, NULL);
3788 } else {
3789 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003790 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003791 if (effect != 0) {
3792 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3793 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3794 } else {
3795 status = INVALID_OPERATION;
3796 }
3797 } else {
3798 status = BAD_VALUE;
3799 }
3800 }
3801 return status;
3802}
3803
Andy Hung4b17e882023-07-07 13:47:37 -07003804void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003805{
3806 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003807 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003808 if (track->auxEffectId() == effectId) {
3809 attachAuxEffect_l(track, 0);
3810 }
3811 }
3812}
3813
Andy Hung4b17e882023-07-07 13:47:37 -07003814bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003815NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003816{
Andy Hung78d8d952023-05-30 18:10:23 -07003817 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003818
Andy Hung11e74242023-06-26 19:20:57 -07003819 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003820
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003821 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003822 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003823
3824 // MIXER
3825 nsecs_t lastWarning = 0;
3826
3827 // DUPLICATING
3828 // FIXME could this be made local to while loop?
3829 writeFrames = 0;
3830
3831 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003832 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003833
Andy Hungd3639922022-04-28 18:00:49 -07003834 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003835 sleepTimeShift = 0;
3836 }
3837
3838 CpuStats cpuStats;
3839 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3840
3841 acquireWakeLock();
3842
Glenn Kasteneef598c2017-04-03 14:41:13 -07003843 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3844 // thread associated with this PlaybackThread.
3845 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3846 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003847 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3848 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003849 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003850 const char *logString = NULL;
3851
rago1bb90822017-05-02 18:31:48 -07003852 // Estimated time for next buffer to be written to hal. This is used only on
3853 // suspended mode (for now) to help schedule the wait time until next iteration.
3854 nsecs_t timeLoopNextNs = 0;
3855
Eric Laurent664539d2013-09-23 18:24:31 -07003856 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003857
Andy Hung2dbffc22018-08-08 18:50:41 -07003858 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003859
Eric Laurentb3f315a2021-07-13 15:09:05 +02003860 sendCheckOutputStageEffectsEvent();
3861
Andy Hung446f4df2019-02-21 12:26:41 -08003862 // loopCount is used for statistics and diagnostics.
3863 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003864 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003865 // Log merge requests are performed during AudioFlinger binder transactions, but
3866 // that does not cover audio playback. It's requested here for that reason.
Andy Hung7535ed92023-07-17 17:05:00 -07003867 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003868
Eric Laurent81784c32012-11-19 14:55:58 -08003869 cpuStats.sample(myName);
3870
Andy Hung116bc262023-06-20 18:56:17 -07003871 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003872 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003873 bool isHapticSessionSpatialized = false;
Andy Hung11e74242023-06-26 19:20:57 -07003874 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003875
Andy Hung2dbffc22018-08-08 18:50:41 -07003876 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3877 //
jiabinc52b1ff2019-10-31 17:20:42 -07003878 // Note: we access outDeviceTypes() outside of mLock.
3879 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003880 // Here, we try for the AF lock, but do not block on it as the latency
3881 // is more informational.
Andy Hung7535ed92023-07-17 17:05:00 -07003882 if (mAfThreadCallback->mutex().tryLock() == NO_ERROR) {
Andy Hungd25fe392023-07-13 16:52:46 -07003883 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07003884 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07003885 status_t status = INVALID_OPERATION;
3886 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung7535ed92023-07-17 17:05:00 -07003887 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungd25fe392023-07-13 16:52:46 -07003888 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07003889 && swPatches.size() > 0) {
3890 status = swPatches[0].getLatencyMs_l(&latencyMs);
3891 downstreamPatchHandle = swPatches[0].getPatchHandle();
3892 }
3893 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003894 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003895 lastDownstreamPatchHandle = downstreamPatchHandle;
3896 }
3897 if (status == OK) {
3898 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003899 // latency of 5 seconds).
3900 const double minLatency = 0., maxLatency = 5000.;
3901 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003902 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003903 } else {
3904 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07003905 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07003906 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003907 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003908 }
Andy Hung7535ed92023-07-17 17:05:00 -07003909 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07003910 }
3911 } else {
3912 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3913 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003914 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003915 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3916 }
3917 }
3918
Eric Laurentb3f315a2021-07-13 15:09:05 +02003919 if (mCheckOutputStageEffects.exchange(false)) {
3920 checkOutputStageEffects();
3921 }
3922
Vlad Popa7e81cea2023-01-19 16:34:16 +01003923 MetadataUpdate metadataUpdate;
Eric Laurent81784c32012-11-19 14:55:58 -08003924 { // scope for mLock
3925
3926 Mutex::Autolock _l(mLock);
3927
Eric Laurent021cf962014-05-13 10:18:14 -07003928 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003929 if (mCheckOutputStageEffects.load()) {
3930 continue;
3931 }
Eric Laurent10351942014-05-08 18:49:52 -07003932
Glenn Kasteneef598c2017-04-03 14:41:13 -07003933 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003934 if (logString != NULL) {
3935 mNBLogWriter->logTimestamp();
3936 mNBLogWriter->log(logString);
3937 logString = NULL;
3938 }
3939
Dean Wheatley12473e92021-03-18 23:00:55 +11003940 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003941
Eric Laurent81784c32012-11-19 14:55:58 -08003942 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003943 if (mSignalPending) {
3944 // A signal was raised while we were unlocked
3945 mSignalPending = false;
3946 } else if (waitingAsyncCallback_l()) {
3947 if (exitPending()) {
3948 break;
3949 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003950 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003951 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003952 releaseWakeLock_l();
3953 released = true;
3954 }
Andy Hung10cbff12017-02-21 17:30:14 -08003955
3956 const int64_t waitNs = computeWaitTimeNs_l();
3957 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3958 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3959 if (status == TIMED_OUT) {
3960 mSignalPending = true; // if timeout recheck everything
3961 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003962 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003963 if (released) {
3964 acquireWakeLock_l();
3965 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003966 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3967 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003968
3969 continue;
3970 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003971 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003972 isSuspended()) {
3973 // put audio hardware into standby after short delay
3974 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003975
3976 threadLoop_standby();
3977
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003978 // This is where we go into standby
3979 if (!mStandby) {
3980 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003981 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003982 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02003983 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003984 }
Andy Hungd0979812019-02-21 15:51:44 -08003985 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003986 }
3987
Eric Tan39ec8d62018-07-24 09:49:29 -07003988 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003989 // we're about to wait, flush the binder command buffer
3990 IPCThreadState::self()->flushCommands();
3991
3992 clearOutputTracks();
3993
3994 if (exitPending()) {
3995 break;
3996 }
3997
3998 releaseWakeLock_l();
3999 // wait until we have something to do...
4000 ALOGV("%s going to sleep", myName.string());
4001 mWaitWorkCV.wait(mLock);
4002 ALOGV("%s waking up", myName.string());
4003 acquireWakeLock_l();
4004
4005 mMixerStatus = MIXER_IDLE;
4006 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4007 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004008 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004009 checkSilentMode_l();
4010
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004011 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4012 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004013 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004014 sleepTimeShift = 0;
4015 }
4016
4017 continue;
4018 }
4019 }
Eric Laurent81784c32012-11-19 14:55:58 -08004020 // mMixerStatusIgnoringFastTracks is also updated internally
4021 mMixerStatus = prepareTracks_l(&tracksToRemove);
4022
Andy Hungdae27702016-10-31 14:01:16 -07004023 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004024
Vlad Popa7e81cea2023-01-19 16:34:16 +01004025 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004026
Eric Laurent81784c32012-11-19 14:55:58 -08004027 // prevent any changes in effect chain list and in each effect chain
4028 // during mixing and effect process as the audio buffers could be deleted
4029 // or modified if an effect is created or deleted
4030 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004031
4032 // Determine which session to pick up haptic data.
4033 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004034 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004035 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004036 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004037 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004038 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004039 if (effectChain != nullptr
4040 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004041 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004042 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004043 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004044 break;
4045 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004046 if (activeHapticSessionId == AUDIO_SESSION_NONE
4047 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004048 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004049 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004050 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004051 }
4052 }
4053 }
4054
Andy Hungc1646382019-04-30 16:12:10 -07004055 // Acquire a local copy of active tracks with lock (release w/o lock).
4056 //
4057 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4058 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4059 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4060 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent68a40a82022-05-03 18:15:04 +02004061
4062 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004063
Jiabin Huangfb476842022-12-06 03:18:10 +00004064 for (const auto &track : mActiveTracks ) {
jiabin7434e812023-06-27 18:22:35 +00004065 track->updateTeePatches_l();
Jiabin Huangfb476842022-12-06 03:18:10 +00004066 }
4067
Eric Laurent19952e12023-04-20 10:08:29 +02004068 // signal actual start of output stream when the render position reported by the kernel
4069 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004070 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4071 && (mKernelPositionOnStandby
4072 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004073 mHalStarted = true;
4074 mWaitHalStartCV.broadcast();
4075 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004076 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004077
Eric Laurentbfb1b832013-01-07 09:53:42 -08004078 if (mBytesRemaining == 0) {
4079 mCurrentWriteLength = 0;
4080 if (mMixerStatus == MIXER_TRACKS_READY) {
4081 // threadLoop_mix() sets mCurrentWriteLength
4082 threadLoop_mix();
4083 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4084 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004085 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004086 // must be written to HAL
4087 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004088 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004089 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004090
4091 // Tally underrun frames as we are inserting 0s here.
4092 for (const auto& track : activeTracks) {
Andy Hung11e74242023-06-26 19:20:57 -07004093 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004094 && !track->isStopped()
4095 && !track->isPaused()
4096 && !track->isTerminated()) {
4097 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4098 __func__, track->id(), track->getTrackStateAsString(),
4099 mNormalFrameCount);
Andy Hung11e74242023-06-26 19:20:57 -07004100 track->audioTrackServerProxy()->tallyUnderrunFrames(
4101 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004102 }
4103 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004104 }
4105 }
Andy Hung98ef9782014-03-04 14:46:50 -08004106 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004107 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004108 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004109 // or mSinkBuffer (if there are no effects and there is no data already copied to
4110 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004111 //
4112 // This is done pre-effects computation; if effects change to
4113 // support higher precision, this needs to move.
4114 //
4115 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004116 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004117 uint32_t mixerChannelCount = mEffectBufferValid ?
4118 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004119 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004120 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4121 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4122
David Li88ee0902022-06-22 10:01:21 +08004123 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4124 // do these processes after effects are applied.
4125 if (!mEffectBufferValid) {
4126 // mono blend occurs for mixer threads only (not direct or offloaded)
4127 // and is handled here if we're going directly to the sink.
4128 if (requireMonoBlend()) {
4129 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4130 mNormalFrameCount, true /*limit*/);
4131 }
Andy Hung2ddee192015-12-18 17:34:44 -08004132
David Li88ee0902022-06-22 10:01:21 +08004133 if (!hasFastMixer()) {
4134 // Balance must take effect after mono conversion.
4135 // We do it here if there is no FastMixer.
4136 // mBalance detects zero balance within the class for speed
4137 // (not needed here).
4138 mBalance.setBalance(mMasterBalance.load());
4139 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4140 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004141 }
4142
Andy Hung98ef9782014-03-04 14:46:50 -08004143 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004144 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004145
4146 // If we're going directly to the sink and there are haptic channels,
4147 // we should adjust channels as the sample data is partially interleaved
4148 // in this case.
4149 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4150 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4151 mChannelCount + mHapticChannelCount,
4152 audio_bytes_per_sample(format),
4153 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4154 }
Andy Hung98ef9782014-03-04 14:46:50 -08004155 }
4156
Eric Laurentbfb1b832013-01-07 09:53:42 -08004157 mBytesRemaining = mCurrentWriteLength;
4158 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004159 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4160 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4161 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4162 mBytesWritten += mBytesRemaining;
4163 mFramesWritten += framesRemaining;
4164 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004165 mBytesRemaining = 0;
4166 }
Eric Laurent81784c32012-11-19 14:55:58 -08004167
Eric Laurentbfb1b832013-01-07 09:53:42 -08004168 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004169 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004170 for (size_t i = 0; i < effectChains.size(); i ++) {
4171 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004172 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004173 if (activeHapticSessionId != AUDIO_SESSION_NONE
4174 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004175 // Haptic data is active in this case, copy it directly from
4176 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004177 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4178 audio_channel_count_from_out_mask(mMixerChannelMask) :
4179 mChannelCount;
4180 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4181 hapticSessionChannelCount = mChannelCount;
4182 }
4183
jiabin47affe52019-04-04 18:02:07 -07004184 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004185 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004186 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004187 memcpy_by_audio_format(
4188 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004189 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004190 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004191 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004192 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004193 }
Eric Laurent81784c32012-11-19 14:55:58 -08004194 }
4195 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004196 // Process effect chains for offloaded thread even if no audio
4197 // was read from audio track: process only updates effect state
4198 // and thus does have to be synchronized with audio writes but may have
4199 // to be called while waiting for async write callback
4200 if (mType == OFFLOAD) {
4201 for (size_t i = 0; i < effectChains.size(); i ++) {
4202 effectChains[i]->process_l();
4203 }
4204 }
Eric Laurent81784c32012-11-19 14:55:58 -08004205
Andy Hung98ef9782014-03-04 14:46:50 -08004206 // Only if the Effects buffer is enabled and there is data in the
4207 // Effects buffer (buffer valid), we need to
4208 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004209 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004210 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004211 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004212 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004213 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004214 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004215 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004216 }
4217
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004218 if (!hasFastMixer()) {
4219 // Balance must take effect after mono conversion.
4220 // We do it here if there is no FastMixer.
4221 // mBalance detects zero balance within the class for speed (not needed here).
4222 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004223 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004224 }
4225
Eric Laurentb62d0362021-10-26 17:40:18 +02004226 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4227 // mPostSpatializerBuffer if the haptics track is spatialized.
4228 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4229 // For other thread types, the haptics channels are already in mEffectBuffer.
4230 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4231 const size_t srcBufferSize = mNormalFrameCount *
4232 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4233 mEffectBufferFormat);
4234 const size_t dstBufferSize = mNormalFrameCount
4235 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4236
4237 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4238 mEffectBufferFormat,
4239 (uint8_t*)mEffectBuffer + srcBufferSize,
4240 mEffectBufferFormat,
4241 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004242 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004243 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4244 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4245 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4246 // Clamp PCM float values more than this distance from 0 to insulate
4247 // a HAL which doesn't handle NaN correctly.
4248 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4249 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4250 static_cast<const float*>(effectBuffer),
4251 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4252 } else {
4253 memcpy_by_audio_format(mSinkBuffer, mFormat,
4254 effectBuffer, mEffectBufferFormat, framesToCopy);
4255 }
jiabin245cdd92018-12-07 17:55:15 -08004256 // The sample data is partially interleaved when haptic channels exist,
4257 // we need to adjust channels here.
4258 if (mHapticChannelCount > 0) {
4259 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4260 mChannelCount + mHapticChannelCount,
4261 audio_bytes_per_sample(mFormat),
4262 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4263 }
Andy Hung98ef9782014-03-04 14:46:50 -08004264 }
4265
Eric Laurent81784c32012-11-19 14:55:58 -08004266 // enable changes in effect chain
4267 unlockEffectChains(effectChains);
4268
Vlad Popafce10862023-02-03 10:37:07 +01004269 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung7535ed92023-07-17 17:05:00 -07004270 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004271 metadataUpdate.playbackMetadataUpdate);
4272 }
4273
Eric Laurentbfb1b832013-01-07 09:53:42 -08004274 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004275 // mSleepTimeUs == 0 means we must write to audio hardware
4276 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004277 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004278 // writePeriodNs is updated >= 0 when ret > 0.
4279 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004280 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004281 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004282 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004283 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004284 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004285 if (ret < 0) {
4286 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004287 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004288 mBytesWritten += ret;
4289 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004290 const int64_t frames = ret / mFrameSize;
4291 mFramesWritten += frames;
4292
4293 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4294 // process information relating to write time.
4295 if (audio_has_proportional_frames(mFormat)) {
4296 // we are in a continuous mixing cycle
4297 if (mMixerStatus == MIXER_TRACKS_READY &&
4298 loopCount == lastLoopCountWritten + 1) {
4299
4300 const double jitterMs =
4301 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4302 {frames, writePeriodNs},
4303 {0, 0} /* lastTimestamp */, mSampleRate);
4304 const double processMs =
4305 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4306
4307 Mutex::Autolock _l(mLock);
4308 mIoJitterMs.add(jitterMs);
4309 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004310
4311 if (mPipeSink.get() != nullptr) {
4312 // Using the Monopipe availableToWrite, we estimate the current
4313 // buffer size.
4314 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4315 const ssize_t
4316 availableToWrite = mPipeSink->availableToWrite();
4317 const size_t pipeFrames = monoPipe->maxFrames();
4318 const size_t
4319 remainingFrames = pipeFrames - max(availableToWrite, 0);
4320 mMonopipePipeDepthStats.add(remainingFrames);
4321 }
Andy Hung446f4df2019-02-21 12:26:41 -08004322 }
4323
4324 // write blocked detection
4325 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004326 if ((mType == MIXER || mType == SPATIALIZER)
4327 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004328 mNumDelayedWrites++;
4329 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4330 ATRACE_NAME("underrun");
4331 ALOGW("write blocked for %lld msecs, "
4332 "%d delayed writes, thread %d",
4333 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4334 mNumDelayedWrites, mId);
4335 lastWarning = lastIoEndNs;
4336 }
4337 }
4338 }
4339 // update timing info.
4340 mLastIoBeginNs = lastIoBeginNs;
4341 mLastIoEndNs = lastIoEndNs;
4342 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004343 }
4344 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4345 (mMixerStatus == MIXER_DRAIN_ALL)) {
4346 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004347 }
Andy Hungd3639922022-04-28 18:00:49 -07004348 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004349
4350 if (mThreadThrottle
4351 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004352 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004353 // Limit MixerThread data processing to no more than twice the
4354 // expected processing rate.
4355 //
4356 // This helps prevent underruns with NuPlayer and other applications
4357 // which may set up buffers that are close to the minimum size, or use
4358 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4359 //
4360 // The throttle smooths out sudden large data drains from the device,
4361 // e.g. when it comes out of standby, which often causes problems with
4362 // (1) mixer threads without a fast mixer (which has its own warm-up)
4363 // (2) minimum buffer sized tracks (even if the track is full,
4364 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004365 //
4366 // Total time spent in last processing cycle equals time spent in
4367 // 1. threadLoop_write, as well as time spent in
4368 // 2. threadLoop_mix (significant for heavy mixing, especially
4369 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004370
Andy Hung446f4df2019-02-21 12:26:41 -08004371 // it's OK if deltaMs is an overestimate.
4372
4373 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004374
Ivan Lozanoea04d392017-11-07 14:37:07 -08004375 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004376 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004377 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004378
Andy Hung08fb1742015-05-31 23:22:10 -07004379 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004380 // notify of throttle start on verbose log
4381 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4382 "mixer(%p) throttle begin:"
4383 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004384 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004385 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004386 // Throttle must be attributed to the previous mixer loop's write time
4387 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004388 // This also ensures proper timing statistics.
4389 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004390 } else {
4391 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4392 if (diff > 0) {
4393 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004394 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004395 ALOGD_IF(!isSingleDeviceType(
4396 outDeviceTypes(), audio_is_a2dp_out_device) &&
4397 !isSingleDeviceType(
4398 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004399 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004400 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4401 }
Andy Hung08fb1742015-05-31 23:22:10 -07004402 }
4403 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004404 }
Eric Laurent81784c32012-11-19 14:55:58 -08004405
Eric Laurentbfb1b832013-01-07 09:53:42 -08004406 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004407 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004408 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004409 // suspended requires accurate metering of sleep time.
4410 if (isSuspended()) {
4411 // advance by expected sleepTime
4412 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4413 const nsecs_t nowNs = systemTime();
4414
4415 // compute expected next time vs current time.
4416 // (negative deltas are treated as delays).
4417 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4418 if (deltaNs < -kMaxNextBufferDelayNs) {
4419 // Delays longer than the max allowed trigger a reset.
4420 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4421 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4422 timeLoopNextNs = nowNs + deltaNs;
4423 } else if (deltaNs < 0) {
4424 // Delays within the max delay allowed: zero the delta/sleepTime
4425 // to help the system catch up in the next iteration(s)
4426 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4427 deltaNs = 0;
4428 }
4429 // update sleep time (which is >= 0)
4430 mSleepTimeUs = deltaNs / 1000;
4431 }
Eric Laurente93cc032016-05-05 10:15:10 -07004432 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4433 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004434 }
Glenn Kastene7754022014-10-31 12:11:26 -07004435 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004436 }
Eric Laurent81784c32012-11-19 14:55:58 -08004437 }
4438
4439 // Finally let go of removed track(s), without the lock held
4440 // since we can't guarantee the destructors won't acquire that
4441 // same lock. This will also mutate and push a new fast mixer state.
4442 threadLoop_removeTracks(tracksToRemove);
4443 tracksToRemove.clear();
4444
4445 // FIXME I don't understand the need for this here;
4446 // it was in the original code but maybe the
4447 // assignment in saveOutputTracks() makes this unnecessary?
4448 clearOutputTracks();
4449
4450 // Effect chains will be actually deleted here if they were removed from
4451 // mEffectChains list during mixing or effects processing
4452 effectChains.clear();
4453
4454 // FIXME Note that the above .clear() is no longer necessary since effectChains
4455 // is now local to this block, but will keep it for now (at least until merge done).
4456 }
4457
Eric Laurentbfb1b832013-01-07 09:53:42 -08004458 threadLoop_exit();
4459
Eric Laurentcf817a22014-08-04 20:36:31 -07004460 if (!mStandby) {
4461 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004462 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004463 }
4464
4465 releaseWakeLock();
4466
4467 ALOGV("Thread %p type %d exiting", this, mType);
4468 return false;
4469}
4470
Andy Hung4b17e882023-07-07 13:47:37 -07004471void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004472{
Dean Wheatley12473e92021-03-18 23:00:55 +11004473 if (mStandby) {
4474 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4475 return;
4476 } else if (mHwPaused) {
4477 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4478 return;
4479 }
4480
4481 // Gather the framesReleased counters for all active tracks,
4482 // and associate with the sink frames written out. We need
4483 // this to convert the sink timestamp to the track timestamp.
4484 bool kernelLocationUpdate = false;
4485 ExtendedTimestamp timestamp; // use private copy to fetch
4486
4487 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4488 // HAL may be draining some small duration buffered data for fade out.
4489 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4490 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4491 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4492 mSampleRate);
4493
4494 if (isTimestampCorrectionEnabled()) {
4495 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4496 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4497 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4498 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4499 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4500 = correctedTimestamp.mFrames;
4501 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4502 = correctedTimestamp.mTimeNs;
4503 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4504 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4505 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4506
4507 // Note: Downstream latency only added if timestamp correction enabled.
4508 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4509 const int64_t newPosition =
4510 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4511 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4512 // prevent retrograde
4513 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4514 newPosition,
4515 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4516 - mSuspendedFrames));
4517 }
4518 }
4519
4520 // We always fetch the timestamp here because often the downstream
4521 // sink will block while writing.
4522
4523 // We keep track of the last valid kernel position in case we are in underrun
4524 // and the normal mixer period is the same as the fast mixer period, or there
4525 // is some error from the HAL.
4526 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4527 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4528 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4529 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4530 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4531
4532 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4533 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4534 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4535 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4536 }
4537
4538 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4539 kernelLocationUpdate = true;
4540 } else {
4541 ALOGVV("getTimestamp error - no valid kernel position");
4542 }
4543
4544 // copy over kernel info
4545 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4546 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4547 + mSuspendedFrames; // add frames discarded when suspended
4548 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4549 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4550 } else {
4551 mTimestampVerifier.error();
4552 }
4553
4554 // mFramesWritten for non-offloaded tracks are contiguous
4555 // even after standby() is called. This is useful for the track frame
4556 // to sink frame mapping.
4557 bool serverLocationUpdate = false;
4558 if (mFramesWritten != mLastFramesWritten) {
4559 serverLocationUpdate = true;
4560 mLastFramesWritten = mFramesWritten;
4561 }
4562 // Only update timestamps if there is a meaningful change.
4563 // Either the kernel timestamp must be valid or we have written something.
4564 if (kernelLocationUpdate || serverLocationUpdate) {
4565 if (serverLocationUpdate) {
4566 // use the time before we called the HAL write - it is a bit more accurate
4567 // to when the server last read data than the current time here.
4568 //
4569 // If we haven't written anything, mLastIoBeginNs will be -1
4570 // and we use systemTime().
4571 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4572 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4573 ? systemTime() : mLastIoBeginNs;
4574 }
4575
Andy Hung11e74242023-06-26 19:20:57 -07004576 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004577 if (!t->isFastTrack()) {
4578 t->updateTrackFrameInfo(
Andy Hung11e74242023-06-26 19:20:57 -07004579 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004580 mFramesWritten,
4581 mSampleRate,
4582 mTimestamp);
4583 }
4584 }
4585 }
4586
4587 if (audio_has_proportional_frames(mFormat)) {
4588 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4589 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4590 mLatencyMs.add(latencyMs);
4591 }
4592 }
4593#if 0
4594 // logFormat example
4595 if (z % 100 == 0) {
4596 timespec ts;
4597 clock_gettime(CLOCK_MONOTONIC, &ts);
4598 LOGT("This is an integer %d, this is a float %f, this is my "
4599 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4600 LOGT("A deceptive null-terminated string %\0");
4601 }
4602 ++z;
4603#endif
4604}
4605
Eric Laurentbfb1b832013-01-07 09:53:42 -08004606// removeTracks_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07004607void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hung920f6572022-10-06 12:09:49 -07004608NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurentbfb1b832013-01-07 09:53:42 -08004609{
Andy Hungfe726a62018-09-27 15:17:25 -07004610 for (const auto& track : tracksToRemove) {
4611 mActiveTracks.remove(track);
4612 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004613 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004614 if (chain != 0) {
4615 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4616 __func__, track->id(), chain.get(), track->sessionId());
4617 chain->decActiveTrackCnt();
4618 }
4619 // If an external client track, inform APM we're no longer active, and remove if needed.
4620 // We do this under lock so that the state is consistent if the Track is destroyed.
4621 if (track->isExternalTrack()) {
4622 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004623 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004624 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004625 }
4626 }
Andy Hungfe726a62018-09-27 15:17:25 -07004627 if (track->isTerminated()) {
4628 // remove from our tracks vector
4629 removeTrack_l(track);
4630 }
jiabineb3bda02020-06-30 14:07:03 -07004631 if (mHapticChannelCount > 0 &&
4632 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4633 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004634 mLock.unlock();
4635 // Unlock due to VibratorService will lock for this call and will
4636 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung76cb9152023-07-20 21:23:42 -07004637 afutils::onExternalVibrationStop(track->getExternalVibration());
jiabin57303cc2018-12-18 15:45:57 -08004638 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004639
4640 // When the track is stop, set the haptic intensity as MUTE
4641 // for the HapticGenerator effect.
4642 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004643 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004644 }
jiabin245cdd92018-12-07 17:55:15 -08004645 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004646 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004647}
Eric Laurent81784c32012-11-19 14:55:58 -08004648
Andy Hung4b17e882023-07-07 13:47:37 -07004649status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004650{
4651 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004652 ExtendedTimestamp ets;
4653 status_t status = mNormalSink->getTimestamp(ets);
4654 if (status == NO_ERROR) {
4655 status = ets.getBestTimestamp(&timestamp);
4656 }
4657 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004658 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004659 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004660 collectTimestamps_l();
4661 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4662 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004663 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004664 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4665 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4666 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4667 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4668 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004669 }
4670 return INVALID_OPERATION;
4671}
Eric Laurent1c333e22014-05-20 10:48:17 -07004672
Eric Laurenteab90452019-06-24 15:17:46 -07004673// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4674// still applied by the mixer.
4675// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4676// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4677// if more than one track are active
Andy Hung4b17e882023-07-07 13:47:37 -07004678status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004679{
4680 status_t result = NO_ERROR;
4681 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4682 if (*volume != mLeftVolFloat) {
4683 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004684 // HAL can return INVALID_OPERATION if operation is not supported.
4685 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004686 "Error when setting output stream volume: %d", result);
4687 if (result == NO_ERROR) {
4688 mLeftVolFloat = *volume;
4689 }
4690 }
4691 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4692 // remove stream volume contribution from software volume.
4693 if (mLeftVolFloat == *volume) {
4694 *volume = 1.0f;
4695 }
4696 }
4697 return result;
4698}
4699
Andy Hung4b17e882023-07-07 13:47:37 -07004700status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004701 audio_patch_handle_t *handle)
4702{
Andy Hungf60abce2016-08-26 11:37:54 -07004703 status_t status;
4704 if (property_get_bool("af.patch_park", false /* default_value */)) {
4705 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4706 // or if HAL does not properly lock against access.
4707 AutoPark<FastMixer> park(mFastMixer);
4708 status = PlaybackThread::createAudioPatch_l(patch, handle);
4709 } else {
4710 status = PlaybackThread::createAudioPatch_l(patch, handle);
4711 }
Eric Laurentb0463942022-12-20 16:31:10 +01004712
4713 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004714 return status;
4715}
4716
Andy Hung4b17e882023-07-07 13:47:37 -07004717status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004718 audio_patch_handle_t *handle)
4719{
4720 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004721
4722 // store new device and send to effects
4723 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004724 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004725 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004726 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4727 && !mOutput->audioHwDev->supportsAudioPatches(),
4728 "Enumerated device type(%#x) must not be used "
4729 "as it does not support audio patches",
4730 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004731 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004732 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4733 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004734 }
4735
François Gaffie0c280aa2018-07-25 10:02:15 +02004736 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004737#ifdef ADD_BATTERY_DATA
4738 // when changing the audio output device, call addBatteryData to notify
4739 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004740 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004741 uint32_t params = 0;
4742 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004743 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004744 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004745 }
4746
Eric Laurent054d9d32015-04-24 08:48:48 -07004747 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004748 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004749 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4750 }
4751
4752 if (params != 0) {
4753 addBatteryData(params);
4754 }
4755 }
4756#endif
4757
4758 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004759 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004760 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004761
jiabinc52b1ff2019-10-31 17:20:42 -07004762 // mPatch.num_sinks is not set when the thread is created so that
4763 // the first patch creation triggers an ioConfigChanged callback
4764 bool configChanged = (mPatch.num_sinks == 0) ||
4765 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004766 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004767 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004768 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004769
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004770 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004771 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4772 status = hwDevice->createAudioPatch(patch->num_sources,
4773 patch->sources,
4774 patch->num_sinks,
4775 patch->sinks,
4776 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004777 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004778 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004779 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004780 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004781 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004782
4783 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004784 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004785 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004786 // also dispatch to active AudioTracks for MediaMetrics
4787 for (const auto &track : mActiveTracks) {
4788 track->logEndInterval();
4789 track->logBeginInterval(patchSinksAsString);
4790 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004791
Eric Laurente8726fe2015-06-26 09:39:24 -07004792 if (configChanged) {
4793 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4794 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004795 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004796 mActiveTracks.setHasChanged();
4797
Eric Laurent1c333e22014-05-20 10:48:17 -07004798 return status;
4799}
4800
Andy Hung4b17e882023-07-07 13:47:37 -07004801status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004802{
Andy Hungf60abce2016-08-26 11:37:54 -07004803 status_t status;
4804 if (property_get_bool("af.patch_park", false /* default_value */)) {
4805 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4806 // or if HAL does not properly lock against access.
4807 AutoPark<FastMixer> park(mFastMixer);
4808 status = PlaybackThread::releaseAudioPatch_l(handle);
4809 } else {
4810 status = PlaybackThread::releaseAudioPatch_l(handle);
4811 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004812 return status;
4813}
4814
Andy Hung4b17e882023-07-07 13:47:37 -07004815status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004816{
4817 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004818
jiabinc52b1ff2019-10-31 17:20:42 -07004819 mPatch = audio_patch{};
4820 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004821
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004822 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004823 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4824 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004825 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004826 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004827 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004828 // Force meteadata update after a route change
4829 mActiveTracks.setHasChanged();
4830
Eric Laurent1c333e22014-05-20 10:48:17 -07004831 return status;
4832}
4833
Andy Hung4b17e882023-07-07 13:47:37 -07004834void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004835{
4836 Mutex::Autolock _l(mLock);
4837 mTracks.add(track);
4838}
4839
Andy Hung4b17e882023-07-07 13:47:37 -07004840void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004841{
4842 Mutex::Autolock _l(mLock);
4843 destroyTrack_l(track);
4844}
4845
Andy Hung4b17e882023-07-07 13:47:37 -07004846void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07004847{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004848 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004849 config->role = AUDIO_PORT_ROLE_SOURCE;
4850 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4851 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004852 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4853 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4854 config->flags.output = mOutput->flags;
4855 }
Eric Laurent83b88082014-06-20 18:31:16 -07004856}
4857
Eric Laurent81784c32012-11-19 14:55:58 -08004858// ----------------------------------------------------------------------------
4859
Andy Hung4b17e882023-07-07 13:47:37 -07004860/* static */
4861sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung7535ed92023-07-17 17:05:00 -07004862 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hung4b17e882023-07-07 13:47:37 -07004863 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung7535ed92023-07-17 17:05:00 -07004864 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hung4b17e882023-07-07 13:47:37 -07004865}
4866
Andy Hung7535ed92023-07-17 17:05:00 -07004867MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004868 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07004869 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004870 // mAudioMixer below
4871 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01004872 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004873 mFastMixerFutex(0),
4874 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004875 // mOutputSink below
4876 // mPipeSink below
4877 // mNormalSink below
4878{
Andy Hung7535ed92023-07-17 17:05:00 -07004879 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004880 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004881 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004882 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004883 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4884 mNormalFrameCount);
4885 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4886
Andy Hungfbfc3952015-01-15 13:33:51 -08004887 if (type == DUPLICATING) {
4888 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4889 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4890 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4891 return;
4892 }
Eric Laurent81784c32012-11-19 14:55:58 -08004893 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004894 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004895 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004896 const NBAIO_Format offers[1] = {Format_from_SR_C(
4897 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004898#if !LOG_NDEBUG
4899 ssize_t index =
4900#else
4901 (void)
4902#endif
4903 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004904 ALOG_ASSERT(index == 0);
4905
4906 // initialize fast mixer depending on configuration
4907 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00004908 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08004909 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004910 } else {
4911 switch (kUseFastMixer) {
4912 case FastMixer_Never:
4913 initFastMixer = false;
4914 break;
4915 case FastMixer_Always:
4916 initFastMixer = true;
4917 break;
4918 case FastMixer_Static:
4919 case FastMixer_Dynamic:
4920 initFastMixer = mFrameCount < mNormalFrameCount;
4921 break;
4922 }
4923 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4924 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4925 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004926 }
4927 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004928 audio_format_t fastMixerFormat;
4929 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4930 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4931 } else {
4932 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4933 }
4934 if (mFormat != fastMixerFormat) {
4935 // change our Sink format to accept our intermediate precision
4936 mFormat = fastMixerFormat;
4937 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004938 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004939 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4940 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4941 }
Eric Laurent81784c32012-11-19 14:55:58 -08004942
4943 // create a MonoPipe to connect our submix to FastMixer
4944 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004945
Andy Hung1258c1a2014-05-23 21:22:17 -07004946 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004947 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004948 format.mFormat = fastMixerFormat;
4949 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4950
Eric Laurent81784c32012-11-19 14:55:58 -08004951 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4952 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4953 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4954 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07004955 const NBAIO_Format offersFast[1] = {format};
4956 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004957#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02004958 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004959#else
4960 (void)
4961#endif
Andy Hung920f6572022-10-06 12:09:49 -07004962 monoPipe->negotiate(offersFast, std::size(offersFast),
4963 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08004964 ALOG_ASSERT(index == 0);
4965 monoPipe->setAvgFrames((mScreenState & 1) ?
4966 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4967 mPipeSink = monoPipe;
4968
Eric Laurent81784c32012-11-19 14:55:58 -08004969 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004970 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004971 FastMixerStateQueue *sq = mFastMixer->sq();
4972#ifdef STATE_QUEUE_DUMP
4973 sq->setObserverDump(&mStateQueueObserverDump);
4974 sq->setMutatorDump(&mStateQueueMutatorDump);
4975#endif
4976 FastMixerState *state = sq->begin();
4977 FastTrack *fastTrack = &state->mFastTracks[0];
4978 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4979 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4980 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004981 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4982 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4983 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004984 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004985 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004986 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01004987 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08004988 fastTrack->mGeneration++;
4989 state->mFastTracksGen++;
4990 state->mTrackMask = 1;
4991 // fast mixer will use the HAL output sink
4992 state->mOutputSink = mOutputSink.get();
4993 state->mOutputSinkGen++;
4994 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004995 // specify sink channel mask when haptic channel mask present as it can not
4996 // be calculated directly from channel count
4997 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004998 ? AUDIO_CHANNEL_NONE
4999 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005000 state->mCommand = FastMixerState::COLD_IDLE;
5001 // already done in constructor initialization list
5002 //mFastMixerFutex = 0;
5003 state->mColdFutexAddr = &mFastMixerFutex;
5004 state->mColdGen++;
5005 state->mDumpState = &mFastMixerDumpState;
Andy Hung7535ed92023-07-17 17:05:00 -07005006 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005007 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005008 sq->end();
5009 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5010
Eric Tan0513b5d2018-09-17 10:32:48 -07005011 NBLog::thread_info_t info;
5012 info.id = mId;
5013 info.type = NBLog::FASTMIXER;
5014 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5015
Eric Laurent81784c32012-11-19 14:55:58 -08005016 // start the fast mixer
5017 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5018 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005019 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005020 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005021
5022#ifdef AUDIO_WATCHDOG
5023 // create and start the watchdog
5024 mAudioWatchdog = new AudioWatchdog();
5025 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5026 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5027 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005028 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005029#endif
Andy Hung8946a282018-04-19 20:04:56 -07005030 } else {
5031#ifdef TEE_SINK
5032 // Only use the MixerThread tee if there is no FastMixer.
5033 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5034 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5035#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005036 }
5037
5038 switch (kUseFastMixer) {
5039 case FastMixer_Never:
5040 case FastMixer_Dynamic:
5041 mNormalSink = mOutputSink;
5042 break;
5043 case FastMixer_Always:
5044 mNormalSink = mPipeSink;
5045 break;
5046 case FastMixer_Static:
5047 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5048 break;
5049 }
5050}
5051
Andy Hung4b17e882023-07-07 13:47:37 -07005052MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005053{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005054 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005055 FastMixerStateQueue *sq = mFastMixer->sq();
5056 FastMixerState *state = sq->begin();
5057 if (state->mCommand == FastMixerState::COLD_IDLE) {
5058 int32_t old = android_atomic_inc(&mFastMixerFutex);
5059 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005060 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005061 }
5062 }
5063 state->mCommand = FastMixerState::EXIT;
5064 sq->end();
5065 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5066 mFastMixer->join();
5067 // Though the fast mixer thread has exited, it's state queue is still valid.
5068 // We'll use that extract the final state which contains one remaining fast track
5069 // corresponding to our sub-mix.
5070 state = sq->begin();
5071 ALOG_ASSERT(state->mTrackMask == 1);
5072 FastTrack *fastTrack = &state->mFastTracks[0];
5073 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5074 delete fastTrack->mBufferProvider;
5075 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005076 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005077#ifdef AUDIO_WATCHDOG
5078 if (mAudioWatchdog != 0) {
5079 mAudioWatchdog->requestExit();
5080 mAudioWatchdog->requestExitAndWait();
5081 mAudioWatchdog.clear();
5082 }
5083#endif
5084 }
Andy Hung7535ed92023-07-17 17:05:00 -07005085 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005086 delete mAudioMixer;
5087}
5088
Andy Hung4b17e882023-07-07 13:47:37 -07005089void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005090 PlaybackThread::onFirstRef();
5091
5092 Mutex::Autolock _l(mLock);
5093 if (mOutput != nullptr && mOutput->stream != nullptr) {
5094 status_t status = mOutput->stream->setLatencyModeCallback(this);
5095 if (status != INVALID_OPERATION) {
5096 updateHalSupportedLatencyModes_l();
5097 }
5098 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5099 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5100 mBluetoothLatencyModesEnabled.store(
5101 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5102 }
5103}
Eric Laurent81784c32012-11-19 14:55:58 -08005104
Andy Hung4b17e882023-07-07 13:47:37 -07005105uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005106{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005107 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005108 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5109 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5110 }
5111 return latency;
5112}
5113
Andy Hung4b17e882023-07-07 13:47:37 -07005114ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005115{
5116 // FIXME we should only do one push per cycle; confirm this is true
5117 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005118 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005119 FastMixerStateQueue *sq = mFastMixer->sq();
5120 FastMixerState *state = sq->begin();
5121 if (state->mCommand != FastMixerState::MIX_WRITE &&
5122 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5123 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005124
5125 // FIXME workaround for first HAL write being CPU bound on some devices
5126 ATRACE_BEGIN("write");
5127 mOutput->write((char *)mSinkBuffer, 0);
5128 ATRACE_END();
5129
Eric Laurent81784c32012-11-19 14:55:58 -08005130 int32_t old = android_atomic_inc(&mFastMixerFutex);
5131 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005132 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005133 }
5134#ifdef AUDIO_WATCHDOG
5135 if (mAudioWatchdog != 0) {
5136 mAudioWatchdog->resume();
5137 }
5138#endif
5139 }
5140 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005141#ifdef FAST_THREAD_STATISTICS
Andy Hung7535ed92023-07-17 17:05:00 -07005142 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005143 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005144#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005145 sq->end();
5146 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5147 if (kUseFastMixer == FastMixer_Dynamic) {
5148 mNormalSink = mPipeSink;
5149 }
5150 } else {
5151 sq->end(false /*didModify*/);
5152 }
5153 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005154 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005155}
5156
Andy Hung4b17e882023-07-07 13:47:37 -07005157void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005158{
5159 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005160 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005161 FastMixerStateQueue *sq = mFastMixer->sq();
5162 FastMixerState *state = sq->begin();
5163 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005164 // Report any frames trapped in the Monopipe
5165 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5166 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5167 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5168 "monoPipeWritten:%lld monoPipeLeft:%lld",
5169 (long long)mFramesWritten, (long long)mSuspendedFrames,
5170 (long long)mPipeSink->framesWritten(), pipeFrames);
5171 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5172
Eric Laurent81784c32012-11-19 14:55:58 -08005173 state->mCommand = FastMixerState::COLD_IDLE;
5174 state->mColdFutexAddr = &mFastMixerFutex;
5175 state->mColdGen++;
5176 mFastMixerFutex = 0;
5177 sq->end();
5178 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5179 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5180 if (kUseFastMixer == FastMixer_Dynamic) {
5181 mNormalSink = mOutputSink;
5182 }
5183#ifdef AUDIO_WATCHDOG
5184 if (mAudioWatchdog != 0) {
5185 mAudioWatchdog->pause();
5186 }
5187#endif
5188 } else {
5189 sq->end(false /*didModify*/);
5190 }
5191 }
5192 PlaybackThread::threadLoop_standby();
5193}
5194
Andy Hung4b17e882023-07-07 13:47:37 -07005195bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005196{
5197 return false;
5198}
5199
Andy Hung4b17e882023-07-07 13:47:37 -07005200bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005201{
5202 return !mStandby;
5203}
5204
Andy Hung4b17e882023-07-07 13:47:37 -07005205bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005206{
5207 Mutex::Autolock _l(mLock);
5208 return waitingAsyncCallback_l();
5209}
5210
Eric Laurent81784c32012-11-19 14:55:58 -08005211// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung4b17e882023-07-07 13:47:37 -07005212void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005213{
5214 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005215 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005216 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005217 // discard any pending drain or write ack by incrementing sequence
5218 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5219 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005220 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005221 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5222 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005223 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005224 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005225 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005226}
5227
Andy Hung4b17e882023-07-07 13:47:37 -07005228void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005229{
5230 ALOGV("signal playback thread");
5231 broadcast_l();
5232}
5233
Andy Hung4b17e882023-07-07 13:47:37 -07005234void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005235{
5236 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5237 invalidateTracks((audio_stream_type_t)i);
5238 }
5239}
5240
Andy Hung4b17e882023-07-07 13:47:37 -07005241void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005242{
Eric Laurent81784c32012-11-19 14:55:58 -08005243 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005244 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005245 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005246 // increase sleep time progressively when application underrun condition clears.
5247 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5248 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5249 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005250 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005251 sleepTimeShift--;
5252 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005253 mSleepTimeUs = 0;
5254 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005255 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005256
Eric Laurent81784c32012-11-19 14:55:58 -08005257}
5258
Andy Hung4b17e882023-07-07 13:47:37 -07005259void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005260{
5261 // If no tracks are ready, sleep once for the duration of an output
5262 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005263 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005264 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005265 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5266 // Using the Monopipe availableToWrite, we estimate the
5267 // sleep time to retry for more data (before we underrun).
5268 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5269 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5270 const size_t pipeFrames = monoPipe->maxFrames();
5271 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5272 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5273 const size_t framesDelay = std::min(
5274 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5275 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5276 pipeFrames, framesLeft, framesDelay);
5277 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5278 } else {
5279 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5280 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5281 mSleepTimeUs = kMinThreadSleepTimeUs;
5282 }
5283 // reduce sleep time in case of consecutive application underruns to avoid
5284 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5285 // duration we would end up writing less data than needed by the audio HAL if
5286 // the condition persists.
5287 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5288 sleepTimeShift++;
5289 }
Eric Laurent81784c32012-11-19 14:55:58 -08005290 }
5291 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005292 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005293 }
5294 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005295 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5296 // before effects processing or output.
5297 if (mMixerBufferValid) {
5298 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005299 if (mType == SPATIALIZER) {
5300 memset(mSinkBuffer, 0, mSinkBufferSize);
5301 }
Andy Hung98ef9782014-03-04 14:46:50 -08005302 } else {
5303 memset(mSinkBuffer, 0, mSinkBufferSize);
5304 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005305 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005306 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5307 "anticipated start");
5308 }
5309 // TODO add standby time extension fct of effect tail
5310}
5311
5312// prepareTracks_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07005313PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07005314 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005315{
Andy Hungc0691382018-09-12 18:01:57 -07005316 // clean up deleted track ids in AudioMixer before allocating new tracks
5317 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5318 // for each trackId, destroy it in the AudioMixer
5319 if (mAudioMixer->exists(trackId)) {
5320 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005321 }
5322 });
Andy Hungc0691382018-09-12 18:01:57 -07005323 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005324
5325 mixer_state mixerStatus = MIXER_IDLE;
5326 // find out which tracks need to be processed
5327 size_t count = mActiveTracks.size();
5328 size_t mixedTracks = 0;
5329 size_t tracksWithEffect = 0;
5330 // counts only _active_ fast tracks
5331 size_t fastTracks = 0;
5332 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5333
5334 float masterVolume = mMasterVolume;
5335 bool masterMute = mMasterMute;
5336
5337 if (masterMute) {
5338 masterVolume = 0;
5339 }
5340 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005341 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005342 if (chain != 0) {
5343 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5344 chain->setVolume_l(&v, &v);
5345 masterVolume = (float)((v + (1 << 23)) >> 24);
5346 chain.clear();
5347 }
5348
5349 // prepare a new state to push
5350 FastMixerStateQueue *sq = NULL;
5351 FastMixerState *state = NULL;
5352 bool didModify = false;
5353 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005354 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005355 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005356 sq = mFastMixer->sq();
5357 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005358 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005359 }
5360
Andy Hung69aed5f2014-02-25 17:24:40 -08005361 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005362 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005363
Andy Hungbd3b2b02018-05-21 10:53:11 -07005364 // DeferredOperations handles statistics after setting mixerStatus.
5365 class DeferredOperations {
5366 public:
Andy Hungea840382020-05-05 21:50:17 -07005367 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5368 : mMixerStatus(mixerStatus)
5369 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005370
5371 // when leaving scope, tally frames properly.
5372 ~DeferredOperations() {
5373 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5374 // because that is when the underrun occurs.
5375 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005376 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005377 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005378 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005379 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005380 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005381 }
5382 }
Andy Hungea840382020-05-05 21:50:17 -07005383 // send the max underrun frames for this mixer period
5384 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005385 }
5386
5387 // tallyUnderrunFrames() is called to update the track counters
5388 // with the number of underrun frames for a particular mixer period.
5389 // We defer tallying until we know the final mixer status.
Andy Hung11e74242023-06-26 19:20:57 -07005390 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005391 mUnderrunFrames.emplace_back(track, underrunFrames);
5392 }
5393
5394 private:
5395 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005396 ThreadMetrics * const mThreadMetrics;
Andy Hung11e74242023-06-26 19:20:57 -07005397 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005398 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005399 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005400
jiabin245cdd92018-12-07 17:55:15 -08005401 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005402 for (size_t i=0 ; i<count ; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07005403 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005404
5405 // this const just means the local variable doesn't change
Andy Hung11e74242023-06-26 19:20:57 -07005406 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005407
5408 // process fast tracks
5409 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005410 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5411 "%s(%d): FastTrack(%d) present without FastMixer",
5412 __func__, id(), track->id());
5413
jiabin245cdd92018-12-07 17:55:15 -08005414 if (track->getHapticPlaybackEnabled()) {
5415 noFastHapticTrack = false;
5416 }
Eric Laurent81784c32012-11-19 14:55:58 -08005417
5418 // It's theoretically possible (though unlikely) for a fast track to be created
5419 // and then removed within the same normal mix cycle. This is not a problem, as
5420 // the track never becomes active so it's fast mixer slot is never touched.
5421 // The converse, of removing an (active) track and then creating a new track
5422 // at the identical fast mixer slot within the same normal mix cycle,
5423 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung11e74242023-06-26 19:20:57 -07005424 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005425 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005426 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5427 FastTrack *fastTrack = &state->mFastTracks[j];
5428
5429 // Determine whether the track is currently in underrun condition,
5430 // and whether it had a recent underrun.
5431 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5432 FastTrackUnderruns underruns = ftDump->mUnderruns;
5433 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung11e74242023-06-26 19:20:57 -07005434 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005435 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung11e74242023-06-26 19:20:57 -07005436 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005437 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung11e74242023-06-26 19:20:57 -07005438 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005439 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung11e74242023-06-26 19:20:57 -07005440 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005441 // don't count underruns that occur while stopping or pausing
5442 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005443 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005444 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5445 recentUnderruns > 0) {
5446 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005447 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005448 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005449 // Immediately account for FastTrack underruns.
Andy Hung11e74242023-06-26 19:20:57 -07005450 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005451
5452 // This is similar to the state machine for normal tracks,
5453 // with a few modifications for fast tracks.
5454 bool isActive = true;
Andy Hung11e74242023-06-26 19:20:57 -07005455 switch (track->state()) {
5456 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005457 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005458 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung11e74242023-06-26 19:20:57 -07005459 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005460 }
5461 break;
Andy Hung11e74242023-06-26 19:20:57 -07005462 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005463 // ramp down is not yet implemented
5464 track->setPaused();
5465 break;
Andy Hung11e74242023-06-26 19:20:57 -07005466 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005467 // ramp up is not yet implemented
Andy Hung11e74242023-06-26 19:20:57 -07005468 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005469 break;
Andy Hung11e74242023-06-26 19:20:57 -07005470 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005471 if (recentFull > 0 || recentPartial > 0) {
5472 // track has provided at least some frames recently: reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07005473 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005474 }
5475 if (recentUnderruns == 0) {
5476 // no recent underruns: stay active
5477 break;
5478 }
5479 // there has recently been an underrun of some kind
5480 if (track->sharedBuffer() == 0) {
5481 // were any of the recent underruns "empty" (no frames available)?
5482 if (recentEmpty == 0) {
5483 // no, then ignore the partial underruns as they are allowed indefinitely
5484 break;
5485 }
5486 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung11e74242023-06-26 19:20:57 -07005487 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005488 break;
5489 }
5490 // indicate to client process that the track was disabled because of underrun;
5491 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005492 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005493 // remove from active list, but state remains ACTIVE [confusing but true]
5494 isActive = false;
5495 break;
5496 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005497 FALLTHROUGH_INTENDED;
Andy Hung11e74242023-06-26 19:20:57 -07005498 case IAfTrackBase::STOPPING_2:
5499 case IAfTrackBase::PAUSED:
5500 case IAfTrackBase::STOPPED:
5501 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005502 // Check for presentation complete if track is inactive
5503 // We have consumed all the buffers of this track.
5504 // This would be incomplete if we auto-paused on underrun
5505 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005506 uint32_t latency = 0;
5507 status_t result = mOutput->stream->getLatency(&latency);
5508 ALOGE_IF(result != OK,
5509 "Error when retrieving output stream latency: %d", result);
5510 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005511 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005512 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5513 // track stays in active list until presentation is complete
5514 break;
5515 }
5516 }
5517 if (track->isStopping_2()) {
Andy Hung11e74242023-06-26 19:20:57 -07005518 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005519 }
5520 if (track->isStopped()) {
5521 // Can't reset directly, as fast mixer is still polling this track
5522 // track->reset();
5523 // So instead mark this track as needing to be reset after push with ack
5524 resetMask |= 1 << i;
5525 }
5526 isActive = false;
5527 break;
Andy Hung11e74242023-06-26 19:20:57 -07005528 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005529 default:
Andy Hung11e74242023-06-26 19:20:57 -07005530 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005531 }
5532
5533 if (isActive) {
5534 // was it previously inactive?
5535 if (!(state->mTrackMask & (1 << j))) {
Andy Hung11e74242023-06-26 19:20:57 -07005536 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5537 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005538 fastTrack->mBufferProvider = eabp;
5539 fastTrack->mVolumeProvider = vp;
Andy Hung11e74242023-06-26 19:20:57 -07005540 fastTrack->mChannelMask = track->channelMask();
5541 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005542 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005543 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005544 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005545 fastTrack->mGeneration++;
5546 state->mTrackMask |= 1 << j;
5547 didModify = true;
5548 // no acknowledgement required for newly active tracks
5549 }
Andy Hung11e74242023-06-26 19:20:57 -07005550 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005551 float volume;
5552 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5553 volume = 0.f;
5554 } else {
5555 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5556 }
5557
5558 handleVoipVolume_l(&volume);
5559
Eric Laurent81784c32012-11-19 14:55:58 -08005560 // cache the combined master volume and stream type volume for fast mixer; this
5561 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005562 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005563 proxy->framesReleased()).first;
5564 volume *= vh;
Andy Hung11e74242023-06-26 19:20:57 -07005565 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005566 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005567 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5568 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5569
Andy Hung7535ed92023-07-17 17:05:00 -07005570 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005571 /*muteState=*/{masterVolume == 0.f,
5572 mStreamTypes[track->streamType()].volume == 0.f,
5573 mStreamTypes[track->streamType()].mute,
5574 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005575 vlf == 0.f && vrf == 0.f,
5576 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005577
5578 vlf *= volume;
5579 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005580
jiabin76d94692022-12-15 21:51:21 +00005581 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005582 ++fastTracks;
5583 } else {
5584 // was it previously active?
5585 if (state->mTrackMask & (1 << j)) {
5586 fastTrack->mBufferProvider = NULL;
5587 fastTrack->mGeneration++;
5588 state->mTrackMask &= ~(1 << j);
5589 didModify = true;
5590 // If any fast tracks were removed, we must wait for acknowledgement
5591 // because we're about to decrement the last sp<> on those tracks.
5592 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5593 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005594 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5595 // AudioTrack may start (which may not be with a start() but with a write()
5596 // after underrun) and immediately paused or released. In that case the
5597 // FastTrack state hasn't had time to update.
5598 // TODO Remove the ALOGW when this theory is confirmed.
5599 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005600 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung11e74242023-06-26 19:20:57 -07005601 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005602 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005603 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005604 }
5605 tracksToRemove->add(track);
5606 // Avoids a misleading display in dumpsys
Andy Hung11e74242023-06-26 19:20:57 -07005607 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005608 }
jiabin245cdd92018-12-07 17:55:15 -08005609 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5610 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5611 didModify = true;
5612 }
Eric Laurent81784c32012-11-19 14:55:58 -08005613 continue;
5614 }
5615
5616 { // local variable scope to avoid goto warning
5617
5618 audio_track_cblk_t* cblk = track->cblk();
5619
5620 // The first time a track is added we wait
5621 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005622 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005623
5624 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005625 // use the trackId as the AudioMixer name.
5626 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005627 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005628 trackId,
Andy Hung11e74242023-06-26 19:20:57 -07005629 track->channelMask(),
5630 track->format(),
5631 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005632 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005633 ALOGW("%s(): AudioMixer cannot create track(%d)"
5634 " mask %#x, format %#x, sessionId %d",
5635 __func__, trackId,
Andy Hung11e74242023-06-26 19:20:57 -07005636 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005637 tracksToRemove->add(track);
5638 track->invalidate(); // consider it dead.
5639 continue;
5640 }
5641 }
5642
Eric Laurent81784c32012-11-19 14:55:58 -08005643 // make sure that we have enough frames to mix one full buffer.
5644 // enforce this condition only once to enable draining the buffer in case the client
5645 // app does not call stop() and relies on underrun to stop:
5646 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5647 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005648 size_t desiredFrames;
Andy Hung11e74242023-06-26 19:20:57 -07005649 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5650 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005651
5652 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005653 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005654 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5655 // add frames already consumed but not yet released by the resampler
5656 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005657 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005658
Eric Laurent81784c32012-11-19 14:55:58 -08005659 uint32_t minFrames = 1;
5660 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5661 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005662 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005663 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005664
5665 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005666 if (ATRACE_ENABLED()) {
5667 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005668 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005669 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005670 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005671 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005672 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005673 !track->isPaused() && !track->isTerminated())
5674 {
Andy Hungc0691382018-09-12 18:01:57 -07005675 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005676
5677 mixedTracks++;
5678
Andy Hung69aed5f2014-02-25 17:24:40 -08005679 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5680 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005681 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005682 if (track->mainBuffer() != mSinkBuffer &&
5683 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005684 if (mEffectBufferEnabled) {
5685 mEffectBufferValid = true; // Later can set directly.
5686 }
Eric Laurent81784c32012-11-19 14:55:58 -08005687 chain = getEffectChain_l(track->sessionId());
5688 // Delegate volume control to effect in track effect chain if needed
5689 if (chain != 0) {
5690 tracksWithEffect++;
5691 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005692 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005693 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005694 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005695 }
5696 }
5697
5698
5699 int param = AudioMixer::VOLUME;
Andy Hung11e74242023-06-26 19:20:57 -07005700 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005701 // no ramp for the first volume setting
Andy Hung11e74242023-06-26 19:20:57 -07005702 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5703 if (track->state() == IAfTrackBase::RESUMING) {
5704 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005705 // If a new track is paused immediately after start, do not ramp on resume.
5706 if (cblk->mServer != 0) {
5707 param = AudioMixer::RAMP_VOLUME;
5708 }
Eric Laurent81784c32012-11-19 14:55:58 -08005709 }
Andy Hungc0691382018-09-12 18:01:57 -07005710 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005711 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005712 // FIXME should not make a decision based on mServer
5713 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005714 // If the track is stopped before the first frame was mixed,
5715 // do not apply ramp
5716 param = AudioMixer::RAMP_VOLUME;
5717 }
5718
5719 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005720 uint32_t vl, vr; // in U8.24 integer format
5721 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005722 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005723 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005724 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung11e74242023-06-26 19:20:57 -07005725 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005726 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung11e74242023-06-26 19:20:57 -07005727 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005728
Eric Laurenteab90452019-06-24 15:17:46 -07005729 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5730 v = 0;
5731 }
5732
5733 handleVoipVolume_l(&v);
5734
5735 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005736 vl = vr = 0;
5737 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005738 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005739 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005740 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005741 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5742 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005743 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005744 if (vlf > GAIN_FLOAT_UNITY) {
5745 ALOGV("Track left volume out of range: %.3g", vlf);
5746 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005747 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005748 if (vrf > GAIN_FLOAT_UNITY) {
5749 ALOGV("Track right volume out of range: %.3g", vrf);
5750 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005751 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005752
Andy Hung7535ed92023-07-17 17:05:00 -07005753 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005754 /*muteState=*/{masterVolume == 0.f,
5755 mStreamTypes[track->streamType()].volume == 0.f,
5756 mStreamTypes[track->streamType()].mute,
5757 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005758 vlf == 0.f && vrf == 0.f,
5759 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005760
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005761 // now apply the master volume and stream type volume and shaper volume
5762 vlf *= v * vh;
5763 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005764 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005765 // then derive vl and vr as U8.24 versions for the effect chain
5766 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5767 vl = (uint32_t) (scaleto8_24 * vlf);
5768 vr = (uint32_t) (scaleto8_24 * vrf);
5769 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005770 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005771 // send level comes from shared memory and so may be corrupt
5772 if (sendLevel > MAX_GAIN_INT) {
5773 ALOGV("Track send level out of range: %04X", sendLevel);
5774 sendLevel = MAX_GAIN_INT;
5775 }
Andy Hung6be49402014-05-30 10:42:03 -07005776 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5777 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005778 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005779
jiabin76d94692022-12-15 21:51:21 +00005780 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005781
Eric Laurent81784c32012-11-19 14:55:58 -08005782 // Delegate volume control to effect in track effect chain if needed
5783 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5784 // Do not ramp volume if volume is controlled by effect
5785 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005786 // Update remaining floating point volume levels
5787 vlf = (float)vl / (1 << 24);
5788 vrf = (float)vr / (1 << 24);
Andy Hung11e74242023-06-26 19:20:57 -07005789 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005790 } else {
5791 // force no volume ramp when volume controller was just disabled or removed
5792 // from effect chain to avoid volume spike
Andy Hung11e74242023-06-26 19:20:57 -07005793 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005794 param = AudioMixer::VOLUME;
5795 }
Andy Hung11e74242023-06-26 19:20:57 -07005796 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005797 }
5798
Eric Laurent81784c32012-11-19 14:55:58 -08005799 // XXX: these things DON'T need to be done each time
Andy Hung11e74242023-06-26 19:20:57 -07005800 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005801 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005802
Andy Hungc0691382018-09-12 18:01:57 -07005803 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5804 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5805 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005806 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005807 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005808 AudioMixer::TRACK,
5809 AudioMixer::FORMAT, (void *)track->format());
5810 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005811 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005812 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005813 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005814
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005815 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005816 mAudioMixer->setParameter(
5817 trackId,
5818 AudioMixer::TRACK,
5819 AudioMixer::MIXER_CHANNEL_MASK,
5820 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5821 } else {
5822 mAudioMixer->setParameter(
5823 trackId,
5824 AudioMixer::TRACK,
5825 AudioMixer::MIXER_CHANNEL_MASK,
5826 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5827 }
5828
Glenn Kastene3aa6592012-12-04 12:22:46 -08005829 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005830 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005831 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005832 if (reqSampleRate == 0) {
5833 reqSampleRate = mSampleRate;
5834 } else if (reqSampleRate > maxSampleRate) {
5835 reqSampleRate = maxSampleRate;
5836 }
Eric Laurent81784c32012-11-19 14:55:58 -08005837 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005838 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005839 AudioMixer::RESAMPLE,
5840 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005841 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005842
Andy Hung8edb8dc2015-03-26 19:13:55 -07005843 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005844 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005845 AudioMixer::TIMESTRETCH,
5846 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07005847 // cast away constness for this generic API.
5848 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005849
Andy Hung69aed5f2014-02-25 17:24:40 -08005850 /*
5851 * Select the appropriate output buffer for the track.
5852 *
Andy Hung98ef9782014-03-04 14:46:50 -08005853 * Tracks with effects go into their own effects chain buffer
5854 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005855 *
5856 * Other tracks can use mMixerBuffer for higher precision
5857 * channel accumulation. If this buffer is enabled
5858 * (mMixerBufferEnabled true), then selected tracks will accumulate
5859 * into it.
5860 *
5861 */
5862 if (mMixerBufferEnabled
5863 && (track->mainBuffer() == mSinkBuffer
5864 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005865 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005866 mAudioMixer->setParameter(
5867 trackId,
5868 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005869 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005870 mAudioMixer->setParameter(
5871 trackId,
5872 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005873 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005874 } else {
5875 mAudioMixer->setParameter(
5876 trackId,
5877 AudioMixer::TRACK,
5878 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5879 mAudioMixer->setParameter(
5880 trackId,
5881 AudioMixer::TRACK,
5882 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5883 // TODO: override track->mainBuffer()?
5884 mMixerBufferValid = true;
5885 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005886 } else {
5887 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005888 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005889 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07005890 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005891 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005892 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005893 AudioMixer::TRACK,
5894 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5895 }
Eric Laurent81784c32012-11-19 14:55:58 -08005896 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005897 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005898 AudioMixer::TRACK,
5899 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005900 mAudioMixer->setParameter(
5901 trackId,
5902 AudioMixer::TRACK,
5903 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005904 mAudioMixer->setParameter(
5905 trackId,
5906 AudioMixer::TRACK,
5907 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung11e74242023-06-26 19:20:57 -07005908 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005909 mAudioMixer->setParameter(
5910 trackId,
5911 AudioMixer::TRACK,
Andy Hung11e74242023-06-26 19:20:57 -07005912 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08005913
5914 // reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07005915 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005916
5917 // If one track is ready, set the mixer ready if:
5918 // - the mixer was not ready during previous round OR
5919 // - no other track is not ready
5920 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5921 mixerStatus != MIXER_TRACKS_ENABLED) {
5922 mixerStatus = MIXER_TRACKS_READY;
5923 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005924
5925 // Enable the next few lines to instrument a test for underrun log handling.
5926 // TODO: Remove when we have a better way of testing the underrun log.
5927#if 0
5928 static int i;
5929 if ((++i & 0xf) == 0) {
5930 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5931 }
5932#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005933 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005934 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005935 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005936 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5937 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005938 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005939 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005940 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005941
Eric Laurent81784c32012-11-19 14:55:58 -08005942 // clear effect chain input buffer if an active track underruns to avoid sending
5943 // previous audio buffer again to effects
5944 chain = getEffectChain_l(track->sessionId());
5945 if (chain != 0) {
5946 chain->clearInputBuffer();
5947 }
5948
Andy Hungc0691382018-09-12 18:01:57 -07005949 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005950 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5951 track->isStopped() || track->isPaused()) {
5952 // We have consumed all the buffers of this track.
5953 // Remove it from the list of active tracks.
5954 // TODO: use actual buffer filling status instead of latency when available from
5955 // audio HAL
5956 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005957 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005958 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5959 if (track->isStopped()) {
5960 track->reset();
5961 }
5962 tracksToRemove->add(track);
5963 }
5964 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005965 // No buffers for this track. Give it a few chances to
5966 // fill a buffer, then remove it from active list.
Andy Hung11e74242023-06-26 19:20:57 -07005967 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005968 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5969 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005970 tracksToRemove->add(track);
5971 // indicate to client process that the track was disabled because of underrun;
5972 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005973 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005974 // If one track is not ready, mark the mixer also not ready if:
5975 // - the mixer was ready during previous round OR
5976 // - no other track is ready
5977 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5978 mixerStatus != MIXER_TRACKS_READY) {
5979 mixerStatus = MIXER_TRACKS_ENABLED;
5980 }
5981 }
Andy Hungc0691382018-09-12 18:01:57 -07005982 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005983 }
5984
5985 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005986
5987 }
5988
jiabin245cdd92018-12-07 17:55:15 -08005989 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5990 // When there is no fast track playing haptic and FastMixer exists,
5991 // enabling the first FastTrack, which provides mixed data from normal
5992 // tracks, to play haptic data.
5993 FastTrack *fastTrack = &state->mFastTracks[0];
5994 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5995 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5996 didModify = true;
5997 }
5998 }
5999
Eric Laurent81784c32012-11-19 14:55:58 -08006000 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006001 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006002 if (didModify) {
6003 state->mFastTracksGen++;
6004 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6005 if (kUseFastMixer == FastMixer_Dynamic &&
6006 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6007 state->mCommand = FastMixerState::COLD_IDLE;
6008 state->mColdFutexAddr = &mFastMixerFutex;
6009 state->mColdGen++;
6010 mFastMixerFutex = 0;
6011 if (kUseFastMixer == FastMixer_Dynamic) {
6012 mNormalSink = mOutputSink;
6013 }
6014 // If we go into cold idle, need to wait for acknowledgement
6015 // so that fast mixer stops doing I/O.
6016 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6017 pauseAudioWatchdog = true;
6018 }
Eric Laurent81784c32012-11-19 14:55:58 -08006019 }
6020 if (sq != NULL) {
6021 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006022 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6023 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6024 // when bringing the output sink into standby.)
6025 //
6026 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6027 //
6028 // This occurs with BT suspend when we idle the FastMixer with
6029 // active tracks, which may be added or removed.
6030 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006031 }
6032#ifdef AUDIO_WATCHDOG
6033 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6034 mAudioWatchdog->pause();
6035 }
6036#endif
6037
6038 // Now perform the deferred reset on fast tracks that have stopped
6039 while (resetMask != 0) {
6040 size_t i = __builtin_ctz(resetMask);
6041 ALOG_ASSERT(i < count);
6042 resetMask &= ~(1 << i);
Andy Hung11e74242023-06-26 19:20:57 -07006043 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006044 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6045 track->reset();
6046 }
6047
Andy Hung80d03d22018-04-10 10:32:11 -07006048 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6049 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6050 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6051 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6052 // See also the implementation of destroyTrack_l().
6053 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006054 const int trackId = track->id();
6055 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6056 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006057 }
6058 }
6059
Eric Laurent81784c32012-11-19 14:55:58 -08006060 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006061 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006062
Eric Laurentb3f315a2021-07-13 15:09:05 +02006063 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6064 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006065 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006066 }
6067
6068 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006069 // as long as there are effects we should clear the effects buffer, to avoid
6070 // passing a non-clean buffer to the effect chain
6071 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006072 if (mType == SPATIALIZER) {
6073 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6074 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006075 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006076 // sink or mix buffer must be cleared if all tracks are connected to an
6077 // effect chain as in this case the mixer will not write to the sink or mix buffer
6078 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006079 // always clear sink buffer for spatializer output as the output of the spatializer
6080 // effect will be accumulated into it
6081 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6082 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006083 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006084 if (mMixerBufferValid) {
6085 memset(mMixerBuffer, 0, mMixerBufferSize);
6086 // TODO: In testing, mSinkBuffer below need not be cleared because
6087 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6088 // after mixing.
6089 //
6090 // To enforce this guarantee:
6091 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6092 // (mixedTracks == 0 && fastTracks > 0))
6093 // must imply MIXER_TRACKS_READY.
6094 // Later, we may clear buffers regardless, and skip much of this logic.
6095 }
Andy Hung98ef9782014-03-04 14:46:50 -08006096 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006097 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006098 }
6099
6100 // if any fast tracks, then status is ready
6101 mMixerStatusIgnoringFastTracks = mixerStatus;
6102 if (fastTracks > 0) {
6103 mixerStatus = MIXER_TRACKS_READY;
6104 }
6105 return mixerStatus;
6106}
6107
Eric Laurentad7dd962016-09-22 12:38:37 -07006108// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07006109uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006110{
6111 uint32_t trackCount = 0;
6112 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006113 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006114 trackCount++;
6115 }
6116 }
6117 return trackCount;
6118}
6119
Andy Hung4b17e882023-07-07 13:47:37 -07006120bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006121{
Brian Lindahl65e90012022-07-27 18:01:07 +02006122 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6123 // could falsely detect that the frame position has stalled due to underrun because we haven't
6124 // given the Audio HAL enough time to update.
6125 const nsecs_t nowNs = systemTime();
6126 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6127 return mLatchedValue;
6128 }
6129 mPreviousNs = nowNs;
6130 mLatchedValue = false;
6131 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006132 uint64_t position = 0;
6133 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006134 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006135 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006136 if (position != mPreviousPosition) {
6137 mPreviousPosition = position;
6138 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006139 }
6140 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006141 return mLatchedValue;
6142}
6143
Andy Hung4b17e882023-07-07 13:47:37 -07006144void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006145{
6146 mLatchedValue = true;
6147 mPreviousPosition = 0;
6148 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006149}
6150
Andy Hung1bc088a2018-02-09 15:57:31 -08006151// isTrackAllowed_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07006152bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006153 audio_channel_mask_t channelMask, audio_format_t format,
6154 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006155{
Andy Hung1bc088a2018-02-09 15:57:31 -08006156 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6157 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006158 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006159 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006160 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006161 ALOGW("%s: invalid format: %#x", __func__, format);
6162 return false;
6163 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006164 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006165 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6166 return false;
6167 }
6168 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006169}
6170
Eric Laurent10351942014-05-08 18:49:52 -07006171// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07006172bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006173 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006174{
Eric Laurent81784c32012-11-19 14:55:58 -08006175 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006176 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006177
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006178 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006179
Eric Laurent10351942014-05-08 18:49:52 -07006180 AudioParameter param = AudioParameter(keyValuePair);
6181 int value;
6182 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6183 reconfig = true;
6184 }
6185 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung4b17e882023-07-07 13:47:37 -07006186 if (!AudioFlinger::isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006187 status = BAD_VALUE;
6188 } else {
6189 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006190 reconfig = true;
6191 }
Eric Laurent10351942014-05-08 18:49:52 -07006192 }
6193 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung4b17e882023-07-07 13:47:37 -07006194 if (!AudioFlinger::isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006195 status = BAD_VALUE;
6196 } else {
6197 // no need to save value, since it's constant
6198 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006199 }
Eric Laurent10351942014-05-08 18:49:52 -07006200 }
6201 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6202 // do not accept frame count changes if tracks are open as the track buffer
6203 // size depends on frame count and correct behavior would not be guaranteed
6204 // if frame count is changed after track creation
6205 if (!mTracks.isEmpty()) {
6206 status = INVALID_OPERATION;
6207 } else {
6208 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006209 }
Eric Laurent10351942014-05-08 18:49:52 -07006210 }
6211 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006212 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006213 }
Eric Laurent81784c32012-11-19 14:55:58 -08006214
Eric Laurent10351942014-05-08 18:49:52 -07006215 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006216 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006217 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006218 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6219 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006220 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006221 mThreadMetrics.logEndInterval();
6222 mThreadSnapshot.onEnd();
6223 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006224 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006225 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006226 }
Eric Laurent10351942014-05-08 18:49:52 -07006227 if (status == NO_ERROR && reconfig) {
6228 readOutputParameters_l();
6229 delete mAudioMixer;
6230 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006231 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006232 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006233 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006234 trackId,
Andy Hung11e74242023-06-26 19:20:57 -07006235 track->channelMask(),
6236 track->format(),
6237 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006238 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006239 "%s(): AudioMixer cannot create track(%d)"
6240 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006241 __func__,
Andy Hung11e74242023-06-26 19:20:57 -07006242 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006243 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006244 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006245 }
Eric Laurent81784c32012-11-19 14:55:58 -08006246 }
6247
Dean Wheatley68918102021-03-19 22:09:19 +11006248 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006249}
6250
6251
Andy Hung4b17e882023-07-07 13:47:37 -07006252void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006253{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006254 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006255 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006256 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006257 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006258 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6259 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6260 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006261 if (hasFastMixer()) {
6262 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6263
6264 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6265 // while we are dumping it. It may be inconsistent, but it won't mutate!
6266 // This is a large object so we place it on the heap.
6267 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006268 const std::unique_ptr<FastMixerDumpState> copy =
6269 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006270 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006271
6272#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006273 // Similar for state queue
6274 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6275 observerCopy.dump(fd);
6276 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6277 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006278#endif
6279
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006280#ifdef AUDIO_WATCHDOG
6281 if (mAudioWatchdog != 0) {
6282 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6283 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6284 wdCopy.dump(fd);
6285 }
6286#endif
6287
6288 } else {
6289 dprintf(fd, " No FastMixer\n");
6290 }
Eric Laurent90cea102023-05-15 15:08:27 +02006291
6292 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6293 mBluetoothLatencyModesEnabled ? "" : "not ");
6294 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6295 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6296 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006297}
6298
Andy Hung4b17e882023-07-07 13:47:37 -07006299uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006300{
6301 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6302}
6303
Andy Hung4b17e882023-07-07 13:47:37 -07006304uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006305{
6306 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6307}
6308
Andy Hung4b17e882023-07-07 13:47:37 -07006309void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006310{
6311 PlaybackThread::cacheParameters_l();
6312
6313 // FIXME: Relaxed timing because of a certain device that can't meet latency
6314 // Should be reduced to 2x after the vendor fixes the driver issue
6315 // increase threshold again due to low power audio mode. The way this warning
6316 // threshold is calculated and its usefulness should be reconsidered anyway.
6317 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6318}
6319
Andy Hung4b17e882023-07-07 13:47:37 -07006320void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung7535ed92023-07-17 17:05:00 -07006321 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006322}
6323
Andy Hung4b17e882023-07-07 13:47:37 -07006324void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006325 // Only handle latency mode if:
6326 // - mBluetoothLatencyModesEnabled is true
6327 // - the HAL supports latency modes
6328 // - the selected device is Bluetooth LE or A2DP
6329 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6330 return;
6331 }
6332 if (mOutDeviceTypeAddrs.size() != 1
6333 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6334 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6335 return;
6336 }
6337
6338 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6339 if (mSupportedLatencyModes.size() == 1) {
6340 // If the HAL only support one latency mode currently, confirm the choice
6341 latencyMode = mSupportedLatencyModes[0];
6342 } else if (mSupportedLatencyModes.size() > 1) {
6343 // Request low latency if:
6344 // - At least one active track is either:
6345 // - a fast track with gaming usage or
6346 // - a track with acessibility usage
6347 for (const auto& track : mActiveTracks) {
6348 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6349 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6350 latencyMode = AUDIO_LATENCY_MODE_LOW;
6351 break;
6352 }
6353 }
6354 }
6355
6356 if (latencyMode != mSetLatencyMode) {
6357 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6358 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6359 __func__, mId, toString(latencyMode).c_str(), status);
6360 if (status == NO_ERROR) {
6361 mSetLatencyMode = latencyMode;
6362 }
6363 }
6364}
6365
Andy Hung4b17e882023-07-07 13:47:37 -07006366void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006367
6368 if (mOutput == nullptr || mOutput->stream == nullptr) {
6369 return;
6370 }
6371 std::vector<audio_latency_mode_t> latencyModes;
6372 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6373 if (status != NO_ERROR) {
6374 latencyModes.clear();
6375 }
6376 if (latencyModes != mSupportedLatencyModes) {
6377 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6378 __func__, mId, status, toString(latencyModes).c_str());
6379 mSupportedLatencyModes.swap(latencyModes);
6380 sendHalLatencyModesChangedEvent_l();
6381 }
6382}
6383
Andy Hung4b17e882023-07-07 13:47:37 -07006384status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006385 std::vector<audio_latency_mode_t>* modes) {
6386 if (modes == nullptr) {
6387 return BAD_VALUE;
6388 }
6389 Mutex::Autolock _l(mLock);
6390 *modes = mSupportedLatencyModes;
6391 return NO_ERROR;
6392}
6393
Andy Hung4b17e882023-07-07 13:47:37 -07006394void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006395 std::vector<audio_latency_mode_t> modes) {
6396 Mutex::Autolock _l(mLock);
6397 if (modes != mSupportedLatencyModes) {
6398 ALOGD("%s: thread(%d) supported latency modes: %s",
6399 __func__, mId, toString(modes).c_str());
6400 mSupportedLatencyModes.swap(modes);
6401 sendHalLatencyModesChangedEvent_l();
6402 }
6403}
6404
Andy Hung4b17e882023-07-07 13:47:37 -07006405status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006406 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6407 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6408 return INVALID_OPERATION;
6409 }
6410 mBluetoothLatencyModesEnabled.store(enabled);
6411 return NO_ERROR;
6412}
6413
Eric Laurent81784c32012-11-19 14:55:58 -08006414// ----------------------------------------------------------------------------
6415
Andy Hung4b17e882023-07-07 13:47:37 -07006416/* static */
6417sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung7535ed92023-07-17 17:05:00 -07006418 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07006419 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6420 const audio_offload_info_t& offloadInfo) {
6421 return sp<DirectOutputThread>::make(
Andy Hung7535ed92023-07-17 17:05:00 -07006422 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung4b17e882023-07-07 13:47:37 -07006423}
6424
Andy Hung7535ed92023-07-17 17:05:00 -07006425DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006426 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6427 const audio_offload_info_t& offloadInfo)
Andy Hung7535ed92023-07-17 17:05:00 -07006428 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006429 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006430{
Andy Hung7535ed92023-07-17 17:05:00 -07006431 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006432}
6433
Andy Hung4b17e882023-07-07 13:47:37 -07006434DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006435{
6436}
6437
Andy Hung4b17e882023-07-07 13:47:37 -07006438void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006439{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006440 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006441 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6442 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6443}
6444
Andy Hung4b17e882023-07-07 13:47:37 -07006445void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006446{
6447 Mutex::Autolock _l(mLock);
6448 if (mMasterBalance != balance) {
6449 mMasterBalance.store(balance);
6450 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6451 broadcast_l();
6452 }
6453}
6454
Andy Hung4b17e882023-07-07 13:47:37 -07006455void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006456{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006457 float left, right;
6458
Andy Hung333ab962019-05-28 20:23:35 -07006459 // Ensure volumeshaper state always advances even when muted.
Andy Hung11e74242023-06-26 19:20:57 -07006460 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006461
6462 const size_t framesReleased = proxy->framesReleased();
6463 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6464 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6465
6466 ALOGV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6467 __func__, framesReleased, (long long)frames, (long long)time);
6468
6469 const int64_t volumeShaperFrames =
6470 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6471 const auto [shaperVolume, shaperActive] =
6472 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006473 mVolumeShaperActive = shaperActive;
6474
Vlad Popae2f5aef2022-07-25 16:00:20 +02006475 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6476 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6477 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6478
6479 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6480
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006481 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006482 left = right = 0;
6483 } else {
6484 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006485 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006486
Glenn Kastenc56f3422014-03-21 17:53:17 -07006487 if (left > GAIN_FLOAT_UNITY) {
6488 left = GAIN_FLOAT_UNITY;
6489 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006490 if (right > GAIN_FLOAT_UNITY) {
6491 right = GAIN_FLOAT_UNITY;
6492 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006493 left *= v;
6494 right *= v;
Andy Hung7535ed92023-07-17 17:05:00 -07006495 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006496 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6497 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6498 right *= mMasterBalanceRight;
6499 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006500 }
6501
Andy Hung7535ed92023-07-17 17:05:00 -07006502 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006503 /*muteState=*/{mMasterMute,
6504 mStreamTypes[track->streamType()].volume == 0.f,
6505 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006506 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006507 clientVolumeMute,
6508 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006509
Eric Laurentbfb1b832013-01-07 09:53:42 -08006510 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006511 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006512 if (left != mLeftVolFloat || right != mRightVolFloat) {
6513 mLeftVolFloat = left;
6514 mRightVolFloat = right;
6515
Eric Laurentbfb1b832013-01-07 09:53:42 -08006516 // Delegate volume control to effect in track effect chain if needed
6517 // only one effect chain can be present on DirectOutputThread, so if
6518 // there is one, the track is connected to it
6519 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006520 // if effect chain exists, volume is handled by it.
6521 // Convert volumes from float to 8.24
6522 uint32_t vl = (uint32_t)(left * (1 << 24));
6523 uint32_t vr = (uint32_t)(right * (1 << 24));
6524 // Direct/Offload effect chains set output volume in setVolume_l().
6525 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6526 } else {
6527 // otherwise we directly set the volume.
6528 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006529 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006530 }
6531 }
6532}
6533
Andy Hung4b17e882023-07-07 13:47:37 -07006534void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006535{
Andy Hung11e74242023-06-26 19:20:57 -07006536 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6537 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006538
Eric Laurent0f0631e2015-07-06 18:01:25 -07006539 if (previousTrack != 0 && latestTrack != 0) {
6540 if (mType == DIRECT) {
6541 if (previousTrack.get() != latestTrack.get()) {
6542 mFlushPending = true;
6543 }
6544 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006545 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6546 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006547 mFlushPending = true;
6548 }
6549 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006550 } else if (previousTrack == 0) {
6551 // there could be an old track added back during track transition for direct
6552 // output, so always issues flush to flush data of the previous track if it
6553 // was already destroyed with HAL paused, then flush can resume the playback
6554 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006555 }
6556 PlaybackThread::onAddNewTrack_l();
6557}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006558
Andy Hung4b17e882023-07-07 13:47:37 -07006559PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07006560 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006561)
6562{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006563 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006564 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006565 bool doHwPause = false;
6566 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006567
6568 // find out which tracks need to be processed
Andy Hung11e74242023-06-26 19:20:57 -07006569 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006570 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006571 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006572 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006573 continue;
6574 }
6575
Andy Hung11e74242023-06-26 19:20:57 -07006576 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006577#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006578 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006579#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006580 // Only consider last track started for volume and mixer state control.
6581 // In theory an older track could underrun and restart after the new one starts
6582 // but as we only care about the transition phase between two tracks on a
6583 // direct output, it is not a problem to ignore the underrun case.
Andy Hung11e74242023-06-26 19:20:57 -07006584 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006585 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006586
Kuowei Li23666472021-01-20 10:23:25 +08006587 if (track->isPausePending()) {
6588 track->pauseAck();
6589 // It is possible a track might have been flushed or stopped.
6590 // Other operations such as flush pending might occur on the next prepare.
6591 if (track->isPausing()) {
6592 track->setPaused();
6593 }
6594 // Always perform pause, as an immediate flush will change
6595 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006596 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006597 doHwPause = true;
6598 mHwPaused = true;
6599 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006600 } else if (track->isFlushPending()) {
6601 track->flushAck();
6602 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006603 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006604 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006605 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006606 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006607 if (last) {
6608 mLeftVolFloat = mRightVolFloat = -1.0;
6609 if (mHwPaused) {
6610 doHwResume = true;
6611 mHwPaused = false;
6612 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006613 }
6614 }
6615
Eric Laurent81784c32012-11-19 14:55:58 -08006616 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006617 // for all its buffers to be filled before processing it.
6618 // Allow draining the buffer in case the client
6619 // app does not call stop() and relies on underrun to stop:
Andy Hung11e74242023-06-26 19:20:57 -07006620 // hence the test on (track->retryCount() > 1).
6621 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006622 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6623 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006624 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006625
6626 // target retry count that we will use is based on the time we wait for retries.
6627 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6628 // the retry threshold is when we accept any size for PCM data. This is slightly
6629 // smaller than the retry count so we can push small bits of data without a glitch.
6630 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006631 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006632 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung11e74242023-06-26 19:20:57 -07006633 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006634 minFrames = mNormalFrameCount;
6635 } else {
6636 minFrames = 1;
6637 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006638
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006639 const size_t framesReady = track->framesReady();
6640 const int trackId = track->id();
6641 if (ATRACE_ENABLED()) {
6642 std::string traceName("nRdy");
6643 traceName += std::to_string(trackId);
6644 ATRACE_INT(traceName.c_str(), framesReady);
6645 }
6646 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006647 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006648 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006649 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006650
Andy Hung11e74242023-06-26 19:20:57 -07006651 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6652 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006653 if (last) {
6654 // make sure processVolume_l() will apply new volume even if 0
6655 mLeftVolFloat = mRightVolFloat = -1.0;
6656 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006657 if (!mHwSupportsPause) {
6658 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006659 }
6660 }
6661
6662 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006663 processVolume_l(track, last);
6664 if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07006665 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006666 if (previousTrack != 0) {
6667 if (track != previousTrack.get()) {
6668 // Flush any data still being written from last track
6669 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006670 // Invalidate previous track to force a seek when resuming.
6671 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006672 }
6673 }
6674 mPreviousTrack = track;
6675
Eric Laurentd595b7c2013-04-03 17:27:56 -07006676 // reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07006677 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006678 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006679 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006680 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006681 doHwResume = true;
6682 mHwPaused = false;
6683 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006684 }
Eric Laurent81784c32012-11-19 14:55:58 -08006685 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006686 // clear effect chain input buffer if the last active track started underruns
6687 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006688 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006689 mEffectChains[0]->clearInputBuffer();
6690 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006691 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07006692 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006693 if (last && mHwPaused) {
6694 doHwResume = true;
6695 mHwPaused = false;
6696 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006697 }
6698 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6699 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006700 // We have consumed all the buffers of this track.
6701 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006702 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006703 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006704 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006705 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006706 if (presComplete) {
6707 mOutput->presentationComplete();
6708 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006709 if (track->isStopping_2()) {
Andy Hung11e74242023-06-26 19:20:57 -07006710 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006711 }
Eric Laurent81784c32012-11-19 14:55:58 -08006712 if (track->isStopped()) {
6713 track->reset();
6714 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006715 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006716 }
6717 } else {
6718 // No buffers for this track. Give it a few chances to
6719 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006720 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006721 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006722 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung11e74242023-06-26 19:20:57 -07006723 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006724 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung11e74242023-06-26 19:20:57 -07006725 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006726 } else {
6727 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6728 tracksToRemove->add(track);
6729 // indicate to client process that the track was disabled because of
6730 // underrun; it will then automatically call start() when data is available
6731 track->disable();
6732 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6733 // unlike mixerthread, HAL can be paused for direct output
6734 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6735 "minFrames = %u, mFormat = %#x",
6736 framesReady, minFrames, mFormat);
6737 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6738 doHwPause = true;
6739 mHwPaused = true;
6740 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006741 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006742 } else if (last) {
6743 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006744 }
6745 }
6746 }
6747 }
6748
Eric Laurentd1f69b02014-12-15 14:33:13 -08006749 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006750 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006751 for (size_t i = 0; i < mTracks.size(); i++) {
6752 if (mTracks[i]->isFlushPending()) {
6753 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006754 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006755 }
6756 }
6757 }
6758
6759 // make sure the pause/flush/resume sequence is executed in the right order.
6760 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6761 // before flush and then resume HW. This can happen in case of pause/flush/resume
6762 // if resume is received before pause is executed.
6763 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006764 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006765 status_t result = mOutput->stream->pause();
6766 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006767 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006768 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006769 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006770 flushHw_l();
6771 }
6772 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006773 status_t result = mOutput->stream->resume();
6774 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006775 }
Eric Laurent81784c32012-11-19 14:55:58 -08006776 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006777 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006778
6779 return mixerStatus;
6780}
6781
Andy Hung4b17e882023-07-07 13:47:37 -07006782void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006783{
Eric Laurent81784c32012-11-19 14:55:58 -08006784 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006785 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006786 // output audio to hardware
6787 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006788 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006789 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006790 status_t status = mActiveTrack->getNextBuffer(&buffer);
6791 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006792 // no need to pad with 0 for compressed audio
6793 if (audio_has_proportional_frames(mFormat)) {
6794 memset(curBuf, 0, frameCount * mFrameSize);
6795 }
Eric Laurent81784c32012-11-19 14:55:58 -08006796 break;
6797 }
6798 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6799 frameCount -= buffer.frameCount;
6800 curBuf += buffer.frameCount * mFrameSize;
6801 mActiveTrack->releaseBuffer(&buffer);
6802 }
Andy Hung2098f272014-02-27 14:00:06 -08006803 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006804 mSleepTimeUs = 0;
6805 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006806 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006807}
6808
Andy Hung4b17e882023-07-07 13:47:37 -07006809void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006810{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006811 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006812 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006813 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006814 return;
6815 }
Andy Hung85ba3332021-04-27 17:40:26 -07006816 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6817 mSleepTimeUs = mActiveSleepTimeUs;
6818 } else {
6819 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006820 }
Andy Hung85ba3332021-04-27 17:40:26 -07006821 // Note: In S or later, we do not write zeroes for
6822 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006823}
6824
Andy Hung4b17e882023-07-07 13:47:37 -07006825void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006826{
6827 {
6828 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006829 for (size_t i = 0; i < mTracks.size(); i++) {
6830 if (mTracks[i]->isFlushPending()) {
6831 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006832 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006833 }
6834 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006835 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006836 flushHw_l();
6837 }
6838 }
6839 PlaybackThread::threadLoop_exit();
6840}
6841
6842// must be called with thread mutex locked
Andy Hung4b17e882023-07-07 13:47:37 -07006843bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006844{
6845 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006846 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006847
6848 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6849 // after a timeout and we will enter standby then.
6850 if (mTracks.size() > 0) {
6851 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006852 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung11e74242023-06-26 19:20:57 -07006853 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006854 }
6855
Eric Laurent5cff4032015-05-26 13:49:58 -07006856 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006857}
6858
Eric Laurent10351942014-05-08 18:49:52 -07006859// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07006860bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006861 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006862{
6863 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006864 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006865
Eric Laurent10351942014-05-08 18:49:52 -07006866 AudioParameter param = AudioParameter(keyValuePair);
6867 int value;
6868 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006869 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006870 }
Eric Laurent10351942014-05-08 18:49:52 -07006871 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6872 // do not accept frame count changes if tracks are open as the track buffer
6873 // size depends on frame count and correct behavior would not be garantied
6874 // if frame count is changed after track creation
6875 if (!mTracks.isEmpty()) {
6876 status = INVALID_OPERATION;
6877 } else {
6878 reconfig = true;
6879 }
6880 }
6881 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006882 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006883 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006884 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006885 if (!mStandby) {
6886 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006887 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02006888 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07006889 }
Eric Laurent10351942014-05-08 18:49:52 -07006890 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006891 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006892 }
6893 if (status == NO_ERROR && reconfig) {
6894 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006895 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006896 }
6897 }
6898
Dean Wheatley68918102021-03-19 22:09:19 +11006899 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006900}
6901
Andy Hung4b17e882023-07-07 13:47:37 -07006902uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006903{
6904 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006905 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006906 time = PlaybackThread::activeSleepTimeUs();
6907 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006908 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006909 }
6910 return time;
6911}
6912
Andy Hung4b17e882023-07-07 13:47:37 -07006913uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006914{
6915 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006916 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006917 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6918 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006919 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006920 }
6921 return time;
6922}
6923
Andy Hung4b17e882023-07-07 13:47:37 -07006924uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006925{
6926 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006927 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006928 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6929 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006930 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006931 }
6932 return time;
6933}
6934
Andy Hung4b17e882023-07-07 13:47:37 -07006935void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006936{
6937 PlaybackThread::cacheParameters_l();
6938
6939 // use shorter standby delay as on normal output to release
6940 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006941 // no delay on outputs with HW A/V sync
6942 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006943 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006944 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006945 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006946 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006947 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006948 }
Eric Laurent81784c32012-11-19 14:55:58 -08006949}
6950
Andy Hung4b17e882023-07-07 13:47:37 -07006951void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07006952{
ziyangch8f194f12021-12-01 13:48:04 -08006953 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08006954 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006955 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006956 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006957 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006958 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08006959 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07006960}
6961
Andy Hung4b17e882023-07-07 13:47:37 -07006962int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08006963 // If a VolumeShaper is active, we must wake up periodically to update volume.
6964 const int64_t NS_PER_MS = 1000000;
6965 return mVolumeShaperActive ?
6966 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6967}
6968
Eric Laurent81784c32012-11-19 14:55:58 -08006969// ----------------------------------------------------------------------------
6970
Andy Hung4b17e882023-07-07 13:47:37 -07006971AsyncCallbackThread::AsyncCallbackThread(
6972 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006973 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006974 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006975 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006976 mDrainSequence(0),
6977 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006978{
6979}
6980
Andy Hung4b17e882023-07-07 13:47:37 -07006981void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08006982{
6983 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6984}
6985
Andy Hung4b17e882023-07-07 13:47:37 -07006986bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08006987{
6988 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006989 uint32_t writeAckSequence;
6990 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006991 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006992
6993 {
6994 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006995 while (!((mWriteAckSequence & 1) ||
6996 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006997 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006998 exitPending())) {
6999 mWaitWorkCV.wait(mLock);
7000 }
7001
Eric Laurentbfb1b832013-01-07 09:53:42 -08007002 if (exitPending()) {
7003 break;
7004 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007005 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7006 mWriteAckSequence, mDrainSequence);
7007 writeAckSequence = mWriteAckSequence;
7008 mWriteAckSequence &= ~1;
7009 drainSequence = mDrainSequence;
7010 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007011 asyncError = mAsyncError;
7012 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007013 }
7014 {
Andy Hung4b17e882023-07-07 13:47:37 -07007015 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007016 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007017 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007018 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007019 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007020 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007021 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007022 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007023 if (asyncError) {
7024 playbackThread->onAsyncError();
7025 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007026 }
7027 }
7028 }
7029 return false;
7030}
7031
Andy Hung4b17e882023-07-07 13:47:37 -07007032void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007033{
7034 ALOGV("AsyncCallbackThread::exit");
7035 Mutex::Autolock _l(mLock);
7036 requestExit();
7037 mWaitWorkCV.broadcast();
7038}
7039
Andy Hung4b17e882023-07-07 13:47:37 -07007040void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007041{
7042 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007043 // bit 0 is cleared
7044 mWriteAckSequence = sequence << 1;
7045}
7046
Andy Hung4b17e882023-07-07 13:47:37 -07007047void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007048{
7049 Mutex::Autolock _l(mLock);
7050 // ignore unexpected callbacks
7051 if (mWriteAckSequence & 2) {
7052 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007053 mWaitWorkCV.signal();
7054 }
7055}
7056
Andy Hung4b17e882023-07-07 13:47:37 -07007057void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007058{
7059 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007060 // bit 0 is cleared
7061 mDrainSequence = sequence << 1;
7062}
7063
Andy Hung4b17e882023-07-07 13:47:37 -07007064void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007065{
7066 Mutex::Autolock _l(mLock);
7067 // ignore unexpected callbacks
7068 if (mDrainSequence & 2) {
7069 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007070 mWaitWorkCV.signal();
7071 }
7072}
7073
Andy Hung4b17e882023-07-07 13:47:37 -07007074void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007075{
7076 Mutex::Autolock _l(mLock);
7077 mAsyncError = true;
7078 mWaitWorkCV.signal();
7079}
7080
Eric Laurentbfb1b832013-01-07 09:53:42 -08007081
7082// ----------------------------------------------------------------------------
Andy Hung4b17e882023-07-07 13:47:37 -07007083
7084/* static */
7085sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung7535ed92023-07-17 17:05:00 -07007086 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007087 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7088 const audio_offload_info_t& offloadInfo) {
Andy Hung7535ed92023-07-17 17:05:00 -07007089 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung4b17e882023-07-07 13:47:37 -07007090}
7091
Andy Hung7535ed92023-07-17 17:05:00 -07007092OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007093 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7094 const audio_offload_info_t& offloadInfo)
Andy Hung7535ed92023-07-17 17:05:00 -07007095 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007096 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007097{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007098 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007099 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007100 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007101}
7102
Andy Hung4b17e882023-07-07 13:47:37 -07007103void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007104{
7105 if (mFlushPending || mHwPaused) {
7106 // If a flush is pending or track was paused, just discard buffered data
7107 flushHw_l();
7108 } else {
7109 mMixerStatus = MIXER_DRAIN_ALL;
7110 threadLoop_drain();
7111 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007112 if (mUseAsyncWrite) {
7113 ALOG_ASSERT(mCallbackThread != 0);
7114 mCallbackThread->exit();
7115 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007116 PlaybackThread::threadLoop_exit();
7117}
7118
Andy Hung4b17e882023-07-07 13:47:37 -07007119PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07007120 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007121)
7122{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007123 size_t count = mActiveTracks.size();
7124
7125 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007126 bool doHwPause = false;
7127 bool doHwResume = false;
7128
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007129 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007130
Eric Laurentbfb1b832013-01-07 09:53:42 -08007131 // find out which tracks need to be processed
Andy Hung11e74242023-06-26 19:20:57 -07007132 for (const sp<IAfTrack>& t : mActiveTracks) {
7133 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007134#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007135 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007136#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007137 // Only consider last track started for volume and mixer state control.
7138 // In theory an older track could underrun and restart after the new one starts
7139 // but as we only care about the transition phase between two tracks on a
7140 // direct output, it is not a problem to ignore the underrun case.
Andy Hung11e74242023-06-26 19:20:57 -07007141 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007142 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007143
Haynes Mathew George7844f672014-01-15 12:32:55 -08007144 if (track->isInvalid()) {
7145 ALOGW("An invalidated track shouldn't be in active list");
7146 tracksToRemove->add(track);
7147 continue;
7148 }
7149
Andy Hung11e74242023-06-26 19:20:57 -07007150 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007151 ALOGW("An idle track shouldn't be in active list");
7152 continue;
7153 }
7154
Kuowei Li23666472021-01-20 10:23:25 +08007155 if (track->isPausePending()) {
7156 track->pauseAck();
7157 // It is possible a track might have been flushed or stopped.
7158 // Other operations such as flush pending might occur on the next prepare.
7159 if (track->isPausing()) {
7160 track->setPaused();
7161 }
7162 // Always perform pause if last, as an immediate flush will change
7163 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007164 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007165 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007166 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007167 mHwPaused = true;
7168 }
7169 // If we were part way through writing the mixbuffer to
7170 // the HAL we must save this until we resume
7171 // BUG - this will be wrong if a different track is made active,
7172 // in that case we want to discard the pending data in the
7173 // mixbuffer and tell the client to present it again when the
7174 // track is resumed
7175 mPausedWriteLength = mCurrentWriteLength;
7176 mPausedBytesRemaining = mBytesRemaining;
7177 mBytesRemaining = 0; // stop writing
7178 }
7179 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007180 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007181 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007182 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007183 } else {
Andy Hung11e74242023-06-26 19:20:57 -07007184 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007185 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007186 track->flushAck();
7187 if (last) {
7188 mFlushPending = true;
7189 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007190 } else if (track->isResumePending()){
7191 track->resumeAck();
7192 if (last) {
7193 if (mPausedBytesRemaining) {
7194 // Need to continue write that was interrupted
7195 mCurrentWriteLength = mPausedWriteLength;
7196 mBytesRemaining = mPausedBytesRemaining;
7197 mPausedBytesRemaining = 0;
7198 }
7199 if (mHwPaused) {
7200 doHwResume = true;
7201 mHwPaused = false;
7202 // threadLoop_mix() will handle the case that we need to
7203 // resume an interrupted write
7204 }
7205 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007206 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007207
Eric Laurent3df841a2016-07-15 15:15:40 -07007208 mLeftVolFloat = mRightVolFloat = -1.0;
7209
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007210 // Do not handle new data in this iteration even if track->framesReady()
7211 mixerStatus = MIXER_TRACKS_ENABLED;
7212 }
7213 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007214 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007215 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung11e74242023-06-26 19:20:57 -07007216 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7217 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007218 if (last) {
7219 // make sure processVolume_l() will apply new volume even if 0
7220 mLeftVolFloat = mRightVolFloat = -1.0;
7221 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007222 }
7223
7224 if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07007225 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007226 if (previousTrack != 0) {
7227 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007228 // Flush any data still being written from last track
7229 mBytesRemaining = 0;
7230 if (mPausedBytesRemaining) {
7231 // Last track was paused so we also need to flush saved
7232 // mixbuffer state and invalidate track so that it will
7233 // re-submit that unwritten data when it is next resumed
7234 mPausedBytesRemaining = 0;
7235 // Invalidate is a bit drastic - would be more efficient
7236 // to have a flag to tell client that some of the
7237 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007238 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007239 }
7240 // flush data already sent to the DSP if changing audio session as audio
7241 // comes from a different source. Also invalidate previous track to force a
7242 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007243 if (previousTrack->sessionId() != track->sessionId()) {
7244 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007245 }
7246 }
7247 }
7248 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007249 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007250 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007251 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007252 } else {
Andy Hung11e74242023-06-26 19:20:57 -07007253 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007254 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007255 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007256 mixerStatus = MIXER_TRACKS_READY;
7257 }
7258 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007259 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007260 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007261 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007262 // Hardware buffer can hold a large amount of audio so we must
7263 // wait for all current track's data to drain before we say
7264 // that the track is stopped.
7265 if (mBytesRemaining == 0) {
7266 // Only start draining when all data in mixbuffer
7267 // has been written
7268 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung11e74242023-06-26 19:20:57 -07007269 track->setState(IAfTrackBase::STOPPING_2);
7270 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007271 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7272 if (last && !mStandby) {
7273 // do not modify drain sequence if we are already draining. This happens
7274 // when resuming from pause after drain.
7275 if ((mDrainSequence & 1) == 0) {
7276 mSleepTimeUs = 0;
7277 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7278 mixerStatus = MIXER_DRAIN_TRACK;
7279 mDrainSequence += 2;
7280 }
7281 if (mHwPaused) {
7282 // It is possible to move from PAUSED to STOPPING_1 without
7283 // a resume so we must ensure hardware is running
7284 doHwResume = true;
7285 mHwPaused = false;
7286 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007287 }
7288 }
Eric Laurente93cc032016-05-05 10:15:10 -07007289 } else if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07007290 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007291 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007292 }
7293 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007294 // Drain has completed or we are in standby, signal presentation complete
7295 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung11e74242023-06-26 19:20:57 -07007296 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007297 mOutput->presentationComplete();
7298 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007299 track->reset();
7300 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007301 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007302 if (!mUseAsyncWrite) {
7303 // If we don't get explicit drain notification we must
7304 // register discontinuity regardless of whether this is
7305 // the previous (!last) or the upcoming (last) track
7306 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007307 mTimestampVerifier.discontinuity(
7308 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007309 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007310 }
7311 } else {
7312 // No buffers for this track. Give it a few chances to
7313 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007314 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007315 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung11e74242023-06-26 19:20:57 -07007316 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007317 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung11e74242023-06-26 19:20:57 -07007318 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007319 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007320 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7321 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007322 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007323 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007324 // it will then automatically call start() when data is available
7325 track->disable();
7326 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007327 } else if (last){
7328 mixerStatus = MIXER_TRACKS_ENABLED;
7329 }
7330 }
7331 }
7332 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007333 if (track->isReady()) { // check ready to prevent premature start.
7334 processVolume_l(track, last);
7335 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007336 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007337
Eric Laurentea0fade2013-10-04 16:23:48 -07007338 // make sure the pause/flush/resume sequence is executed in the right order.
7339 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7340 // before flush and then resume HW. This can happen in case of pause/flush/resume
7341 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007342 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007343 status_t result = mOutput->stream->pause();
7344 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007345 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007346 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007347 if (mFlushPending) {
7348 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007349 }
Eric Laurentfd477972013-10-25 18:10:40 -07007350 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007351 status_t result = mOutput->stream->resume();
7352 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007353 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007354
Eric Laurentbfb1b832013-01-07 09:53:42 -08007355 // remove all the tracks that need to be...
7356 removeTracks_l(*tracksToRemove);
7357
7358 return mixerStatus;
7359}
7360
Eric Laurentbfb1b832013-01-07 09:53:42 -08007361// must be called with thread mutex locked
Andy Hung4b17e882023-07-07 13:47:37 -07007362bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007363{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007364 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7365 mWriteAckSequence, mDrainSequence);
7366 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007367 return true;
7368 }
7369 return false;
7370}
7371
Andy Hung4b17e882023-07-07 13:47:37 -07007372bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007373{
7374 Mutex::Autolock _l(mLock);
7375 return waitingAsyncCallback_l();
7376}
7377
Andy Hung4b17e882023-07-07 13:47:37 -07007378void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007379{
Eric Laurente659ef42014-09-29 13:06:46 -07007380 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007381 // Flush anything still waiting in the mixbuffer
7382 mCurrentWriteLength = 0;
7383 mBytesRemaining = 0;
7384 mPausedWriteLength = 0;
7385 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007386 // reset bytes written count to reflect that DSP buffers are empty after flush.
7387 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007388
Eric Laurentbfb1b832013-01-07 09:53:42 -08007389 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007390 // discard any pending drain or write ack by incrementing sequence
7391 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7392 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007393 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007394 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7395 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007396 }
7397}
7398
Andy Hung4b17e882023-07-07 13:47:37 -07007399void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007400{
7401 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007402 if (PlaybackThread::invalidateTracks_l(streamType)) {
7403 mFlushPending = true;
7404 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007405}
7406
Andy Hung4b17e882023-07-07 13:47:37 -07007407void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08007408 Mutex::Autolock _l(mLock);
7409 if (PlaybackThread::invalidateTracks_l(portIds)) {
7410 mFlushPending = true;
7411 }
7412}
7413
Eric Laurentbfb1b832013-01-07 09:53:42 -08007414// ----------------------------------------------------------------------------
7415
Andy Hung4b17e882023-07-07 13:47:37 -07007416/* static */
7417sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -07007418 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007419 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -07007420 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -07007421}
7422
Andy Hung7535ed92023-07-17 17:05:00 -07007423DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung0c1e11e2023-07-06 20:56:16 -07007424 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -07007425 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007426 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007427 mWaitTimeMs(UINT_MAX)
7428{
7429 addOutputTrack(mainThread);
7430}
7431
Andy Hung4b17e882023-07-07 13:47:37 -07007432DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007433{
7434 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7435 mOutputTracks[i]->destroy();
7436 }
7437}
7438
Andy Hung4b17e882023-07-07 13:47:37 -07007439void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007440{
7441 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007442 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007443 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007444 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007445 if (mMixerBufferValid) {
7446 memset(mMixerBuffer, 0, mMixerBufferSize);
7447 } else {
7448 memset(mSinkBuffer, 0, mSinkBufferSize);
7449 }
Eric Laurent81784c32012-11-19 14:55:58 -08007450 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007451 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007452 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007453 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007454 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007455}
7456
Andy Hung4b17e882023-07-07 13:47:37 -07007457void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007458{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007459 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007460 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007461 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007462 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007463 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007464 }
7465 } else if (mBytesWritten != 0) {
7466 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7467 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007468 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007469 } else {
7470 // flush remaining overflow buffers in output tracks
7471 writeFrames = 0;
7472 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007473 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007474 }
7475}
7476
Andy Hung4b17e882023-07-07 13:47:37 -07007477ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007478{
7479 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007480 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7481
7482 // Consider the first OutputTrack for timestamp and frame counting.
7483
7484 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7485 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7486 // we always claim success.
7487 if (i == 0) {
7488 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7489 ALOGD_IF(correction != 0 && writeFrames != 0,
7490 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7491 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7492 mFramesWritten -= correction;
7493 }
7494
7495 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007496 }
Andy Hungcf10d742020-04-28 15:38:24 -07007497 if (mStandby) {
7498 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007499 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007500 mStandby = false;
7501 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007502 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007503}
7504
Andy Hung4b17e882023-07-07 13:47:37 -07007505void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007506{
7507 // DuplicatingThread implements standby by stopping all tracks
7508 for (size_t i = 0; i < outputTracks.size(); i++) {
7509 outputTracks[i]->stop();
7510 }
7511}
7512
Andy Hung4b17e882023-07-07 13:47:37 -07007513void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007514{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007515 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007516
7517 std::stringstream ss;
7518 const size_t numTracks = mOutputTracks.size();
7519 ss << " " << numTracks << " OutputTracks";
7520 if (numTracks > 0) {
7521 ss << ":";
7522 for (const auto &track : mOutputTracks) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007523 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007524 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007525 if (thread.get() != nullptr) {
7526 ss << thread.get() << ", " << thread->id();
7527 } else {
7528 ss << "null";
7529 }
7530 ss << ")";
7531 }
7532 }
7533 ss << "\n";
7534 std::string result = ss.str();
7535 write(fd, result.c_str(), result.size());
7536}
7537
Andy Hung4b17e882023-07-07 13:47:37 -07007538void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007539{
7540 outputTracks = mOutputTracks;
7541}
7542
Andy Hung4b17e882023-07-07 13:47:37 -07007543void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007544{
7545 outputTracks.clear();
7546}
7547
Andy Hung4b17e882023-07-07 13:47:37 -07007548void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007549{
7550 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007551 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7552 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7553 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7554 const size_t frameCount =
7555 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7556 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7557 // from different OutputTracks and their associated MixerThreads (e.g. one may
7558 // nearly empty and the other may be dropping data).
7559
Svet Ganov33761132021-05-13 22:51:08 +00007560 // TODO b/182392769: use attribution source util, move to server edge
7561 AttributionSourceState attributionSource = AttributionSourceState();
7562 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007563 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007564 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007565 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007566 attributionSource.token = sp<BBinder>::make();
Andy Hung11e74242023-06-26 19:20:57 -07007567 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007568 this,
7569 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007570 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007571 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007572 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007573 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007574 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7575 if (status != NO_ERROR) {
7576 ALOGE("addOutputTrack() initCheck failed %d", status);
7577 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007578 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007579 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7580 mOutputTracks.add(outputTrack);
7581 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7582 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007583}
7584
Andy Hung4b17e882023-07-07 13:47:37 -07007585void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007586{
7587 Mutex::Autolock _l(mLock);
7588 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7589 if (mOutputTracks[i]->thread() == thread) {
7590 mOutputTracks[i]->destroy();
7591 mOutputTracks.removeAt(i);
7592 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007593 if (thread->getOutput() == mOutput) {
7594 mOutput = NULL;
7595 }
Eric Laurent81784c32012-11-19 14:55:58 -08007596 return;
7597 }
7598 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007599 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007600}
7601
7602// caller must hold mLock
Andy Hung4b17e882023-07-07 13:47:37 -07007603void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007604{
7605 mWaitTimeMs = UINT_MAX;
7606 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007607 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007608 if (strong != 0) {
7609 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7610 if (waitTimeMs < mWaitTimeMs) {
7611 mWaitTimeMs = waitTimeMs;
7612 }
7613 }
7614 }
7615}
7616
Andy Hung4b17e882023-07-07 13:47:37 -07007617bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007618{
7619 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007620 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007621 if (thread == 0) {
7622 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7623 outputTracks[i].get());
7624 return false;
7625 }
Andy Hung0c1e11e2023-07-06 20:56:16 -07007626 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007627 // see note at standby() declaration
Andy Hung3e4c8742023-06-29 21:19:25 -07007628 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007629 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7630 thread.get());
7631 return false;
7632 }
7633 }
7634 return true;
7635}
7636
Andy Hung4b17e882023-07-07 13:47:37 -07007637void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007638 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007639{
Kevin Rocard12381092018-04-11 09:19:59 -07007640 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7641 outputTrack->setMetadatas(metadata.tracks);
7642 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007643}
7644
Andy Hung4b17e882023-07-07 13:47:37 -07007645uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007646{
7647 return (mWaitTimeMs * 1000) / 2;
7648}
7649
Andy Hung4b17e882023-07-07 13:47:37 -07007650void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007651{
7652 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7653 updateWaitTime_l();
7654
7655 MixerThread::cacheParameters_l();
7656}
7657
Eric Laurentb3f315a2021-07-13 15:09:05 +02007658// ----------------------------------------------------------------------------
7659
Andy Hung4b17e882023-07-07 13:47:37 -07007660/* static */
7661sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung7535ed92023-07-17 17:05:00 -07007662 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007663 AudioStreamOut* output,
7664 audio_io_handle_t id,
7665 bool systemReady,
7666 audio_config_base_t* mixerConfig) {
Andy Hung7535ed92023-07-17 17:05:00 -07007667 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hung4b17e882023-07-07 13:47:37 -07007668}
7669
Andy Hung7535ed92023-07-17 17:05:00 -07007670SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007671 AudioStreamOut* output,
7672 audio_io_handle_t id,
7673 bool systemReady,
7674 audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07007675 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007676{
7677}
7678
Andy Hung4b17e882023-07-07 13:47:37 -07007679void SpatializerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01007680 MixerThread::onFirstRef();
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007681
Andy Hung41ccf7f2022-12-14 14:25:49 -08007682 const pid_t tid = getTid();
7683 if (tid == -1) {
7684 // Unusual: PlaybackThread::onFirstRef() should set the threadLoop running.
7685 ALOGW("%s: Cannot update Spatializer mixer thread priority, not running", __func__);
7686 } else {
7687 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
7688 if (priorityBoost > 0) {
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007689 stream()->setHalThreadPriority(priorityBoost);
7690 }
7691 }
Eric Laurent68a40a82022-05-03 18:15:04 +02007692}
7693
Andy Hung4b17e882023-07-07 13:47:37 -07007694void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007695 // if mSupportedLatencyModes is empty, the HAL stream does not support
7696 // latency mode control and we can exit.
7697 if (mSupportedLatencyModes.empty()) {
7698 return;
7699 }
7700 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7701 if (mSupportedLatencyModes.size() == 1) {
7702 // If the HAL only support one latency mode currently, confirm the choice
7703 latencyMode = mSupportedLatencyModes[0];
7704 } else if (mSupportedLatencyModes.size() > 1) {
7705 // Request low latency if:
7706 // - The low latency mode is requested by the spatializer controller
7707 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7708 // AND
7709 // - At least one active track is spatialized
7710 bool hasSpatializedActiveTrack = false;
7711 for (const auto& track : mActiveTracks) {
7712 if (track->isSpatialized()) {
7713 hasSpatializedActiveTrack = true;
7714 break;
7715 }
7716 }
7717 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7718 latencyMode = AUDIO_LATENCY_MODE_LOW;
7719 }
7720 }
7721
7722 if (latencyMode != mSetLatencyMode) {
7723 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007724 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7725 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007726 if (status == NO_ERROR) {
7727 mSetLatencyMode = latencyMode;
7728 }
7729 }
7730}
7731
Andy Hung4b17e882023-07-07 13:47:37 -07007732status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007733 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7734 return BAD_VALUE;
7735 }
7736 Mutex::Autolock _l(mLock);
7737 mRequestedLatencyMode = mode;
7738 return NO_ERROR;
7739}
7740
Andy Hung4b17e882023-07-07 13:47:37 -07007741void SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007742{
7743 bool hasVirtualizer = false;
7744 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007745 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007746 {
7747 Mutex::Autolock _l(mLock);
Andy Hung116bc262023-06-20 18:56:17 -07007748 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007749 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007750 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007751 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7752 }
7753
7754 finalDownMixer = mFinalDownMixer;
7755 mFinalDownMixer.clear();
7756 }
7757
7758 if (hasVirtualizer) {
7759 if (finalDownMixer != nullptr) {
7760 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007761 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007762 }
7763 finalDownMixer.clear();
7764 } else if (!hasDownMixer) {
7765 std::vector<effect_descriptor_t> descriptors;
Andy Hung7535ed92023-07-17 17:05:00 -07007766 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007767 EFFECT_UIID_DOWNMIX, &descriptors);
7768 if (status != NO_ERROR) {
7769 return;
7770 }
7771 ALOG_ASSERT(!descriptors.empty(),
7772 "%s getDescriptors() returned no error but empty list", __func__);
7773
7774 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7775 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007776 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007777
7778 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7779 ALOGW("%s error creating downmixer %d", __func__, status);
7780 finalDownMixer.clear();
7781 } else {
7782 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007783 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007784 }
7785 }
7786
7787 {
7788 Mutex::Autolock _l(mLock);
7789 mFinalDownMixer = finalDownMixer;
7790 }
7791}
7792
Eric Laurent81784c32012-11-19 14:55:58 -08007793// ----------------------------------------------------------------------------
7794// Record
7795// ----------------------------------------------------------------------------
7796
Andy Hung7535ed92023-07-17 17:05:00 -07007797sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung0c1e11e2023-07-06 20:56:16 -07007798 AudioStreamIn* input,
7799 audio_io_handle_t id,
7800 bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -07007801 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung0c1e11e2023-07-06 20:56:16 -07007802}
7803
Andy Hung7535ed92023-07-17 17:05:00 -07007804RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007805 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007806 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007807 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007808 ) :
Andy Hung7535ed92023-07-17 17:05:00 -07007809 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007810 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007811 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007812 mActiveTracks(&this->mLocalLog),
7813 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007814 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007815 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007816 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7817 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007818 // mFastCapture below
7819 , mFastCaptureFutex(0)
7820 // mInputSource
7821 // mPipeSink
7822 // mPipeSource
7823 , mPipeFramesP2(0)
7824 // mPipeMemory
7825 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007826 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007827 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007828{
Glenn Kastend7dca052015-03-05 16:05:54 -08007829 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung7535ed92023-07-17 17:05:00 -07007830 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007831
George Burgess IVa8f90c12020-05-14 11:27:19 -07007832 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007833 mIsMsdDevice = strcmp(
7834 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7835 }
7836
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007837 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007838
Andy Hungc8fddf32018-08-08 18:32:37 -07007839 // TODO: We may also match on address as well as device type for
7840 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007841 // TODO: This property should be ensure that only contains one single device type.
7842 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7843 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007844 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7845 : AUDIO_DEVICE_NONE));
7846
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007847 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007848 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007849 size_t numCounterOffers = 0;
7850 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007851#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007852 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007853#else
7854 (void)
7855#endif
7856 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007857 ALOG_ASSERT(index == 0);
7858
7859 // initialize fast capture depending on configuration
7860 bool initFastCapture;
7861 switch (kUseFastCapture) {
7862 case FastCapture_Never:
7863 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007864 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007865 break;
7866 case FastCapture_Always:
7867 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007868 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007869 break;
7870 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007871 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
7872 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7873 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d "
7874 "mIsMsdDevice = %d", this, (long long)mFrameCount, mSampleRate,
7875 kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007876 break;
7877 // case FastCapture_Dynamic:
7878 }
7879
7880 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007881 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007882 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007883 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7884 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007885 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007886 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007887 const sp<MemoryDealer> roHeap(readOnlyHeap());
7888 sp<IMemory> pipeMemory;
7889 if ((roHeap == 0) ||
7890 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007891 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007892 ALOGE("not enough memory for pipe buffer size=%zu; "
7893 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7894 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7895 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007896 goto failed;
7897 }
7898 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7899 memset(pipeBuffer, 0, pipeSize);
7900 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07007901 const NBAIO_Format offersFast[1] = {format};
7902 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007903 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07007904 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007905 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007906 mPipeSink = pipe;
7907 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07007908 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007909 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07007910 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007911 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007912 mPipeSource = pipeReader;
7913 mPipeFramesP2 = pipeFramesP2;
7914 mPipeMemory = pipeMemory;
7915
7916 // create fast capture
7917 mFastCapture = new FastCapture();
7918 FastCaptureStateQueue *sq = mFastCapture->sq();
7919#ifdef STATE_QUEUE_DUMP
7920 // FIXME
7921#endif
7922 FastCaptureState *state = sq->begin();
7923 state->mCblk = NULL;
7924 state->mInputSource = mInputSource.get();
7925 state->mInputSourceGen++;
7926 state->mPipeSink = pipe;
7927 state->mPipeSinkGen++;
7928 state->mFrameCount = mFrameCount;
7929 state->mCommand = FastCaptureState::COLD_IDLE;
7930 // already done in constructor initialization list
7931 //mFastCaptureFutex = 0;
7932 state->mColdFutexAddr = &mFastCaptureFutex;
7933 state->mColdGen++;
7934 state->mDumpState = &mFastCaptureDumpState;
7935#ifdef TEE_SINK
7936 // FIXME
7937#endif
Andy Hung7535ed92023-07-17 17:05:00 -07007938 mFastCaptureNBLogWriter =
7939 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007940 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7941 sq->end();
7942 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7943
7944 // start the fast capture
7945 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7946 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007947 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007948 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007949#ifdef AUDIO_WATCHDOG
7950 // FIXME
7951#endif
7952
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007953 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007954 }
Andy Hung8946a282018-04-19 20:04:56 -07007955#ifdef TEE_SINK
7956 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7957 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7958#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007959failed: ;
7960
7961 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007962}
7963
Andy Hung4b17e882023-07-07 13:47:37 -07007964RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007965{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007966 if (mFastCapture != 0) {
7967 FastCaptureStateQueue *sq = mFastCapture->sq();
7968 FastCaptureState *state = sq->begin();
7969 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7970 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7971 if (old == -1) {
7972 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7973 }
7974 }
7975 state->mCommand = FastCaptureState::EXIT;
7976 sq->end();
7977 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7978 mFastCapture->join();
7979 mFastCapture.clear();
7980 }
Andy Hung7535ed92023-07-17 17:05:00 -07007981 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
7982 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007983 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007984}
7985
Andy Hung4b17e882023-07-07 13:47:37 -07007986void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08007987{
Glenn Kastend7dca052015-03-05 16:05:54 -08007988 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007989}
7990
Andy Hung4b17e882023-07-07 13:47:37 -07007991void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08007992{
7993 ALOGV(" preExit()");
7994 Mutex::Autolock _l(mLock);
7995 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07007996 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08007997 track->invalidate();
7998 }
7999 mActiveTracks.clear();
8000 mStartStopCond.broadcast();
8001}
8002
Andy Hung4b17e882023-07-07 13:47:37 -07008003bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008004{
Eric Laurent81784c32012-11-19 14:55:58 -08008005 nsecs_t lastWarning = 0;
8006
8007 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008008
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008009reacquire_wakelock:
Andy Hung11e74242023-06-26 19:20:57 -07008010 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008011 {
8012 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07008013 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008014 }
8015
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008016 // used to request a deferred sleep, to be executed later while mutex is unlocked
8017 uint32_t sleepUs = 0;
8018
Andy Hung446f4df2019-02-21 12:26:41 -08008019 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8020
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008021 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008022 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung116bc262023-06-20 18:56:17 -07008023 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008024
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008025 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung11e74242023-06-26 19:20:57 -07008026 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008027
Glenn Kasten735f45f2014-08-18 15:51:59 -07008028 // reference to the (first and only) active fast track
Andy Hung11e74242023-06-26 19:20:57 -07008029 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008030
Glenn Kasten735f45f2014-08-18 15:51:59 -07008031 // reference to a fast track which is about to be removed
Andy Hung11e74242023-06-26 19:20:57 -07008032 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008033
Eric Laurent33403f02020-05-29 18:35:06 -07008034 bool silenceFastCapture = false;
8035
Eric Laurent81784c32012-11-19 14:55:58 -08008036 { // scope for mLock
8037 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08008038
Eric Laurent021cf962014-05-13 10:18:14 -07008039 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008040
Eric Laurent000a4192014-01-29 15:17:32 -08008041 // check exitPending here because checkForNewParameters_l() and
8042 // checkForNewParameters_l() can temporarily release mLock
8043 if (exitPending()) {
8044 break;
8045 }
8046
Eric Laurent5c25d562016-07-13 17:17:45 -07008047 // sleep with mutex unlocked
8048 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008049 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07008050 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
8051 ATRACE_END();
8052 sleepUs = 0;
8053 continue;
8054 }
8055
Glenn Kasten2b806402013-11-20 16:37:38 -08008056 // if no active track(s), then standby and release wakelock
8057 size_t size = mActiveTracks.size();
8058 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008059 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008060 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008061 releaseWakeLock_l();
8062 ALOGV("RecordThread: loop stopping");
8063 // go to sleep
8064 mWaitWorkCV.wait(mLock);
8065 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008066 goto reacquire_wakelock;
8067 }
8068
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008069 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008070 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008071 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008072
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008073 activeTrack = mActiveTracks[i];
8074 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008075 if (activeTrack->isFastTrack()) {
8076 ALOG_ASSERT(fastTrackToRemove == 0);
8077 fastTrackToRemove = activeTrack;
8078 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008079 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008080 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008081 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008082 continue;
8083 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008084
Andy Hung11e74242023-06-26 19:20:57 -07008085 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008086 switch (activeTrackState) {
8087
Andy Hung11e74242023-06-26 19:20:57 -07008088 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008089 mActiveTracks.remove(activeTrack);
Andy Hung11e74242023-06-26 19:20:57 -07008090 activeTrack->setState(IAfTrackBase::PAUSED);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008091 doBroadcast = true;
8092 size--;
8093 continue;
8094
Andy Hung11e74242023-06-26 19:20:57 -07008095 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008096 sleepUs = 10000;
8097 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008098 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008099 continue;
8100
Andy Hung11e74242023-06-26 19:20:57 -07008101 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008102 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008103 if (mStandby) {
8104 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008105 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008106 mStandby = false;
8107 }
Andy Hung11e74242023-06-26 19:20:57 -07008108 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008109 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008110 break;
8111
Andy Hung11e74242023-06-26 19:20:57 -07008112 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008113 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008114 break;
8115
Andy Hung11e74242023-06-26 19:20:57 -07008116 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8117 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8118 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008119 default:
Andy Hungce685402018-10-05 17:23:27 -07008120 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8121 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008122 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008123
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008124 if (activeTrack->isFastTrack()) {
8125 ALOG_ASSERT(!mFastTrackAvail);
8126 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008127 // if the active fast track is silenced either:
8128 // 1) silence the whole capture from fast capture buffer if this is
8129 // the only active track
8130 // 2) invalidate this track: this will cause the client to reconnect and possibly
8131 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008132 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008133 if (activeTrack->isSilenced()) {
8134 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008135 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008136 } else {
8137 silenceFastCapture = true;
8138 }
8139 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008140 // Invalidate fast tracks if access to audio history is required as this is not
8141 // possible with fast tracks. Once the fast track has been invalidated, no new
8142 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8143 if (mMaxSharedAudioHistoryMs != 0) {
8144 invalidate = true;
8145 }
8146 if (invalidate) {
8147 activeTrack->invalidate();
8148 ALOG_ASSERT(fastTrackToRemove == 0);
8149 fastTrackToRemove = activeTrack;
8150 removeTrack_l(activeTrack);
8151 mActiveTracks.remove(activeTrack);
8152 size--;
8153 continue;
8154 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008155 fastTrack = activeTrack;
8156 }
Eric Laurent33403f02020-05-29 18:35:06 -07008157
8158 activeTracks.add(activeTrack);
8159 i++;
8160
Glenn Kasten9e982352013-08-14 14:39:50 -07008161 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008162
Andy Hungdae27702016-10-31 14:01:16 -07008163 mActiveTracks.updatePowerState(this);
8164
Kevin Rocard069c2712018-03-29 19:09:14 -07008165 updateMetadata_l();
8166
Eric Laurent5c25d562016-07-13 17:17:45 -07008167 if (allStopped) {
8168 standbyIfNotAlreadyInStandby();
8169 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008170 if (doBroadcast) {
8171 mStartStopCond.broadcast();
8172 }
8173
8174 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008175 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008176 if (sleepUs == 0) {
8177 sleepUs = kRecordThreadSleepUs;
8178 }
8179 continue;
8180 }
8181 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008182
Eric Laurent81784c32012-11-19 14:55:58 -08008183 lockEffectChains_l(effectChains);
8184 }
8185
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008186 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008187
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008188 size_t size = effectChains.size();
8189 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008190 // thread mutex is not locked, but effect chain is locked
8191 effectChains[i]->process_l();
8192 }
8193
Glenn Kasten735f45f2014-08-18 15:51:59 -07008194 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008195 if (mFastCapture != 0) {
8196 FastCaptureStateQueue *sq = mFastCapture->sq();
8197 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008198 bool didModify = false;
8199 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008200 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8201 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8202 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8203 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8204 if (old == -1) {
8205 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8206 }
8207 }
8208 state->mCommand = FastCaptureState::READ_WRITE;
8209#if 0 // FIXME
Andy Hung7535ed92023-07-17 17:05:00 -07008210 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008211 FastThreadDumpState::kSamplingNforLowRamDevice :
8212 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008213#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008214 didModify = true;
8215 }
8216 audio_track_cblk_t *cblkOld = state->mCblk;
8217 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8218 if (cblkNew != cblkOld) {
8219 state->mCblk = cblkNew;
8220 // block until acked if removing a fast track
8221 if (cblkOld != NULL) {
8222 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8223 }
8224 didModify = true;
8225 }
jiabin01c8f562018-07-19 17:47:28 -07008226 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8227 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8228 if (state->mFastPatchRecordBufferProvider != abp) {
8229 state->mFastPatchRecordBufferProvider = abp;
8230 state->mFastPatchRecordFormat = fastTrack == 0 ?
8231 AUDIO_FORMAT_INVALID : fastTrack->format();
8232 didModify = true;
8233 }
Eric Laurent33403f02020-05-29 18:35:06 -07008234 if (state->mSilenceCapture != silenceFastCapture) {
8235 state->mSilenceCapture = silenceFastCapture;
8236 didModify = true;
8237 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008238 sq->end(didModify);
8239 if (didModify) {
8240 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008241#if 0
8242 if (kUseFastCapture == FastCapture_Dynamic) {
8243 mNormalSource = mPipeSource;
8244 }
8245#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008246 }
8247 }
8248
Glenn Kasten735f45f2014-08-18 15:51:59 -07008249 // now run the fast track destructor with thread mutex unlocked
8250 fastTrackToRemove.clear();
8251
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008252 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8253 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8254 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8255 // If destination is non-contiguous, first read past the nominal end of buffer, then
8256 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008257
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008258 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008259 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008260 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008261
8262 // If an NBAIO source is present, use it to read the normal capture's data
8263 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008264 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008265
8266 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8267 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8268 // we immediately retry the read() to get data and prevent another overflow.
8269 for (int retries = 0; retries <= 2; ++retries) {
8270 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8271 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8272 framesToRead);
8273 if (framesRead != OVERRUN) break;
8274 }
8275
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008276 const ssize_t availableToRead = mPipeSource->availableToRead();
8277 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008278 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008279 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008280 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8281 "more frames to read than fifo size, %zd > %zu",
8282 availableToRead, mPipeFramesP2);
8283 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8284 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8285 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8286 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008287 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8288 }
8289 if (framesRead < 0) {
8290 status_t status = (status_t) framesRead;
8291 switch (status) {
8292 case OVERRUN:
8293 ALOGW("overrun on read from pipe");
8294 framesRead = 0;
8295 break;
8296 case NEGOTIATE:
8297 ALOGE("re-negotiation is needed");
8298 framesRead = -1; // Will cause an attempt to recover.
8299 break;
8300 default:
8301 ALOGE("unknown error %d on read from pipe", status);
8302 break;
8303 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008304 }
8305 // otherwise use the HAL / AudioStreamIn directly
8306 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008307 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008308 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008309 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008310 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008311 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008312 if (result < 0) {
8313 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008314 } else {
8315 framesRead = bytesRead / mFrameSize;
8316 }
8317 }
8318
Andy Hung446f4df2019-02-21 12:26:41 -08008319 const int64_t lastIoEndNs = systemTime(); // end IO timing
8320
Andy Hung3f0c9022016-01-15 17:49:46 -08008321 // Update server timestamp with server stats
8322 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008323 if (framesRead >= 0) {
8324 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8325 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8326 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008327
8328 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008329 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008330 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008331 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008332 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8333 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8334 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008335 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008336 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8337
8338 mTimestampVerifier.add(position, time, mSampleRate);
8339
8340 // Correct timestamps
8341 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008342 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008343 id(), (long long)time, (long long)position);
8344 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8345 position = correctedTimestamp.mFrames;
8346 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008347 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008348 id(), (long long)time, (long long)position);
8349 }
8350
Andy Hung3f0c9022016-01-15 17:49:46 -08008351 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8352 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8353 // Note: In general record buffers should tend to be empty in
8354 // a properly running pipeline.
8355 //
8356 // Also, it is not advantageous to call get_presentation_position during the read
8357 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008358 } else {
8359 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008360 }
8361 }
Andy Hunge6c37112019-02-26 17:38:10 -08008362
8363 // From the timestamp, input read latency is negative output write latency.
8364 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung11e74242023-06-26 19:20:57 -07008365 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008366 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8367 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8368 mLatencyMs.add(latencyMs);
8369 }
8370
Andy Hung3f0c9022016-01-15 17:49:46 -08008371 // Use this to track timestamp information
8372 // ALOGD("%s", mTimestamp.toString().c_str());
8373
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008374 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008375 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008376 // Force input into standby so that it tries to recover at next read attempt
8377 inputStandBy();
8378 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008379 }
8380 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008381 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008382 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008383 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008384 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008385
Andy Hung8946a282018-04-19 20:04:56 -07008386#ifdef TEE_SINK
8387 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8388#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008389 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008390 {
8391 size_t part1 = mRsmpInFramesP2 - rear;
8392 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008393 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008394 (framesRead - part1) * mFrameSize);
8395 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008396 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008397 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008398
8399 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008400
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008401 // loop over each active track
8402 for (size_t i = 0; i < size; i++) {
8403 activeTrack = activeTracks[i];
8404
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008405 // skip fast tracks, as those are handled directly by FastCapture
8406 if (activeTrack->isFastTrack()) {
8407 continue;
8408 }
8409
Andy Hung73c02e42015-03-29 01:13:58 -07008410 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008411 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8412
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008413 enum {
8414 OVERRUN_UNKNOWN,
8415 OVERRUN_TRUE,
8416 OVERRUN_FALSE
8417 } overrun = OVERRUN_UNKNOWN;
8418
8419 // loop over getNextBuffer to handle circular sink
8420 for (;;) {
8421
Andy Hung11e74242023-06-26 19:20:57 -07008422 activeTrack->sinkBuffer().frameCount = ~0;
8423 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8424 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008425 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8426
Andy Hung73c02e42015-03-29 01:13:58 -07008427 // check available frames and handle overrun conditions
8428 // if the record track isn't draining fast enough.
8429 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008430 size_t framesIn;
Andy Hung11e74242023-06-26 19:20:57 -07008431 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008432 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008433 overrun = OVERRUN_TRUE;
8434 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008435 if (framesOut == 0 || framesIn == 0) {
8436 break;
8437 }
8438
Andy Hung6770c6f2015-04-07 13:43:36 -07008439 // Don't allow framesOut to be larger than what is possible with resampling
8440 // from framesIn.
8441 // This isn't strictly necessary but helps limit buffer resizing in
8442 // RecordBufferConverter. TODO: remove when no longer needed.
8443 framesOut = min(framesOut,
8444 destinationFramesPossible(
Andy Hung11e74242023-06-26 19:20:57 -07008445 framesIn, mSampleRate, activeTrack->sampleRate()));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008446
8447 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008448 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008449 // straight from RecordThread buffer to RecordTrack buffer.
8450 AudioBufferProvider::Buffer buffer;
8451 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008452 const status_t getNextBufferStatus =
Andy Hung11e74242023-06-26 19:20:57 -07008453 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008454 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008455 ALOGV_IF(buffer.frameCount != framesOut,
8456 "%s() read less than expected (%zu vs %zu)",
8457 __func__, buffer.frameCount, framesOut);
8458 framesOut = buffer.frameCount;
Andy Hung11e74242023-06-26 19:20:57 -07008459 memcpy(activeTrack->sinkBuffer().raw,
8460 buffer.raw, buffer.frameCount * mFrameSize);
8461 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008462 } else {
8463 framesOut = 0;
8464 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008465 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008466 }
8467 } else {
8468 // process frames from the RecordThread buffer provider to the RecordTrack
8469 // buffer
Andy Hung11e74242023-06-26 19:20:57 -07008470 framesOut = activeTrack->recordBufferConverter()->convert(
8471 activeTrack->sinkBuffer().raw,
8472 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008473 framesOut);
8474 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008475
8476 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8477 overrun = OVERRUN_FALSE;
8478 }
8479
Andy Hung93bb5732023-05-04 21:16:34 -07008480 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8481 const ssize_t framesToDrop =
Andy Hung11e74242023-06-26 19:20:57 -07008482 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008483 if (framesToDrop == 0) {
8484 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008485 if (framesOut > 0) {
Andy Hung11e74242023-06-26 19:20:57 -07008486 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008487 // Sanitize before releasing if the track has no access to the source data
8488 // An idle UID receives silence from non virtual devices until active
8489 if (activeTrack->isSilenced()) {
Andy Hung11e74242023-06-26 19:20:57 -07008490 memset(activeTrack->sinkBuffer().raw,
8491 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008492 }
Andy Hung11e74242023-06-26 19:20:57 -07008493 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008494 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008495 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008496 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008497 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008498 }
8499 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008500
8501 switch (overrun) {
8502 case OVERRUN_TRUE:
8503 // client isn't retrieving buffers fast enough
8504 if (!activeTrack->setOverflow()) {
8505 nsecs_t now = systemTime();
8506 // FIXME should lastWarning per track?
8507 if ((now - lastWarning) > kWarningThrottleNs) {
8508 ALOGW("RecordThread: buffer overflow");
8509 lastWarning = now;
8510 }
8511 }
8512 break;
8513 case OVERRUN_FALSE:
8514 activeTrack->clearOverflow();
8515 break;
8516 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008517 break;
8518 }
8519
Andy Hung3f0c9022016-01-15 17:49:46 -08008520 // update frame information and push timestamp out
8521 activeTrack->updateTrackFrameInfo(
Andy Hung11e74242023-06-26 19:20:57 -07008522 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008523 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8524 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008525 }
8526
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008527unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008528 // enable changes in effect chain
8529 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008530 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008531 if (audio_has_proportional_frames(mFormat)
8532 && loopCount == lastLoopCountRead + 1) {
8533 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8534 const double jitterMs =
8535 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8536 {framesRead, readPeriodNs},
8537 {0, 0} /* lastTimestamp */, mSampleRate);
8538 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8539
8540 Mutex::Autolock _l(mLock);
8541 mIoJitterMs.add(jitterMs);
8542 mProcessTimeMs.add(processMs);
8543 }
8544 // update timing info.
8545 mLastIoBeginNs = lastIoBeginNs;
8546 mLastIoEndNs = lastIoEndNs;
8547 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008548 }
8549
Glenn Kasten93e471f2013-08-19 08:40:07 -07008550 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008551
8552 {
8553 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008554 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07008555 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008556 track->invalidate();
8557 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008558 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008559 mStartStopCond.broadcast();
8560 }
8561
8562 releaseWakeLock();
8563
8564 ALOGV("RecordThread %p exiting", this);
8565 return false;
8566}
8567
Andy Hung4b17e882023-07-07 13:47:37 -07008568void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008569{
8570 if (!mStandby) {
8571 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008572 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008573 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008574 mStandby = true;
8575 }
8576}
8577
Andy Hung4b17e882023-07-07 13:47:37 -07008578void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008579{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008580 // Idle the fast capture if it's currently running
8581 if (mFastCapture != 0) {
8582 FastCaptureStateQueue *sq = mFastCapture->sq();
8583 FastCaptureState *state = sq->begin();
8584 if (!(state->mCommand & FastCaptureState::IDLE)) {
8585 state->mCommand = FastCaptureState::COLD_IDLE;
8586 state->mColdFutexAddr = &mFastCaptureFutex;
8587 state->mColdGen++;
8588 mFastCaptureFutex = 0;
8589 sq->end();
8590 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8591 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8592#if 0
8593 if (kUseFastCapture == FastCapture_Dynamic) {
8594 // FIXME
8595 }
8596#endif
8597#ifdef AUDIO_WATCHDOG
8598 // FIXME
8599#endif
8600 } else {
8601 sq->end(false /*didModify*/);
8602 }
8603 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008604 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008605 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008606
8607 // If going into standby, flush the pipe source.
8608 if (mPipeSource.get() != nullptr) {
8609 const ssize_t flushed = mPipeSource->flush();
8610 if (flushed > 0) {
8611 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8612 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8613 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8614 }
8615 }
Eric Laurent81784c32012-11-19 14:55:58 -08008616}
8617
Glenn Kasten05997e22014-03-13 15:08:33 -07008618// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07008619sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008620 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008621 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008622 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008623 audio_format_t format,
8624 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008625 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008626 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008627 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008628 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008629 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008630 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008631 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008632 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008633 audio_port_handle_t portId,
8634 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008635{
Glenn Kasten74935e42013-12-19 08:56:45 -08008636 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008637 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung11e74242023-06-26 19:20:57 -07008638 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008639 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008640 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008641 audio_input_flags_t requestedFlags = *flags;
8642 uint32_t sampleRate;
8643
8644 lStatus = initCheck();
8645 if (lStatus != NO_ERROR) {
8646 ALOGE("createRecordTrack_l() audio driver not initialized");
8647 goto Exit;
8648 }
8649
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008650 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8651 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8652 lStatus = BAD_VALUE;
8653 goto Exit;
8654 }
8655
Eric Laurentec376dc2021-04-08 20:41:22 +02008656 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008657 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008658 lStatus = PERMISSION_DENIED;
8659 goto Exit;
8660 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008661 if (maxSharedAudioHistoryMs < 0
8662 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8663 lStatus = BAD_VALUE;
8664 goto Exit;
8665 }
8666 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008667 if (*pSampleRate == 0) {
8668 *pSampleRate = mSampleRate;
8669 }
8670 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008671
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008672 // special case for FAST flag considered OK if fast capture is present and access to
8673 // audio history is not required
8674 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008675 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8676 }
8677
Eric Laurentf14db3c2017-12-08 14:20:36 -08008678 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008679 if ((*flags & inputFlags) != *flags) {
8680 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8681 " input flags (%08x)",
8682 *flags, inputFlags);
8683 *flags = (audio_input_flags_t)(*flags & inputFlags);
8684 }
Eric Laurent81784c32012-11-19 14:55:58 -08008685
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008686 // client expresses a preference for FAST and no access to audio history,
8687 // but we get the final say
8688 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008689 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008690 // we formerly checked for a callback handler (non-0 tid),
8691 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008692 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008693 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008694 // Frame count is not specified (0), or is less than or equal the pipe depth.
8695 // It is OK to provide a higher capacity than requested.
8696 // We will force it to mPipeFramesP2 below.
8697 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008698 // PCM data
8699 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008700 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008701 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008702 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008703 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008704 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008705 hasFastCapture() &&
8706 // there are sufficient fast track slots available
8707 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008708 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008709 // check compatibility with audio effects.
8710 Mutex::Autolock _l(mLock);
8711 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008712 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008713 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008714 audio_input_flags_t old = *flags;
8715 chain->checkInputFlagCompatibility(flags);
8716 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008717 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8718 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008719 }
8720 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008721 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008722 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8723 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008724 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008725 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8726 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008727 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008728 this, frameCount, mFrameCount, mPipeFramesP2,
8729 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008730 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008731 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008732 }
8733 }
8734
Eric Laurentf14db3c2017-12-08 14:20:36 -08008735 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8736 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8737 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8738 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8739 lStatus = BAD_TYPE;
8740 goto Exit;
8741 }
8742
Glenn Kasten74105912014-07-03 12:28:53 -07008743 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008744 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008745 // fast track: frame count is exactly the pipe depth
8746 frameCount = mPipeFramesP2;
8747 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008748 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008749 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008750 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8751 // or 20 ms if there is a fast capture
8752 // TODO This could be a roundupRatio inline, and const
8753 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8754 * sampleRate + mSampleRate - 1) / mSampleRate;
8755 // minimum number of notification periods is at least kMinNotifications,
8756 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8757 static const size_t kMinNotifications = 3;
8758 static const uint32_t kMinMs = 30;
8759 // TODO This could be a roundupRatio inline
8760 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8761 // TODO This could be a roundupRatio inline
8762 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8763 maxNotificationFrames;
8764 const size_t minFrameCount = maxNotificationFrames *
8765 max(kMinNotifications, minNotificationsByMs);
8766 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008767 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8768 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008769 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008770 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008771 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008772 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008773
8774 { // scope for mLock
8775 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008776 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008777 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008778 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008779 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008780 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008781 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008782 }
Eric Laurent81784c32012-11-19 14:55:58 -08008783
Andy Hung11e74242023-06-26 19:20:57 -07008784 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008785 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008786 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung11e74242023-06-26 19:20:57 -07008787 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008788 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008789
Glenn Kasten03003332013-08-06 15:40:54 -07008790 lStatus = track->initCheck();
8791 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008792 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008793 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008794 goto Exit;
8795 }
8796 mTracks.add(track);
8797
Eric Laurent05067782016-06-01 18:27:28 -07008798 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008799 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8800 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8801 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008802 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008803 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008804
8805 if (maxSharedAudioHistoryMs != 0) {
8806 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8807 }
Eric Laurent81784c32012-11-19 14:55:58 -08008808 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008809
Eric Laurent81784c32012-11-19 14:55:58 -08008810 lStatus = NO_ERROR;
8811
8812Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008813 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008814 return track;
8815}
8816
Andy Hung4b17e882023-07-07 13:47:37 -07008817status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08008818 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008819 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008820{
8821 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8822 sp<ThreadBase> strongMe = this;
8823 status_t status = NO_ERROR;
8824
8825 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008826 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008827 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung11e74242023-06-26 19:20:57 -07008828 recordTrack->synchronizedRecordState().startRecording(
Andy Hung7535ed92023-07-17 17:05:00 -07008829 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07008830 event, triggerSession,
8831 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08008832 }
8833
8834 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008835 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008836 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008837 if (recordTrack->isInvalid()) {
8838 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008839 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8840 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008841 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008842 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung11e74242023-06-26 19:20:57 -07008843 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008844 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8845 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008846 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung11e74242023-06-26 19:20:57 -07008847 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008848 } else {
Andy Hung11e74242023-06-26 19:20:57 -07008849 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008850 }
8851 return status;
8852 }
8853
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008854 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8855 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8856 // or using a separate command thread
Andy Hung11e74242023-06-26 19:20:57 -07008857 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08008858 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008859 if (recordTrack->isExternalTrack()) {
8860 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008861 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008862 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008863 if (recordTrack->isInvalid()) {
8864 recordTrack->clearSyncStartEvent();
Andy Hung11e74242023-06-26 19:20:57 -07008865 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
8866 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07008867 // STARTING_2 forces destroy to call stopInput.
8868 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008869 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8870 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008871 }
Andy Hung11e74242023-06-26 19:20:57 -07008872 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07008873 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung11e74242023-06-26 19:20:57 -07008874 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07008875 // Someone else has changed state, let them take over,
8876 // leave mState in the new state.
8877 recordTrack->clearSyncStartEvent();
8878 return INVALID_OPERATION;
8879 }
8880 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008881 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008882 ALOGW("%s(%d): startInput failed, status %d",
8883 __func__, recordTrack->id(), status);
8884 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8885 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008886 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008887 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008888 return status;
8889 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008890 sendIoConfigEvent_l(
8891 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008892 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008893
8894 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8895
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008896 // Catch up with current buffer indices if thread is already running.
8897 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8898 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8899 // see previously buffered data before it called start(), but with greater risk of overrun.
8900
Andy Hung11e74242023-06-26 19:20:57 -07008901 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008902 if (!recordTrack->isDirect()) {
8903 // clear any converter state as new data will be discontinuous
Andy Hung11e74242023-06-26 19:20:57 -07008904 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008905 }
Andy Hung11e74242023-06-26 19:20:57 -07008906 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08008907 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008908 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008909 return status;
8910 }
Eric Laurent81784c32012-11-19 14:55:58 -08008911}
8912
Andy Hung4b17e882023-07-07 13:47:37 -07008913void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08008914{
Andy Hung4b17e882023-07-07 13:47:37 -07008915 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08008916
8917 if (strongEvent != 0) {
Andy Hungfafbebc2023-06-23 19:27:19 -07008918 sp<IAfTrackBase> ptr =
8919 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
8920 if (ptr != nullptr) {
Andy Hungeb6b5f82023-07-14 11:00:08 -07008921 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungfafbebc2023-06-23 19:27:19 -07008922 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08008923 }
Eric Laurent81784c32012-11-19 14:55:58 -08008924 }
8925}
8926
Andy Hung4b17e882023-07-07 13:47:37 -07008927bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008928 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008929 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008930 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung11e74242023-06-26 19:20:57 -07008931 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008932 return false;
8933 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008934 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung11e74242023-06-26 19:20:57 -07008935 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07008936
Andy Hungabfab202019-03-07 19:45:54 -08008937 // NOTE: Waiting here is important to keep stop synchronous.
8938 // This is needed for proper patchRecord peer release.
Andy Hung11e74242023-06-26 19:20:57 -07008939 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungce685402018-10-05 17:23:27 -07008940 mWaitWorkCV.broadcast(); // signal thread to stop
8941 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008942 }
Andy Hungce685402018-10-05 17:23:27 -07008943
Andy Hung11e74242023-06-26 19:20:57 -07008944 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008945 ALOGV("Record stopped OK");
8946 return true;
8947 }
Andy Hungce685402018-10-05 17:23:27 -07008948
8949 // don't handle anything - we've been invalidated or restarted and in a different state
8950 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung11e74242023-06-26 19:20:57 -07008951 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008952 return false;
8953}
8954
Andy Hung4b17e882023-07-07 13:47:37 -07008955bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08008956{
8957 return false;
8958}
8959
Andy Hung4b17e882023-07-07 13:47:37 -07008960status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08008961{
8962#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8963 if (!isValidSyncEvent(event)) {
8964 return BAD_VALUE;
8965 }
8966
Glenn Kastend848eb42016-03-08 13:42:11 -08008967 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008968 status_t ret = NAME_NOT_FOUND;
8969
8970 Mutex::Autolock _l(mLock);
8971
8972 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07008973 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08008974 if (eventSession == track->sessionId()) {
8975 (void) track->setSyncEvent(event);
8976 ret = NO_ERROR;
8977 }
8978 }
8979 return ret;
8980#else
8981 return BAD_VALUE;
8982#endif
8983}
8984
Andy Hung4b17e882023-07-07 13:47:37 -07008985status_t RecordThread::getActiveMicrophones(
Andy Hung0c1e11e2023-07-06 20:56:16 -07008986 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08008987{
8988 ALOGV("RecordThread::getActiveMicrophones");
8989 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008990 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008991 return NO_INIT;
8992 }
jiabin9ff780e2018-03-19 18:19:52 -07008993 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8994 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008995}
8996
Andy Hung4b17e882023-07-07 13:47:37 -07008997status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06008998 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008999{
Paul McLean12340082019-03-19 09:35:05 -06009000 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009001 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009002 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009003 return NO_INIT;
9004 }
Paul McLean12340082019-03-19 09:35:05 -06009005 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009006}
9007
Andy Hung4b17e882023-07-07 13:47:37 -07009008status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009009{
Paul McLean12340082019-03-19 09:35:05 -06009010 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009011 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009012 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009013 return NO_INIT;
9014 }
Paul McLean12340082019-03-19 09:35:05 -06009015 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009016}
9017
Andy Hung4b17e882023-07-07 13:47:37 -07009018status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009019 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9020 int64_t sharedAudioStartMs) {
9021 AutoMutex _l(mLock);
9022 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9023}
9024
Andy Hung4b17e882023-07-07 13:47:37 -07009025status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009026 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9027 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009028
Eric Laurentec376dc2021-04-08 20:41:22 +02009029 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9030 return BAD_VALUE;
9031 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009032
9033 if (sharedAudioStartMs < 0
9034 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009035 return BAD_VALUE;
9036 }
9037
Eric Laurent2407ce32021-04-26 14:56:03 +02009038 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9039 // As we cannot detect more than one wraparound, only accept values up current write position
9040 // after one wraparound
9041 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9042 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009043 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009044 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9045 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009046 // Bring the start frame position within the input buffer to match the documented
9047 // "best effort" behavior of the API.
9048 if (sharedOffset < 0) {
9049 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009050 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009051 sharedAudioStartFrames =
9052 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009053 }
9054
Eric Laurentec376dc2021-04-08 20:41:22 +02009055 mSharedAudioPackageName = sharedAudioPackageName;
9056 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009057 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009058 } else {
9059 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009060 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009061 }
9062 return NO_ERROR;
9063}
9064
Andy Hung4b17e882023-07-07 13:47:37 -07009065void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009066 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9067 mSharedAudioStartFrames = -1;
9068 mSharedAudioPackageName = "";
9069}
9070
Andy Hung4b17e882023-07-07 13:47:37 -07009071ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009072{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009073 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009074 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009075 }
9076 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009077 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung11e74242023-06-26 19:20:57 -07009078 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009079 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009080 }
9081 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009082 MetadataUpdate change;
9083 change.recordMetadataUpdate = metadata.tracks;
9084 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009085}
9086
Eric Laurent81784c32012-11-19 14:55:58 -08009087// destroyTrack_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07009088void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009089{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009090 track->terminate();
Andy Hung11e74242023-06-26 19:20:57 -07009091 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009092
Eric Laurent81784c32012-11-19 14:55:58 -08009093 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009094 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009095 removeTrack_l(track);
9096 }
9097}
9098
Andy Hung4b17e882023-07-07 13:47:37 -07009099void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009100{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009101 String8 result;
9102 track->appendDump(result, false /* active */);
9103 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
9104
Eric Laurent81784c32012-11-19 14:55:58 -08009105 mTracks.remove(track);
9106 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009107 if (track->isFastTrack()) {
9108 ALOG_ASSERT(!mFastTrackAvail);
9109 mFastTrackAvail = true;
9110 }
Eric Laurent81784c32012-11-19 14:55:58 -08009111}
9112
Andy Hung4b17e882023-07-07 13:47:37 -07009113void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009114{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009115 AudioStreamIn *input = mInput;
9116 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9117 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009118 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009119 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009120 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009121 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009122 }
Andy Hungbfa64962017-06-12 14:43:19 -07009123
9124 if (input != nullptr) {
9125 dprintf(fd, " Hal stream dump:\n");
9126 (void)input->stream->dump(fd);
9127 }
9128
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009129 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009130 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009131
Glenn Kasten2f90c512015-12-02 11:40:09 -08009132 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9133 // while we are dumping it. It may be inconsistent, but it won't mutate!
9134 // This is a large object so we place it on the heap.
9135 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009136 const std::unique_ptr<FastCaptureDumpState> copy =
9137 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009138 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009139}
9140
Andy Hung4b17e882023-07-07 13:47:37 -07009141void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009142{
Eric Laurent81784c32012-11-19 14:55:58 -08009143 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009144 size_t numtracks = mTracks.size();
9145 size_t numactive = mActiveTracks.size();
9146 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009147 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009148 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009149 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009150 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009151 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009152 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009153 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07009154 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009155 if (track != 0) {
9156 bool active = mActiveTracks.indexOf(track) >= 0;
9157 if (active) {
9158 numactiveseen++;
9159 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009160 result.append(prefix);
9161 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009162 }
Eric Laurent81784c32012-11-19 14:55:58 -08009163 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009164 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009165 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009166 }
9167
Marco Nelissenb2208842014-02-07 14:00:50 -08009168 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009169 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009170 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009171 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009172 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009173 for (size_t i = 0; i < numactive; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07009174 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009175 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009176 result.append(prefix);
9177 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009178 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009179 }
Eric Laurent81784c32012-11-19 14:55:58 -08009180
9181 }
9182 write(fd, result.string(), result.size());
9183}
9184
Andy Hung4b17e882023-07-07 13:47:37 -07009185void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009186{
9187 Mutex::Autolock _l(mLock);
9188 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009189 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009190 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009191 track->setSilenced(silenced);
9192 }
9193 }
9194}
Andy Hung73c02e42015-03-29 01:13:58 -07009195
Andy Hung11e74242023-06-26 19:20:57 -07009196void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009197{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009198 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung4b17e882023-07-07 13:47:37 -07009199 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009200 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009201 const int32_t rear = recordThread->mRsmpInRear;
9202 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009203 if (mRecordTrack->startFrames() >= 0) {
9204 int32_t startFrames = mRecordTrack->startFrames();
9205 // Accept a recent wraparound of mRsmpInRear
9206 if (startFrames <= rear) {
9207 deltaFrames = rear - startFrames;
9208 } else {
9209 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009210 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009211 // start frame cannot be further in the past than start of resampling buffer
9212 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9213 deltaFrames = recordThread->mRsmpInFrames;
9214 }
9215 }
9216 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009217}
9218
Andy Hung11e74242023-06-26 19:20:57 -07009219void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009220 size_t *framesAvailable, bool *hasOverrun)
9221{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009222 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung4b17e882023-07-07 13:47:37 -07009223 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009224 const int32_t rear = recordThread->mRsmpInRear;
9225 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009226 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009227
9228 size_t framesIn;
9229 bool overrun = false;
9230 if (filled < 0) {
9231 // should not happen, but treat like a massive overrun and re-sync
9232 framesIn = 0;
9233 mRsmpInFront = rear;
9234 overrun = true;
9235 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9236 framesIn = (size_t) filled;
9237 } else {
9238 // client is not keeping up with server, but give it latest data
9239 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009240 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9241 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009242 overrun = true;
9243 }
9244 if (framesAvailable != NULL) {
9245 *framesAvailable = framesIn;
9246 }
9247 if (hasOverrun != NULL) {
9248 *hasOverrun = overrun;
9249 }
9250}
9251
Eric Laurent81784c32012-11-19 14:55:58 -08009252// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07009253status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009254 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009255{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009256 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009257 if (threadBase == 0) {
9258 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009259 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009260 return NOT_ENOUGH_DATA;
9261 }
Andy Hung4b17e882023-07-07 13:47:37 -07009262 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009263 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009264 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009265 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009266 // FIXME should not be P2 (don't want to increase latency)
9267 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009268 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009269 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009270
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009271 front &= recordThread->mRsmpInFramesP2 - 1;
9272 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009273 if (part1 > (size_t) filled) {
9274 part1 = filled;
9275 }
9276 size_t ask = buffer->frameCount;
9277 ALOG_ASSERT(ask > 0);
9278 if (part1 > ask) {
9279 part1 = ask;
9280 }
9281 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009282 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009283 buffer->raw = NULL;
9284 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009285 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009286 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009287 }
9288
Andy Hung57446612015-04-19 23:56:46 -07009289 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009290 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009291 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009292 return NO_ERROR;
9293}
9294
9295// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07009296void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009297 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009298{
Hongwei Wang95e37682019-04-12 11:13:36 -07009299 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009300 if (stepCount == 0) {
9301 return;
9302 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009303 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009304 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009305 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009306 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009307 buffer->frameCount = 0;
9308}
9309
Andy Hung4b17e882023-07-07 13:47:37 -07009310void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009311{
9312 Mutex::Autolock _l(mLock);
9313 checkBtNrec_l();
9314}
9315
Andy Hung4b17e882023-07-07 13:47:37 -07009316void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009317{
9318 // disable AEC and NS if the device is a BT SCO headset supporting those
9319 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009320 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Andy Hung7535ed92023-07-17 17:05:00 -07009321 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009322 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9323 for (size_t i = 0; i < mEffectChains.size(); i++) {
9324 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9325 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9326 }
9327 }
9328}
9329
Andy Hung97a893e2015-03-29 01:03:07 -07009330
Andy Hung4b17e882023-07-07 13:47:37 -07009331bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009332 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009333{
9334 bool reconfig = false;
9335
Eric Laurent10351942014-05-08 18:49:52 -07009336 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009337
Eric Laurent10351942014-05-08 18:49:52 -07009338 audio_format_t reqFormat = mFormat;
9339 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009340 // 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 +08009341 [[maybe_unused]] audio_channel_mask_t channelMask =
9342 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009343
9344 AudioParameter param = AudioParameter(keyValuePair);
9345 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009346
9347 // scope for AutoPark extends to end of method
9348 AutoPark<FastCapture> park(mFastCapture);
9349
Eric Laurent10351942014-05-08 18:49:52 -07009350 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9351 // channel count change can be requested. Do we mandate the first client defines the
9352 // HAL sampling rate and channel count or do we allow changes on the fly?
9353 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9354 samplingRate = value;
9355 reconfig = true;
9356 }
9357 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009358 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009359 status = BAD_VALUE;
9360 } else {
9361 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009362 reconfig = true;
9363 }
Eric Laurent10351942014-05-08 18:49:52 -07009364 }
9365 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9366 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009367 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009368 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009369 status = BAD_VALUE;
9370 } else {
9371 channelMask = mask;
9372 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009373 }
Eric Laurent10351942014-05-08 18:49:52 -07009374 }
9375 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9376 // do not accept frame count changes if tracks are open as the track buffer
9377 // size depends on frame count and correct behavior would not be guaranteed
9378 // if frame count is changed after track creation
9379 if (mActiveTracks.size() > 0) {
9380 status = INVALID_OPERATION;
9381 } else {
9382 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009383 }
Eric Laurent10351942014-05-08 18:49:52 -07009384 }
9385 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009386 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009387 }
9388 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9389 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009390 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009391 }
Glenn Kastene198c362013-08-13 09:13:36 -07009392
Eric Laurent10351942014-05-08 18:49:52 -07009393 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009394 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009395 if (status == INVALID_OPERATION) {
9396 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009397 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009398 }
9399 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009400 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009401 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9402 if (mInput->stream->getAudioProperties(&config) == OK &&
9403 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9404 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009405 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009406 status = NO_ERROR;
9407 }
Eric Laurent81784c32012-11-19 14:55:58 -08009408 }
Eric Laurent10351942014-05-08 18:49:52 -07009409 if (status == NO_ERROR) {
9410 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009411 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009412 }
9413 }
Eric Laurent81784c32012-11-19 14:55:58 -08009414 }
Eric Laurent10351942014-05-08 18:49:52 -07009415
Eric Laurent81784c32012-11-19 14:55:58 -08009416 return reconfig;
9417}
9418
Andy Hung4b17e882023-07-07 13:47:37 -07009419String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009420{
Eric Laurent81784c32012-11-19 14:55:58 -08009421 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009422 if (initCheck() == NO_ERROR) {
9423 String8 out_s8;
9424 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9425 return out_s8;
9426 }
Eric Laurent81784c32012-11-19 14:55:58 -08009427 }
Andy Hung920f6572022-10-06 12:09:49 -07009428 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009429}
9430
Andy Hung4b17e882023-07-07 13:47:37 -07009431void RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009432 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009433 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009434 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009435 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009436 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009437 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009438 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9439 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009440 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009441 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009442 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009443 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009444 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009445 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009446 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009447 break;
9448 }
Andy Hung7535ed92023-07-17 17:05:00 -07009449 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009450}
9451
Andy Hung4b17e882023-07-07 13:47:37 -07009452void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009453{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009454 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9455 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009456 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009457 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9458 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009459 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9460 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009461 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009462 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009463 ALOGI("HAL format %#x is not linear pcm", mFormat);
9464 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009465 result = mInput->stream->getFrameSize(&mFrameSize);
9466 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009467 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9468 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009469 result = mInput->stream->getBufferSize(&mBufferSize);
9470 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009471 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009472 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9473 "mBufferSize=%zu, mFrameCount=%zu",
9474 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009475
Eric Laurentec376dc2021-04-08 20:41:22 +02009476 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9477 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009478 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009479
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009480 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9481 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009482
9483 audio_input_flags_t flags = mInput->flags;
9484 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9485 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9486 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9487 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9488 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9489 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9490 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9491 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9492 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009493}
9494
Andy Hung4b17e882023-07-07 13:47:37 -07009495uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009496{
9497 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009498 uint32_t result;
9499 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9500 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009501 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009502 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009503}
9504
Andy Hung4b17e882023-07-07 13:47:37 -07009505KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009506{
Glenn Kastend848eb42016-03-08 13:42:11 -08009507 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009508 Mutex::Autolock _l(mLock);
9509 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung11e74242023-06-26 19:20:57 -07009510 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009511 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009512 if (ids.indexOfKey(sessionId) < 0) {
9513 ids.add(sessionId, true);
9514 }
9515 }
9516 return ids;
9517}
9518
Andy Hung4b17e882023-07-07 13:47:37 -07009519AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009520{
9521 Mutex::Autolock _l(mLock);
9522 AudioStreamIn *input = mInput;
9523 mInput = NULL;
9524 return input;
9525}
9526
9527// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hung4b17e882023-07-07 13:47:37 -07009528sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009529{
9530 if (mInput == NULL) {
9531 return NULL;
9532 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009533 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009534}
9535
Andy Hung4b17e882023-07-07 13:47:37 -07009536status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009537{
Eric Laurent81784c32012-11-19 14:55:58 -08009538 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009539 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009540 chain->setInBuffer(NULL);
9541 chain->setOutBuffer(NULL);
9542
9543 checkSuspendOnAddEffectChain_l(chain);
9544
Eric Laurent1b928682014-10-02 19:41:47 -07009545 // make sure enabled pre processing effects state is communicated to the HAL as we
9546 // just moved them to a new input stream.
9547 chain->syncHalEffectsState();
9548
Eric Laurent81784c32012-11-19 14:55:58 -08009549 mEffectChains.add(chain);
9550
9551 return NO_ERROR;
9552}
9553
Andy Hung4b17e882023-07-07 13:47:37 -07009554size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009555{
9556 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009557
9558 for (size_t i = 0; i < mEffectChains.size(); i++) {
9559 if (chain == mEffectChains[i]) {
9560 mEffectChains.removeAt(i);
9561 break;
9562 }
Eric Laurent81784c32012-11-19 14:55:58 -08009563 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009564 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009565}
9566
Andy Hung4b17e882023-07-07 13:47:37 -07009567status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009568 audio_patch_handle_t *handle)
9569{
9570 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009571
9572 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009573 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009574 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009575 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009576 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009577 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009578 }
9579
Eric Laurentd8365c52017-07-16 15:27:05 -07009580 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009581
9582 // store new source and send to effects
9583 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9584 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009585 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009586 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009587 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009588 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009589
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009590 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009591 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9592 status = hwDevice->createAudioPatch(patch->num_sources,
9593 patch->sources,
9594 patch->num_sinks,
9595 patch->sinks,
9596 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009597 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009598 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9599 patch->sinks[0].ext.mix.usecase.source,
9600 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009601 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009602 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009603
jiabinc52b1ff2019-10-31 17:20:42 -07009604 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009605 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009606 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009607 }
Eric Laurent296fb132015-05-01 11:38:42 -07009608
Andy Hungc2b11cb2020-04-22 09:04:01 -07009609 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009610 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009611 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009612 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009613 // also dispatch to active AudioRecords
9614 for (const auto &track : mActiveTracks) {
9615 track->logEndInterval();
9616 track->logBeginInterval(pathSourcesAsString);
9617 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009618 // Force meteadata update after a route change
9619 mActiveTracks.setHasChanged();
9620
Eric Laurent1c333e22014-05-20 10:48:17 -07009621 return status;
9622}
9623
Andy Hung4b17e882023-07-07 13:47:37 -07009624status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009625{
9626 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009627
jiabinc52b1ff2019-10-31 17:20:42 -07009628 mPatch = audio_patch{};
9629 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009630
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009631 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009632 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9633 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009634 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009635 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009636 }
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 Hung4b17e882023-07-07 13:47:37 -07009643void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009644{
wendy lin56aa82b2020-12-02 15:19:55 +08009645 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009646 mOutDevices = outDevices;
9647 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9648 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009649 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009650 }
9651}
9652
Andy Hung4b17e882023-07-07 13:47:37 -07009653int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009654{
9655 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009656 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009657 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009658 int32_t oldestFront = mRsmpInRear;
9659 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009660 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009661 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009662 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009663 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009664 if (filled > maxFilled) {
9665 oldestFront = front;
9666 maxFilled = filled;
9667 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009668 }
Andy Hung920f6572022-10-06 12:09:49 -07009669 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009670 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9671 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009672 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009673}
9674
Andy Hung4b17e882023-07-07 13:47:37 -07009675void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009676{
9677 if (offset == 0) {
9678 return;
9679 }
9680 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009681 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009682 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung11e74242023-06-26 19:20:57 -07009683 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009684 }
9685}
9686
Andy Hung4b17e882023-07-07 13:47:37 -07009687void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009688{
9689 // This is the formula for calculating the temporary buffer size.
9690 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9691 // 1 full output buffer, regardless of the alignment of the available input.
9692 // The value is somewhat arbitrary, and could probably be even larger.
9693 // A larger value should allow more old data to be read after a track calls start(),
9694 // without increasing latency.
9695 //
9696 // Note this is independent of the maximum downsampling ratio permitted for capture.
9697 size_t minRsmpInFrames = mFrameCount * 7;
9698
9699 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9700 // capture history available to another client using the same session ID:
9701 // dimension the resampler input buffer accordingly.
9702
9703 // Get oldest client read position: getOldestFront_l() must be called before altering
9704 // mRsmpInRear, or mRsmpInFrames
9705 int32_t previousFront = getOldestFront_l();
9706 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9707 int32_t previousRear = mRsmpInRear;
9708 mRsmpInRear = 0;
9709
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009710 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hung4b17e882023-07-07 13:47:37 -07009711 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009712 "resizeInputBuffer_l() called with invalid max shared history %d",
9713 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009714 if (maxSharedAudioHistoryMs != 0) {
9715 // resizeInputBuffer_l should never be called with a non zero shared history if the
9716 // buffer was not already allocated
9717 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9718 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9719 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9720 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009721 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009722 return;
9723 }
9724 mRsmpInFrames = rsmpInFrames;
9725 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009726 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009727 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9728 // initialized
9729 if (mRsmpInFrames < minRsmpInFrames) {
9730 mRsmpInFrames = minRsmpInFrames;
9731 }
9732 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9733
9734 // TODO optimize audio capture buffer sizes ...
9735 // Here we calculate the size of the sliding buffer used as a source
9736 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9737 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9738 // be better to have it derived from the pipe depth in the long term.
9739 // The current value is higher than necessary. However it should not add to latency.
9740
9741 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9742 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9743
9744 void *rsmpInBuffer;
9745 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9746 // if posix_memalign fails, will segv here.
9747 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9748
9749 // Copy audio history if any from old buffer before freeing it
9750 if (previousRear != 0) {
9751 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9752 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9753
9754 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9755 previousFront &= previousRsmpInFramesP2 - 1;
9756 size_t part1 = previousRsmpInFramesP2 - previousFront;
9757 if (part1 > (size_t) unread) {
9758 part1 = unread;
9759 }
9760 if (part1 != 0) {
9761 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9762 part1 * mFrameSize);
9763 mRsmpInRear = part1;
9764 part1 = unread - part1;
9765 if (part1 != 0) {
9766 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9767 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9768 mRsmpInRear += part1;
9769 }
9770 }
9771 // Update front for all clients according to new rear
9772 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9773 } else {
9774 mRsmpInRear = 0;
9775 }
9776 free(mRsmpInBuffer);
9777 mRsmpInBuffer = rsmpInBuffer;
9778}
9779
Andy Hung4b17e882023-07-07 13:47:37 -07009780void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009781{
9782 Mutex::Autolock _l(mLock);
9783 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009784 if (record->getSource()) {
9785 mSource = record->getSource();
9786 }
Eric Laurent83b88082014-06-20 18:31:16 -07009787}
9788
Andy Hung4b17e882023-07-07 13:47:37 -07009789void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009790{
9791 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009792 if (mSource == record->getSource()) {
9793 mSource = mInput;
9794 }
Eric Laurent83b88082014-06-20 18:31:16 -07009795 destroyTrack_l(record);
9796}
9797
Andy Hung4b17e882023-07-07 13:47:37 -07009798void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07009799{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009800 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009801 config->role = AUDIO_PORT_ROLE_SINK;
9802 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9803 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009804 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9805 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9806 config->flags.input = mInput->flags;
9807 }
Eric Laurent83b88082014-06-20 18:31:16 -07009808}
Eric Laurent1c333e22014-05-20 10:48:17 -07009809
Eric Laurent6acd1d42017-01-04 14:23:29 -08009810// ----------------------------------------------------------------------------
9811// Mmap
9812// ----------------------------------------------------------------------------
9813
Andy Hung765de282023-07-07 15:58:48 -07009814// Mmap stream control interface implementation. Each MmapThreadHandle controls one
9815// MmapPlaybackThread or MmapCaptureThread instance.
9816class MmapThreadHandle : public MmapStreamInterface {
9817public:
9818 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
9819 ~MmapThreadHandle() override;
9820
9821 // MmapStreamInterface virtuals
9822 status_t createMmapBuffer(int32_t minSizeFrames,
9823 struct audio_mmap_buffer_info* info) final;
9824 status_t getMmapPosition(struct audio_mmap_position* position) final;
9825 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
9826 status_t start(const AudioClient& client,
9827 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
9828 status_t stop(audio_port_handle_t handle) final;
9829 status_t standby() final;
9830 status_t reportData(const void* buffer, size_t frameCount) final;
9831private:
9832 const sp<IAfMmapThread> mThread;
9833};
9834
9835/* static */
9836sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
9837 const sp<IAfMmapThread>& mmapThread) {
9838 return sp<MmapThreadHandle>::make(mmapThread);
9839}
9840
9841MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009842 : mThread(thread)
9843{
Phil Burk9fabbf82017-08-03 12:02:00 -07009844 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009845}
9846
Andy Hung765de282023-07-07 15:58:48 -07009847// MmapStreamInterface could be directly implemented by MmapThread excepting this
9848// special handling on adapter dtor.
9849MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009850{
Phil Burk9fabbf82017-08-03 12:02:00 -07009851 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009852}
9853
Andy Hung765de282023-07-07 15:58:48 -07009854status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009855 struct audio_mmap_buffer_info *info)
9856{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009857 return mThread->createMmapBuffer(minSizeFrames, info);
9858}
9859
Andy Hung765de282023-07-07 15:58:48 -07009860status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009861{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009862 return mThread->getMmapPosition(position);
9863}
9864
Andy Hung765de282023-07-07 15:58:48 -07009865status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -07009866 int64_t *timeNanos) {
9867 return mThread->getExternalPosition(position, timeNanos);
9868}
9869
Andy Hung765de282023-07-07 15:58:48 -07009870status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009871 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009872{
jiabind1f1cb62020-03-24 11:57:57 -07009873 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009874}
9875
Andy Hung765de282023-07-07 15:58:48 -07009876status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009877{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009878 return mThread->stop(handle);
9879}
9880
Andy Hung765de282023-07-07 15:58:48 -07009881status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -08009882{
Eric Laurent18b57012017-02-13 16:23:52 -08009883 return mThread->standby();
9884}
9885
Andy Hung765de282023-07-07 15:58:48 -07009886status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
9887{
jiabinfc791ee2023-02-15 19:43:40 +00009888 return mThread->reportData(buffer, frameCount);
9889}
9890
Eric Laurent6acd1d42017-01-04 14:23:29 -08009891
Andy Hung4b17e882023-07-07 13:47:37 -07009892MmapThread::MmapThread(
Andy Hung7535ed92023-07-17 17:05:00 -07009893 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -07009894 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung7535ed92023-07-17 17:05:00 -07009895 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009896 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009897 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009898 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009899 mActiveTracks(&this->mLocalLog),
9900 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9901 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009902{
Eric Laurent18b57012017-02-13 16:23:52 -08009903 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009904 readHalParameters_l();
9905}
9906
Andy Hung4b17e882023-07-07 13:47:37 -07009907void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009908{
9909 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9910}
9911
Andy Hung4b17e882023-07-07 13:47:37 -07009912void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009913{
Andy Hung11e74242023-06-26 19:20:57 -07009914 ActiveTracks<IAfMmapTrack> activeTracks;
Eric Laurent331679c2018-04-16 17:03:16 -07009915 {
9916 Mutex::Autolock _l(mLock);
Andy Hung11e74242023-06-26 19:20:57 -07009917 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -07009918 activeTracks.add(t);
9919 }
9920 }
Andy Hung11e74242023-06-26 19:20:57 -07009921 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009922 stop(t->portId());
9923 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009924 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009925 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009926 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009927 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009928 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009929 }
9930}
9931
9932
Andy Hung4b17e882023-07-07 13:47:37 -07009933void MmapThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009934 audio_stream_type_t streamType __unused,
9935 audio_session_t sessionId,
9936 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009937 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009938 audio_port_handle_t portId)
9939{
9940 mAttr = *attr;
9941 mSessionId = sessionId;
9942 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009943 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009944 mPortId = portId;
9945}
9946
Andy Hung4b17e882023-07-07 13:47:37 -07009947status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009948 struct audio_mmap_buffer_info *info)
9949{
9950 if (mHalStream == 0) {
9951 return NO_INIT;
9952 }
Eric Laurent18b57012017-02-13 16:23:52 -08009953 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009954 return mHalStream->createMmapBuffer(minSizeFrames, info);
9955}
9956
Andy Hung4b17e882023-07-07 13:47:37 -07009957status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -08009958{
9959 if (mHalStream == 0) {
9960 return NO_INIT;
9961 }
9962 return mHalStream->getMmapPosition(position);
9963}
9964
Andy Hung4b17e882023-07-07 13:47:37 -07009965status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -07009966{
Eric Laurentdda206a2022-07-08 17:28:35 +02009967 // The HAL must receive track metadata before starting the stream
9968 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -07009969 status_t ret = mHalStream->start();
9970 if (ret != NO_ERROR) {
9971 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9972 return ret;
9973 }
Andy Hungcf10d742020-04-28 15:38:24 -07009974 if (mStandby) {
9975 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009976 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07009977 mStandby = false;
9978 }
Eric Laurent331679c2018-04-16 17:03:16 -07009979 return NO_ERROR;
9980}
9981
Andy Hung4b17e882023-07-07 13:47:37 -07009982status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009983 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009984 audio_port_handle_t *handle)
9985{
Eric Laurenta54f1282017-07-01 19:39:32 -07009986 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009987 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009988 if (mHalStream == 0) {
9989 return NO_INIT;
9990 }
9991
9992 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009993
Eric Laurentdda206a2022-07-08 17:28:35 +02009994 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -07009995 if (*handle == mPortId) {
Eric Laurentdda206a2022-07-08 17:28:35 +02009996 acquireWakeLock();
9997 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -07009998 }
9999
10000 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10001
10002 audio_io_handle_t io = mId;
Andy Hungc3af0112023-07-19 16:56:19 -070010003 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010004 client.attributionSource);
10005
Eric Laurenta54f1282017-07-01 19:39:32 -070010006 if (isOutput()) {
10007 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10008 config.sample_rate = mSampleRate;
10009 config.channel_mask = mChannelMask;
10010 config.format = mFormat;
10011 audio_stream_type_t stream = streamType();
10012 audio_output_flags_t flags =
10013 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010014 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010015 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010016 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010017 bool isBitPerfect;
Eric Laurenta54f1282017-07-01 19:39:32 -070010018 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
10019 mSessionId,
10020 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010021 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010022 &config,
10023 flags,
10024 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010025 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010026 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010027 &isSpatialized,
10028 &isBitPerfect);
Kevin Rocard153f92d2018-12-18 18:33:28 -080010029 ALOGD_IF(!secondaryOutputs.empty(),
10030 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010031 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010032 audio_config_base_t config;
10033 config.sample_rate = mSampleRate;
10034 config.channel_mask = mChannelMask;
10035 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010036 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -070010037 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010038 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -070010039 mSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010040 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010041 &config,
10042 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10043 &deviceId,
10044 &portId);
10045 }
10046 // APM should not chose a different input or output stream for the same set of attributes
10047 // and audo configuration
10048 if (ret != NO_ERROR || io != mId) {
10049 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10050 __FUNCTION__, ret, io, mId);
10051 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010052 }
10053
10054 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010055 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010056 } else {
jiabin09609032022-06-15 19:26:01 +000010057 {
10058 // Add the track record before starting input so that the silent status for the
10059 // client can be cached.
10060 Mutex::Autolock _l(mLock);
10061 setClientSilencedState_l(portId, false /*silenced*/);
10062 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010063 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010064 }
10065
Eric Laurent331679c2018-04-16 17:03:16 -070010066 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010067 // abort if start is rejected by audio policy manager
10068 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010069 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010070 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -070010071 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010072 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010073 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010074 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010075 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010076 }
Eric Laurent331679c2018-04-16 17:03:16 -070010077 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010078 } else {
10079 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010080 }
jiabin09609032022-06-15 19:26:01 +000010081 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010082 return PERMISSION_DENIED;
10083 }
10084
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010085 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung11e74242023-06-26 19:20:57 -070010086 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10087 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010088 mChannelMask, mSessionId, isOutput(),
10089 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010090 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010091 if (!isOutput()) {
10092 track->setSilenced_l(isClientSilenced_l(portId));
10093 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010094
Eric Laurent4eb58f12018-12-07 16:41:02 -080010095 if (isOutput()) {
10096 // force volume update when a new track is added
10097 mHalVolFloat = -1.0f;
10098 } else if (!track->isSilenced_l()) {
Andy Hung11e74242023-06-26 19:20:57 -070010099 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010100 if (t->isSilenced_l()
10101 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010102 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010103 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010104 }
10105 }
10106
Eric Laurent6acd1d42017-01-04 14:23:29 -080010107 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010108 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010109 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +020010110 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010111 chain->incTrackCnt();
10112 chain->incActiveTrackCnt();
10113 }
10114
Andy Hungc2b11cb2020-04-22 09:04:01 -070010115 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010116 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010117
10118 if (mActiveTracks.size() == 1) {
10119 ret = exitStandby_l();
10120 }
10121
Eric Laurent6acd1d42017-01-04 14:23:29 -080010122 broadcast_l();
10123
Eric Laurentdda206a2022-07-08 17:28:35 +020010124 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010125
Eric Laurentdda206a2022-07-08 17:28:35 +020010126 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010127}
10128
Andy Hung4b17e882023-07-07 13:47:37 -070010129status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010130{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010131 ALOGV("%s handle %d", __FUNCTION__, handle);
10132
10133 if (mHalStream == 0) {
10134 return NO_INIT;
10135 }
10136
Eric Laurenta54f1282017-07-01 19:39:32 -070010137 if (handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +000010138 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -070010139 return NO_ERROR;
10140 }
10141
Eric Laurent331679c2018-04-16 17:03:16 -070010142 Mutex::Autolock _l(mLock);
10143
Andy Hung11e74242023-06-26 19:20:57 -070010144 sp<IAfMmapTrack> track;
10145 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010146 if (handle == t->portId()) {
10147 track = t;
10148 break;
10149 }
10150 }
10151 if (track == 0) {
10152 return BAD_VALUE;
10153 }
10154
10155 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010156 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010157
Eric Laurent331679c2018-04-16 17:03:16 -070010158 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010159 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010160 AudioSystem::stopOutput(track->portId());
10161 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010162 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010163 AudioSystem::stopInput(track->portId());
10164 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010165 }
Eric Laurent331679c2018-04-16 17:03:16 -070010166 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010167
Andy Hung116bc262023-06-20 18:56:17 -070010168 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010169 if (chain != 0) {
10170 chain->decActiveTrackCnt();
10171 chain->decTrackCnt();
10172 }
10173
Eric Laurentdda206a2022-07-08 17:28:35 +020010174 if (mActiveTracks.isEmpty()) {
10175 mHalStream->stop();
10176 }
10177
Eric Laurent6acd1d42017-01-04 14:23:29 -080010178 broadcast_l();
10179
Eric Laurent6acd1d42017-01-04 14:23:29 -080010180 return NO_ERROR;
10181}
10182
Andy Hung4b17e882023-07-07 13:47:37 -070010183status_t MmapThread::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010184{
10185 ALOGV("%s", __FUNCTION__);
10186
10187 if (mHalStream == 0) {
10188 return NO_INIT;
10189 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010190 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010191 return INVALID_OPERATION;
10192 }
10193 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010194 if (!mStandby) {
10195 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010196 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010197 mStandby = true;
10198 }
Eric Laurent18b57012017-02-13 16:23:52 -080010199 releaseWakeLock();
10200 return NO_ERROR;
10201}
10202
Andy Hung4b17e882023-07-07 13:47:37 -070010203status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010204 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10205 return INVALID_OPERATION;
10206}
10207
Andy Hung4b17e882023-07-07 13:47:37 -070010208void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010209{
10210 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10211 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10212 mFormat = mHALFormat;
10213 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10214 result = mHalStream->getFrameSize(&mFrameSize);
10215 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010216 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10217 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010218 result = mHalStream->getBufferSize(&mBufferSize);
10219 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10220 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010221
Andy Hungcf10d742020-04-28 15:38:24 -070010222 // TODO: make a readHalParameters call?
10223 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010224 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
10225 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
10226 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10227 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10228 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10229 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10230 /*
10231 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10232 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10233 (int32_t)mHapticChannelMask)
10234 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10235 (int32_t)mHapticChannelCount)
10236 */
10237 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
10238 formatToString(mHALFormat).c_str())
10239 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10240 (int32_t)mFrameCount) // sic - added HAL
10241 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010242}
10243
Andy Hung4b17e882023-07-07 13:47:37 -070010244bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010245{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010246 checkSilentMode_l();
10247
10248 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10249
10250 while (!exitPending())
10251 {
Andy Hung116bc262023-06-20 18:56:17 -070010252 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010253
Andy Hung13850be2019-03-14 11:33:09 -070010254 { // under Thread lock
10255 Mutex::Autolock _l(mLock);
10256
Eric Laurent6acd1d42017-01-04 14:23:29 -080010257 if (mSignalPending) {
10258 // A signal was raised while we were unlocked
10259 mSignalPending = false;
10260 } else {
10261 if (mConfigEvents.isEmpty()) {
10262 // we're about to wait, flush the binder command buffer
10263 IPCThreadState::self()->flushCommands();
10264
10265 if (exitPending()) {
10266 break;
10267 }
10268
Eric Laurent6acd1d42017-01-04 14:23:29 -080010269 // wait until we have something to do...
10270 ALOGV("%s going to sleep", myName.string());
10271 mWaitWorkCV.wait(mLock);
10272 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010273
10274 checkSilentMode_l();
10275
10276 continue;
10277 }
10278 }
10279
10280 processConfigEvents_l();
10281
10282 processVolume_l();
10283
10284 checkInvalidTracks_l();
10285
10286 mActiveTracks.updatePowerState(this);
10287
Kevin Rocard069c2712018-03-29 19:09:14 -070010288 updateMetadata_l();
10289
Eric Laurent6acd1d42017-01-04 14:23:29 -080010290 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010291 } // release Thread lock
10292
Eric Laurent6acd1d42017-01-04 14:23:29 -080010293 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010294 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010295 }
Andy Hung13850be2019-03-14 11:33:09 -070010296
10297 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010298 unlockEffectChains(effectChains);
10299 // Effect chains will be actually deleted here if they were removed from
10300 // mEffectChains list during mixing or effects processing
10301 }
10302
10303 threadLoop_exit();
10304
10305 if (!mStandby) {
10306 threadLoop_standby();
10307 mStandby = true;
10308 }
10309
Eric Laurent6acd1d42017-01-04 14:23:29 -080010310 ALOGV("Thread %p type %d exiting", this, mType);
10311 return false;
10312}
10313
10314// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -070010315bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010316 status_t& status)
10317{
10318 AudioParameter param = AudioParameter(keyValuePair);
10319 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010320 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010321 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010322 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010323 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010324 if (sendToHal) {
10325 status = mHalStream->setParameters(keyValuePair);
10326 } else {
10327 status = NO_ERROR;
10328 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010329
10330 return false;
10331}
10332
Andy Hung4b17e882023-07-07 13:47:37 -070010333String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010334{
10335 Mutex::Autolock _l(mLock);
10336 String8 out_s8;
10337 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10338 return out_s8;
10339 }
Andy Hung920f6572022-10-06 12:09:49 -070010340 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010341}
10342
Andy Hung4b17e882023-07-07 13:47:37 -070010343void MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010344 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010345 sp<AudioIoDescriptor> desc;
10346 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010347 switch (event) {
10348 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010349 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010350 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010351 isInput = true;
10352 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010353 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010354 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010355 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010356 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10357 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010358 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010359 case AUDIO_INPUT_CLOSED:
10360 case AUDIO_OUTPUT_CLOSED:
10361 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010362 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010363 break;
10364 }
Andy Hung7535ed92023-07-17 17:05:00 -070010365 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010366}
10367
Andy Hung4b17e882023-07-07 13:47:37 -070010368status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010369 audio_patch_handle_t *handle)
Andy Hung920f6572022-10-06 12:09:49 -070010370NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010371{
10372 status_t status = NO_ERROR;
10373
10374 // store new device and send to effects
10375 audio_devices_t type = AUDIO_DEVICE_NONE;
10376 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010377 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10378 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10379 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010380 if (isOutput()) {
10381 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010382 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10383 && !mAudioHwDev->supportsAudioPatches(),
10384 "Enumerated device type(%#x) must not be used "
10385 "as it does not support audio patches",
10386 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010387 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010388 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10389 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010390 }
10391 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010392 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010393 } else {
10394 type = patch->sources[0].ext.device.type;
10395 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010396 numDevices = mPatch.num_sources;
10397 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010398 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010399 }
10400
10401 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010402 if (isOutput()) {
10403 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10404 } else {
10405 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10406 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010407 }
10408
jiabinc52b1ff2019-10-31 17:20:42 -070010409 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010410 // store new source and send to effects
10411 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10412 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10413 for (size_t i = 0; i < mEffectChains.size(); i++) {
10414 mEffectChains[i]->setAudioSource_l(mAudioSource);
10415 }
10416 }
10417 }
10418
10419 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010420 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10421 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010422 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010423 audio_port_config port;
10424 std::optional<audio_source_t> source;
10425 if (isOutput()) {
10426 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010427 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010428 port = patch->sources[0];
10429 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010430 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010431 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010432 *handle = AUDIO_PATCH_HANDLE_NONE;
10433 }
10434
jiabinc52b1ff2019-10-31 17:20:42 -070010435 if (numDevices == 0 || mDeviceId != deviceId) {
10436 if (isOutput()) {
10437 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10438 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010439 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010440 } else {
10441 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10442 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10443 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010444 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010445 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010446 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010447 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -070010448 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010449 }
jiabinc52b1ff2019-10-31 17:20:42 -070010450 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010451 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010452 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010453 // Force meteadata update after a route change
10454 mActiveTracks.setHasChanged();
10455
Eric Laurent6acd1d42017-01-04 14:23:29 -080010456 return status;
10457}
10458
Andy Hung4b17e882023-07-07 13:47:37 -070010459status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010460{
10461 status_t status = NO_ERROR;
10462
jiabinc52b1ff2019-10-31 17:20:42 -070010463 mPatch = audio_patch{};
10464 mOutDeviceTypeAddrs.clear();
10465 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010466
10467 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10468 supportsAudioPatches : false;
10469
10470 if (supportsAudioPatches) {
10471 status = mHalDevice->releaseAudioPatch(handle);
10472 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010473 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010474 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010475 // Force meteadata update after a route change
10476 mActiveTracks.setHasChanged();
10477
Eric Laurent6acd1d42017-01-04 14:23:29 -080010478 return status;
10479}
10480
Andy Hung4b17e882023-07-07 13:47:37 -070010481void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010482{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010483 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010484 if (isOutput()) {
10485 config->role = AUDIO_PORT_ROLE_SOURCE;
10486 config->ext.mix.hw_module = mAudioHwDev->handle();
10487 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10488 } else {
10489 config->role = AUDIO_PORT_ROLE_SINK;
10490 config->ext.mix.hw_module = mAudioHwDev->handle();
10491 config->ext.mix.usecase.source = mAudioSource;
10492 }
10493}
10494
Andy Hung4b17e882023-07-07 13:47:37 -070010495status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010496{
10497 audio_session_t session = chain->sessionId();
10498
10499 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10500 // Attach all tracks with same session ID to this chain.
10501 // indicate all active tracks in the chain
Andy Hung11e74242023-06-26 19:20:57 -070010502 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010503 if (session == track->sessionId()) {
10504 chain->incTrackCnt();
10505 chain->incActiveTrackCnt();
10506 }
10507 }
10508
10509 chain->setThread(this);
10510 chain->setInBuffer(nullptr);
10511 chain->setOutBuffer(nullptr);
10512 chain->syncHalEffectsState();
10513
10514 mEffectChains.add(chain);
10515 checkSuspendOnAddEffectChain_l(chain);
10516 return NO_ERROR;
10517}
10518
Andy Hung4b17e882023-07-07 13:47:37 -070010519size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010520{
10521 audio_session_t session = chain->sessionId();
10522
10523 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10524
10525 for (size_t i = 0; i < mEffectChains.size(); i++) {
10526 if (chain == mEffectChains[i]) {
10527 mEffectChains.removeAt(i);
10528 // detach all active tracks from the chain
10529 // detach all tracks with same session ID from this chain
Andy Hung11e74242023-06-26 19:20:57 -070010530 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010531 if (session == track->sessionId()) {
10532 chain->decActiveTrackCnt();
10533 chain->decTrackCnt();
10534 }
10535 }
10536 break;
10537 }
10538 }
10539 return mEffectChains.size();
10540}
10541
Andy Hung4b17e882023-07-07 13:47:37 -070010542void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010543{
10544 mHalStream->standby();
10545}
10546
Andy Hung4b17e882023-07-07 13:47:37 -070010547void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010548{
Phil Burk7dce7282017-09-27 13:51:41 -070010549 // Do not call callback->onTearDown() because it is redundant for thread exit
10550 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010551}
10552
Andy Hung4b17e882023-07-07 13:47:37 -070010553status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010554{
10555 return BAD_VALUE;
10556}
10557
Andy Hung4b17e882023-07-07 13:47:37 -070010558bool MmapThread::isValidSyncEvent(
10559 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010560{
10561 return false;
10562}
10563
Andy Hung4b17e882023-07-07 13:47:37 -070010564status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010565 const effect_descriptor_t *desc, audio_session_t sessionId)
10566{
10567 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010568 if (audio_is_global_session(sessionId)) {
10569 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010570 desc->name, mThreadName);
10571 return BAD_VALUE;
10572 }
10573
10574 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10575 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10576 desc->name);
10577 return BAD_VALUE;
10578 }
10579 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010580 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10581 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010582 return BAD_VALUE;
10583 }
10584
10585 // Only allow effects without processing load or latency
10586 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10587 return BAD_VALUE;
10588 }
10589
Andy Hung116bc262023-06-20 18:56:17 -070010590 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010591 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10592 return BAD_VALUE;
10593 }
10594
Eric Laurent6acd1d42017-01-04 14:23:29 -080010595 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010596}
10597
Andy Hung4b17e882023-07-07 13:47:37 -070010598void MmapThread::checkInvalidTracks_l()
Andy Hung920f6572022-10-06 12:09:49 -070010599NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010600{
Eric Laurent039c24a2022-10-07 14:01:59 +020010601 sp<MmapStreamCallback> callback;
Andy Hung11e74242023-06-26 19:20:57 -070010602 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010603 if (track->isInvalid()) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010604 callback = mCallback.promote();
10605 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10606 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10607 mNoCallbackWarningCount++;
10608 }
10609 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010610 }
10611 }
Eric Laurent039c24a2022-10-07 14:01:59 +020010612 if (callback != 0) {
10613 mLock.unlock();
10614 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10615 mLock.lock();
jiabindfa32482022-10-06 19:45:50 +000010616 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010617}
10618
Andy Hung4b17e882023-07-07 13:47:37 -070010619void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010620{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010621 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10622 mAttr.content_type, mAttr.usage, mAttr.source);
10623 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010624 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010625 dprintf(fd, " No active clients\n");
10626 }
10627}
10628
Andy Hung4b17e882023-07-07 13:47:37 -070010629void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010630{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010631 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010632 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010633 dprintf(fd, " %zu Tracks\n", numtracks);
10634 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010635 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010636 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010637 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010638 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -070010639 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010640 result.append(prefix);
10641 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010642 }
10643 } else {
10644 dprintf(fd, "\n");
10645 }
10646 write(fd, result.string(), result.size());
10647}
10648
Andy Hung4b17e882023-07-07 13:47:37 -070010649/* static */
10650sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -070010651 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung4b17e882023-07-07 13:47:37 -070010652 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070010653 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070010654}
10655
10656MmapPlaybackThread::MmapPlaybackThread(
Andy Hung7535ed92023-07-17 17:05:00 -070010657 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010658 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070010659 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010660 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010661 mStreamVolume(1.0),
10662 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010663 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010664{
10665 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10666 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung7535ed92023-07-17 17:05:00 -070010667 mMasterVolume = afThreadCallback->masterVolume_l();
10668 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010669 if (mAudioHwDev) {
10670 if (mAudioHwDev->canSetMasterVolume()) {
10671 mMasterVolume = 1.0;
10672 }
10673
10674 if (mAudioHwDev->canSetMasterMute()) {
10675 mMasterMute = false;
10676 }
10677 }
10678}
10679
Andy Hung4b17e882023-07-07 13:47:37 -070010680void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010681 audio_stream_type_t streamType,
10682 audio_session_t sessionId,
10683 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010684 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010685 audio_port_handle_t portId)
10686{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010687 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010688 mStreamType = streamType;
10689}
10690
Andy Hung4b17e882023-07-07 13:47:37 -070010691AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010692{
10693 Mutex::Autolock _l(mLock);
10694 AudioStreamOut *output = mOutput;
10695 mOutput = NULL;
10696 return output;
10697}
10698
Andy Hung4b17e882023-07-07 13:47:37 -070010699void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010700{
10701 Mutex::Autolock _l(mLock);
10702 // Don't apply master volume in SW if our HAL can do it for us.
10703 if (mAudioHwDev &&
10704 mAudioHwDev->canSetMasterVolume()) {
10705 mMasterVolume = 1.0;
10706 } else {
10707 mMasterVolume = value;
10708 }
10709}
10710
Andy Hung4b17e882023-07-07 13:47:37 -070010711void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010712{
10713 Mutex::Autolock _l(mLock);
10714 // Don't apply master mute in SW if our HAL can do it for us.
10715 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10716 mMasterMute = false;
10717 } else {
10718 mMasterMute = muted;
10719 }
10720}
10721
Andy Hung4b17e882023-07-07 13:47:37 -070010722void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010723{
10724 Mutex::Autolock _l(mLock);
10725 if (stream == mStreamType) {
10726 mStreamVolume = value;
10727 broadcast_l();
10728 }
10729}
10730
Andy Hung4b17e882023-07-07 13:47:37 -070010731float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010732{
10733 Mutex::Autolock _l(mLock);
10734 if (stream == mStreamType) {
10735 return mStreamVolume;
10736 }
10737 return 0.0f;
10738}
10739
Andy Hung4b17e882023-07-07 13:47:37 -070010740void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010741{
10742 Mutex::Autolock _l(mLock);
10743 if (stream == mStreamType) {
10744 mStreamMute= muted;
10745 broadcast_l();
10746 }
10747}
10748
Andy Hung4b17e882023-07-07 13:47:37 -070010749void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010750{
10751 Mutex::Autolock _l(mLock);
10752 if (streamType == mStreamType) {
Andy Hung11e74242023-06-26 19:20:57 -070010753 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010754 track->invalidate();
10755 }
10756 broadcast_l();
10757 }
10758}
10759
Andy Hung4b17e882023-07-07 13:47:37 -070010760void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010761{
10762 Mutex::Autolock _l(mLock);
10763 bool trackMatch = false;
Andy Hung11e74242023-06-26 19:20:57 -070010764 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010765 if (portIds.find(track->portId()) != portIds.end()) {
10766 track->invalidate();
10767 trackMatch = true;
10768 portIds.erase(track->portId());
10769 }
10770 if (portIds.empty()) {
10771 break;
10772 }
10773 }
10774 if (trackMatch) {
10775 broadcast_l();
10776 }
10777}
10778
Andy Hung4b17e882023-07-07 13:47:37 -070010779void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070010780NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080010781{
10782 float volume;
10783
10784 if (mMasterMute || mStreamMute) {
10785 volume = 0;
10786 } else {
10787 volume = mMasterVolume * mStreamVolume;
10788 }
10789
10790 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010791
10792 // Convert volumes from float to 8.24
10793 uint32_t vol = (uint32_t)(volume * (1 << 24));
10794
10795 // Delegate volume control to effect in track effect chain if needed
10796 // only one effect chain can be present on DirectOutputThread, so if
10797 // there is one, the track is connected to it
10798 if (!mEffectChains.isEmpty()) {
10799 mEffectChains[0]->setVolume_l(&vol, &vol);
10800 volume = (float)vol / (1 << 24);
10801 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010802 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010803 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10804 mHalVolFloat = volume; // HW volume control worked, so update value.
10805 mNoCallbackWarningCount = 0;
10806 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010807 sp<MmapStreamCallback> callback = mCallback.promote();
10808 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010809 mHalVolFloat = volume; // SW volume control worked, so update value.
10810 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010811 mLock.unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010812 callback->onVolumeChanged(volume);
Eric Laurent734046e2018-04-16 14:50:52 -070010813 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010814 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010815 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10816 ALOGW("Could not set MMAP stream volume: no volume callback!");
10817 mNoCallbackWarningCount++;
10818 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010819 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010820 }
Andy Hung11e74242023-06-26 19:20:57 -070010821 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010822 track->setMetadataHasChanged();
Andy Hung7535ed92023-07-17 17:05:00 -070010823 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010824 /*muteState=*/{mMasterMute,
10825 mStreamVolume == 0.f,
10826 mStreamMute,
10827 // TODO(b/241533526): adjust logic to include mute from AppOps
10828 false /*muteFromPlaybackRestricted*/,
10829 false /*muteFromClientVolume*/,
10830 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010831 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010832 }
10833}
10834
Andy Hung4b17e882023-07-07 13:47:37 -070010835ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070010836{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010837 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010010838 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010839 }
10840 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung11e74242023-06-26 19:20:57 -070010841 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070010842 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010843 playback_track_metadata_v7_t trackMetadata;
10844 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010845 .usage = track->attributes().usage,
10846 .content_type = track->attributes().content_type,
10847 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010848 };
10849 trackMetadata.channel_mask = track->channelMask(),
10850 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10851 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010852 }
10853 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010010854
10855 MetadataUpdate change;
10856 change.playbackMetadataUpdate = metadata.tracks;
10857 return change;
10858};
Kevin Rocard069c2712018-03-29 19:09:14 -070010859
Andy Hung4b17e882023-07-07 13:47:37 -070010860void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010861{
10862 if (!mMasterMute) {
10863 char value[PROPERTY_VALUE_MAX];
10864 if (property_get("ro.audio.silent", value, "0") > 0) {
10865 char *endptr;
10866 unsigned long ul = strtoul(value, &endptr, 0);
10867 if (*endptr == '\0' && ul != 0) {
10868 ALOGD("Silence is golden");
10869 // The setprop command will not allow a property to be changed after
10870 // the first time it is set, so we don't have to worry about un-muting.
10871 setMasterMute_l(true);
10872 }
10873 }
10874 }
10875}
10876
Andy Hung4b17e882023-07-07 13:47:37 -070010877void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010878{
10879 MmapThread::toAudioPortConfig(config);
10880 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10881 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10882 config->flags.output = mOutput->flags;
10883 }
10884}
10885
Andy Hung4b17e882023-07-07 13:47:37 -070010886status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung3e4c8742023-06-29 21:19:25 -070010887 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070010888{
10889 if (mOutput == nullptr) {
10890 return NO_INIT;
10891 }
10892 struct timespec timestamp;
10893 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10894 if (status == NO_ERROR) {
10895 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10896 }
10897 return status;
10898}
10899
Andy Hung4b17e882023-07-07 13:47:37 -070010900status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010901 // Send to MelProcessor for sound dose measurement.
10902 auto processor = mMelProcessor.load();
10903 if (processor) {
10904 processor->process(buffer, frameCount * mFrameSize);
10905 }
10906
jiabinfc791ee2023-02-15 19:43:40 +000010907 return NO_ERROR;
10908}
10909
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010910// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -070010911void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010912 const sp<audio_utils::MelProcessor>& processor)
10913{
10914 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010915 mMelProcessor.store(processor);
10916 if (processor) {
10917 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010918 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010919
10920 // no need to update output format for MMapPlaybackThread since it is
10921 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010922}
10923
10924// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -070010925void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010926{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010927 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
10928 auto melProcessor = mMelProcessor.load();
10929 if (melProcessor != nullptr) {
10930 melProcessor->pause();
10931 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010932}
10933
Andy Hung4b17e882023-07-07 13:47:37 -070010934void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010935{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010936 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010937
Glenn Kastend3bb6452016-12-05 18:14:37 -080010938 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10939 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010940 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10941}
10942
Andy Hung4b17e882023-07-07 13:47:37 -070010943/* static */
10944sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -070010945 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung4b17e882023-07-07 13:47:37 -070010946 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070010947 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070010948}
10949
10950MmapCaptureThread::MmapCaptureThread(
Andy Hung7535ed92023-07-17 17:05:00 -070010951 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010952 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070010953 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010954 mInput(input)
10955{
10956 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10957 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10958}
10959
Andy Hung4b17e882023-07-07 13:47:37 -070010960status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010961{
Phil Burkf054fc32018-12-06 09:45:59 -080010962 {
10963 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080010964 if (mInput != nullptr && mInput->stream != nullptr) {
10965 mInput->stream->setGain(1.0f);
10966 }
10967 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010968 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010969}
10970
Andy Hung4b17e882023-07-07 13:47:37 -070010971AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010972{
10973 Mutex::Autolock _l(mLock);
10974 AudioStreamIn *input = mInput;
10975 mInput = NULL;
10976 return input;
10977}
Kevin Rocard069c2712018-03-29 19:09:14 -070010978
Andy Hung4b17e882023-07-07 13:47:37 -070010979void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010980{
10981 bool changed = false;
10982 bool silenced = false;
10983
10984 sp<MmapStreamCallback> callback = mCallback.promote();
10985 if (callback == 0) {
10986 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10987 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10988 mNoCallbackWarningCount++;
10989 }
10990 }
10991
10992 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10993 // track is silenced and unmute otherwise
10994 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10995 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10996 changed = true;
10997 silenced = mActiveTracks[i]->isSilenced_l();
10998 }
10999 }
11000
11001 if (changed) {
11002 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11003 }
11004}
11005
Andy Hung4b17e882023-07-07 13:47:37 -070011006ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011007{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011008 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011009 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011010 }
11011 StreamInHalInterface::SinkMetadata metadata;
Andy Hung11e74242023-06-26 19:20:57 -070011012 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011013 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011014 record_track_metadata_v7_t trackMetadata;
11015 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011016 .source = track->attributes().source,
11017 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011018 };
11019 trackMetadata.channel_mask = track->channelMask(),
11020 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11021 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011022 }
11023 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011024 MetadataUpdate change;
11025 change.recordMetadataUpdate = metadata.tracks;
11026 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011027}
11028
Andy Hung4b17e882023-07-07 13:47:37 -070011029void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011030{
11031 Mutex::Autolock _l(mLock);
11032 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011033 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011034 mActiveTracks[i]->setSilenced_l(silenced);
11035 broadcast_l();
11036 }
11037 }
jiabin09609032022-06-15 19:26:01 +000011038 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011039}
11040
Andy Hung4b17e882023-07-07 13:47:37 -070011041void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011042{
11043 MmapThread::toAudioPortConfig(config);
11044 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11045 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11046 config->flags.input = mInput->flags;
11047 }
11048}
11049
Andy Hung4b17e882023-07-07 13:47:37 -070011050status_t MmapCaptureThread::getExternalPosition(
Andy Hung3e4c8742023-06-29 21:19:25 -070011051 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011052{
11053 if (mInput == nullptr) {
11054 return NO_INIT;
11055 }
11056 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11057}
11058
jiabinc658e452022-10-21 20:52:21 +000011059// ----------------------------------------------------------------------------
11060
Andy Hung4b17e882023-07-07 13:47:37 -070011061/* static */
11062sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung7535ed92023-07-17 17:05:00 -070011063 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -070011064 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070011065 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070011066}
11067
Andy Hung7535ed92023-07-17 17:05:00 -070011068BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011069 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070011070 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011071
Andy Hung4b17e882023-07-07 13:47:37 -070011072PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -070011073 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011074 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11075 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011076 float volumeLeft = 1.0f;
11077 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011078 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11079 const int trackId = mActiveTracks[0]->id();
11080 mAudioMixer->setParameter(
11081 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11082 mAudioMixer->setParameter(
11083 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11084 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011085 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011086 mIsBitPerfect = true;
11087 } else {
11088 mIsBitPerfect = false;
11089 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11090 // active.
11091 for (const auto& track : mActiveTracks) {
11092 const int trackId = track->id();
11093 mAudioMixer->setParameter(
11094 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11095 }
11096 }
jiabin76d94692022-12-15 21:51:21 +000011097 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11098 mVolumeLeft = volumeLeft;
11099 mVolumeRight = volumeRight;
11100 setVolumeForOutput_l(volumeLeft, volumeRight);
11101 }
jiabinc658e452022-10-21 20:52:21 +000011102 return result;
11103}
11104
Andy Hung4b17e882023-07-07 13:47:37 -070011105void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011106 MixerThread::threadLoop_mix();
11107 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11108}
11109
Glenn Kasten63238ef2015-03-02 15:50:29 -080011110} // namespace android