blob: f6b8e191b4310233cf63d5d62c6a06ac7fd4f1e9 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
Vlad Popab042ee62022-10-20 18:05:00 +020020// #define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <memory>
Andy Hungb68f5eb2019-12-03 16:49:17 -080027#include <sstream>
Eric Tan7b651152018-07-13 10:17:19 -070028#include <string>
Glenn Kastenad8510a2015-02-17 16:24:07 -080029#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080030#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080031#include <sys/syscall.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070032#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080033#include <cutils/properties.h>
Vlad Popae8d99472022-06-30 16:02:48 +020034#include <binder/PersistableBundle.h>
jiabinc52b1ff2019-10-31 17:20:42 -070035#include <media/AudioContainers.h>
36#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070037#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070038#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080039#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070040#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080041#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080042#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043
44#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070045#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010046#include <audio_utils/Balance.h>
Vlad Popab042ee62022-10-20 18:05:00 +020047#include <audio_utils/MelProcessor.h>
jiabinf6eb4c32020-02-25 14:06:25 -080048#include <audio_utils/Metadata.h>
jiabin245cdd92018-12-07 17:55:15 -080049#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080050#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080051#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080052#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070053#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070054#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070055#include <system/audio_effects/effect_aec.h>
Eric Laurentb3f315a2021-07-13 15:09:05 +020056#include <system/audio_effects/effect_downmix.h>
57#include <system/audio_effects/effect_ns.h>
Eric Laurent1c5e2e32021-08-18 18:50:28 +020058#include <system/audio_effects/effect_spatializer.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070059#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080060
61// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070062#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080063#include <media/nbaio/AudioStreamOutSink.h>
64#include <media/nbaio/MonoPipe.h>
65#include <media/nbaio/MonoPipeReader.h>
66#include <media/nbaio/Pipe.h>
67#include <media/nbaio/PipeReader.h>
68#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080069#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070070#include <mediautils/Process.h>
Eric Laurent81784c32012-11-19 14:55:58 -080071
Mikhail Naganov2996f672019-04-18 12:29:59 -070072#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080073#include <powermanager/PowerManager.h>
74
Kevin Rocard7588ff42018-01-08 11:11:30 -080075#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070076#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080077
Eric Laurent81784c32012-11-19 14:55:58 -080078#include "AudioFlinger.h"
Andy Hung71742ab2023-07-07 13:47:37 -070079#include "Threads.h"
80
Andy Hungab7ef302018-05-15 19:35:29 -070081#include <mediautils/SchedulingPolicyService.h>
82#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080083
Eric Laurent81784c32012-11-19 14:55:58 -080084#ifdef ADD_BATTERY_DATA
85#include <media/IMediaPlayerService.h>
86#include <media/IMediaDeathNotifier.h>
87#endif
88
Eric Laurent81784c32012-11-19 14:55:58 -080089#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070090#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080091#include <cpustats/ThreadCpuUsage.h>
92#endif
93
Andy Hungbef3a1e2023-05-23 17:36:46 -070094#include <fastpath/AutoPark.h>
Glenn Kastenc05b8d72016-03-24 09:48:17 -070095
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080096#include <pthread.h>
Andy Hung21ff9672023-07-18 20:54:44 -070097#include <afutils/DumpTryLock.h>
Andy Hungc5106312023-07-19 16:56:19 -070098#include <afutils/Permission.h>
Andy Hungb776e372023-05-24 11:53:47 -070099#include <afutils/TypedLogger.h>
Andy Hung9554ec02023-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 Hung71742ab2023-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 Lindahl9e661ad2022-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 Naganova77d5552022-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 Hung71ba4b32022-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",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000499 title.c_str(),
Eric Laurent81784c32012-11-19 14:55:58 -0800500 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 Hung71742ab2023-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 Hung2cbc2722023-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 Hung2cbc2722023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-07-07 13:47:37 -0700623status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800624{
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000625 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800626 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 Hung71742ab2023-07-07 13:47:37 -0700633status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung71ba4b32022-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-07-07 13:47:37 -0700775void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent6f9534f2022-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 Hung71742ab2023-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",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000810 data->mKeyValuePairs.c_str());
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 Laurent6f9534f2022-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 Hung71742ab2023-07-07 13:47:37 -0700949void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung71ba4b32022-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 Hung21ff9672023-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 Hung71742ab2023-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,
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000997 channelMaskToString(mChannelMask, mType != RECORD).c_str());
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 Hung71742ab2023-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 Hungbd72c542023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hungbd72c542023-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 Hung71742ab2023-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 Hungbd72c542023-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 Hung71742ab2023-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 Hungbd72c542023-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 Hung71742ab2023-07-07 13:47:37 -07001317void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001318 audio_session_t sessionId,
Andy Hung71ba4b32022-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 Hung71742ab2023-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 Hungbd72c542023-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 Hung71742ab2023-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 Hungbd72c542023-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 Hung71742ab2023-07-07 13:47:37 -07001542sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hungd65869f2023-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 Hungbd72c542023-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 Hungbd72c542023-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 Hungbd72c542023-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 Hung2cbc2722023-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 Hung2cbc2722023-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 Hung2cbc2722023-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 Hungbd72c542023-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 Hung71742ab2023-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 Hungbd72c542023-06-20 18:56:17 -07001651 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001652 {
1653 Mutex::Autolock _l(mLock);
Andy Hungbd72c542023-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 Hung2cbc2722023-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 Hung71742ab2023-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 Hung2cbc2722023-07-17 17:05:00 -07001688 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001689 }
1690 }
1691}
1692
Andy Hung71742ab2023-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 Hung71742ab2023-07-07 13:47:37 -07001700sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung4989d312023-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 Hung71742ab2023-07-07 13:47:37 -07001707sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung4989d312023-06-29 21:19:25 -07001708 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001709{
Andy Hungbd72c542023-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 Hung71742ab2023-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 Hungbd72c542023-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 Hung71742ab2023-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 Hungbd72c542023-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 Hungbd72c542023-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 Hung2cbc2722023-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 Hung71742ab2023-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 Hungbd72c542023-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 Hung71742ab2023-07-07 13:47:37 -07001786void ThreadBase::lockEffectChains_l(
Andy Hungbd72c542023-06-20 18:56:17 -07001787 Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung71ba4b32022-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 Hung71742ab2023-07-07 13:47:37 -07001796void ThreadBase::unlockEffectChains(
Andy Hungbd72c542023-06-20 18:56:17 -07001797 const Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung71ba4b32022-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001837 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001838 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 Hung71742ab2023-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 Hung71742ab2023-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;
1867 ++mBatteryCounter[track->uid()].second;
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 Hung71742ab2023-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++;
1881 --mBatteryCounter[track->uid()].second;
1882 // 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 Hung71742ab2023-07-07 13:47:37 -07001892void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001893 for (const sp<T> &track : mActiveTracks) {
1894 BatteryNotifier::getInstance().noteStopAudio(track->uid());
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();
1901 mBatteryCounter.clear();
1902}
1903
1904template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001905void ThreadBase::ActiveTracks<T>::updatePowerState(
Andy Hung71ba4b32022-10-06 12:09:49 -07001906 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001907 // Updates ActiveTracks client uids to the thread wakelock.
1908 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1909 thread->updateWakeLockUids_l(getWakeLockUids());
1910 mLastActiveTracksGeneration = mActiveTracksGeneration;
1911 }
1912
1913 // Updates BatteryNotifier uids
1914 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1915 const uid_t uid = it->first;
1916 ssize_t &previous = it->second.first;
1917 ssize_t &current = it->second.second;
1918 if (current > 0) {
1919 if (previous == 0) {
1920 BatteryNotifier::getInstance().noteStartAudio(uid);
1921 }
1922 previous = current;
1923 ++it;
1924 } else if (current == 0) {
1925 if (previous > 0) {
1926 BatteryNotifier::getInstance().noteStopAudio(uid);
1927 }
1928 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1929 } else /* (current < 0) */ {
1930 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1931 }
1932 }
1933}
Eric Laurent83b88082014-06-20 18:31:16 -07001934
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001935template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001936bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001937 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001938 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001939
1940 for (const sp<T> &track : mActiveTracks) {
1941 // Do not short-circuit as all hasChanged states must be reset
1942 // as all the metadata are going to be sent
1943 hasChanged |= track->readAndClearHasChanged();
1944 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001945 return hasChanged;
1946}
1947
1948template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001949void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001950 const char *funcName, const sp<T> &track) const {
1951 if (mLocalLog != nullptr) {
1952 String8 result;
1953 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00001954 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001955 }
1956}
1957
Andy Hung71742ab2023-07-07 13:47:37 -07001958void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08001959{
1960 // Thread could be blocked waiting for async
1961 // so signal it to handle state changes immediately
1962 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1963 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1964 mSignalPending = true;
1965 mWaitWorkCV.broadcast();
1966}
1967
Andy Hungd0979812019-02-21 15:51:44 -08001968// Call only from threadLoop() or when it is idle.
1969// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hung71742ab2023-07-07 13:47:37 -07001970void ThreadBase::sendStatistics(bool force)
Andy Hungd0979812019-02-21 15:51:44 -08001971{
1972 // Do not log if we have no stats.
1973 // We choose the timestamp verifier because it is the most likely item to be present.
1974 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1975 if (nstats == 0) {
1976 return;
1977 }
1978
1979 // Don't log more frequently than once per 12 hours.
1980 // We use BOOTTIME to include suspend time.
1981 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1982 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1983 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1984 return;
1985 }
1986
1987 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1988 mLastRecordedTimeNs = timeNs;
1989
Ray Essickf27e9872019-12-07 06:28:46 -08001990 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001991
1992#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1993
1994 // thread configuration
1995 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1996 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1997 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1998 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1999 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2000 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2001 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07002002 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
2003 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002004
2005 // thread statistics
2006 if (mIoJitterMs.getN() > 0) {
2007 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2008 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2009 }
2010 if (mProcessTimeMs.getN() > 0) {
2011 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2012 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2013 }
2014 const auto tsjitter = mTimestampVerifier.getJitterMs();
2015 if (tsjitter.getN() > 0) {
2016 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2017 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2018 }
2019 if (mLatencyMs.getN() > 0) {
2020 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2021 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2022 }
Robert Wu06db0a32021-08-10 19:05:34 +00002023 if (mMonopipePipeDepthStats.getN() > 0) {
2024 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2025 mMonopipePipeDepthStats.getMean());
2026 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2027 mMonopipePipeDepthStats.getStdDev());
2028 }
Andy Hungd0979812019-02-21 15:51:44 -08002029
2030 item->selfrecord();
2031}
2032
Andy Hung71742ab2023-07-07 13:47:37 -07002033product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002034{
Andy Hung2cbc2722023-07-17 17:05:00 -07002035 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002036 return PRODUCT_STRATEGY_NONE;
2037 }
2038 return AudioSystem::getStrategyForStream(stream);
2039}
2040
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002041// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002042void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002043 const sp<audio_utils::MelProcessor>& /*processor*/)
2044{
2045 // Do nothing
2046 ALOGW("%s: ThreadBase does not support CSD", __func__);
2047}
2048
2049// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002050void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002051{
2052 // Do nothing
2053 ALOGW("%s: ThreadBase does not support CSD", __func__);
2054}
2055
Eric Laurent81784c32012-11-19 14:55:58 -08002056// ----------------------------------------------------------------------------
2057// Playback
2058// ----------------------------------------------------------------------------
2059
Andy Hung2cbc2722023-07-17 17:05:00 -07002060PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002061 AudioStreamOut* output,
2062 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002063 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002064 bool systemReady,
2065 audio_config_base_t *mixerConfig)
Andy Hung2cbc2722023-07-17 17:05:00 -07002066 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002067 mNormalFrameCount(0), mSinkBuffer(NULL),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002068 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002069 mMixerBuffer(NULL),
2070 mMixerBufferSize(0),
2071 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2072 mMixerBufferValid(false),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002073 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002074 mEffectBuffer(NULL),
2075 mEffectBufferSize(0),
2076 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2077 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002078 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002079 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002080 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002081 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002082 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002083 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002084 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002085 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002086 mMixerStatus(MIXER_IDLE),
2087 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002088 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002089 mBytesRemaining(0),
2090 mCurrentWriteLength(0),
2091 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002092 mWriteAckSequence(0),
2093 mDrainSequence(0),
Andy Hung01b29482023-07-19 16:22:58 -07002094 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002095 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002096 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002097 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002098 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl9e661ad2022-07-27 18:01:07 +02002099 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002100 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002101{
Glenn Kastend7dca052015-03-05 16:05:54 -08002102 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung2cbc2722023-07-17 17:05:00 -07002103 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002104
2105 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2106 // it would be safer to explicitly pass initial masterVolume/masterMute as
2107 // parameter.
2108 //
2109 // If the HAL we are using has support for master volume or master mute,
2110 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2111 // and the mute set to false).
Andy Hung2cbc2722023-07-17 17:05:00 -07002112 mMasterVolume = afThreadCallback->masterVolume_l();
2113 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002114 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002115 if (mOutput->audioHwDev->canSetMasterVolume()) {
2116 mMasterVolume = 1.0;
2117 }
2118
2119 if (mOutput->audioHwDev->canSetMasterMute()) {
2120 mMasterMute = false;
2121 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002122 mIsMsdDevice = strcmp(
2123 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002124 }
2125
Eric Laurentf1f22e72021-07-13 14:04:14 +02002126 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2127 mMixerChannelMask = mixerConfig->channel_mask;
2128 }
2129
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002130 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002131
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002132 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002133 && mMixerChannelMask != mChannelMask) {
2134 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2135 mChannelMask, mMixerChannelMask);
2136 }
2137
Andy Hungc8fddf32018-08-08 18:32:37 -07002138 // TODO: We may also match on address as well as device type for
2139 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002140 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002141 // TODO: This property should be ensure that only contains one single device type.
2142 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2143 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002144 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2145 : AUDIO_DEVICE_NONE));
2146 }
2147
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002148 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2149 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002150 mStreamTypes[stream].volume = 0.0f;
Andy Hung2cbc2722023-07-17 17:05:00 -07002151 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002152 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002153 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002154 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2155 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002156 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2157 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002158}
2159
Andy Hung71742ab2023-07-07 13:47:37 -07002160PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002161{
Andy Hung2cbc2722023-07-17 17:05:00 -07002162 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002163 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002164 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002165 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002166 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002167}
2168
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002169// Thread virtuals
2170
Andy Hung71742ab2023-07-07 13:47:37 -07002171void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002172{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002173 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002174 ALOGE("The stream is not open yet"); // This should not happen.
2175 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002176 // Callbacks take strong or weak pointers as a parameter.
2177 // Since PlaybackThread passes itself as a callback handler, it can only
2178 // be done outside of the constructor. Creating weak and especially strong
2179 // pointers to a refcounted object in its own constructor is strongly
2180 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2181 // Even if a function takes a weak pointer, it is possible that it will
2182 // need to convert it to a strong pointer down the line.
2183 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2184 mOutput->stream->setCallback(this) == OK) {
2185 mUseAsyncWrite = true;
Andy Hung71742ab2023-07-07 13:47:37 -07002186 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002187 }
2188
jiabinf6eb4c32020-02-25 14:06:25 -08002189 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002190 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002191 }
2192 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002193 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002194 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002195}
2196
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002197// ThreadBase virtuals
Andy Hung71742ab2023-07-07 13:47:37 -07002198void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002199{
2200 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002201 status_t result = mOutput->stream->exit();
2202 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002203}
2204
Andy Hung71742ab2023-07-07 13:47:37 -07002205void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002206{
Eric Laurent81784c32012-11-19 14:55:58 -08002207 String8 result;
2208
Marco Nelissenb2208842014-02-07 14:00:50 -08002209 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002210 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2211 const stream_type_t *st = &mStreamTypes[i];
2212 if (i > 0) {
2213 result.appendFormat(", ");
2214 }
2215 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2216 if (st->mute) {
2217 result.append("M");
2218 }
2219 }
2220 result.append("\n");
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002221 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002222 result.clear();
2223
Eric Laurent81784c32012-11-19 14:55:58 -08002224 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2225 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002226 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002227 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002228
2229 size_t numtracks = mTracks.size();
2230 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002231 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002232 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002233 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002234 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002235 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002236 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002237 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002238 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002239 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002240 if (track != 0) {
2241 bool active = mActiveTracks.indexOf(track) >= 0;
2242 if (active) {
2243 numactiveseen++;
2244 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002245 result.append(prefix);
2246 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002247 }
2248 }
2249 } else {
2250 result.append("\n");
2251 }
2252 if (numactiveseen != numactive) {
2253 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002254 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002255 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002256 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002257 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002258 for (size_t i = 0; i < numactive; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002259 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002260 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002261 result.append(prefix);
2262 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002263 }
2264 }
2265 }
2266
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002267 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002268}
2269
Andy Hung71742ab2023-07-07 13:47:37 -07002270void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002271{
Andy Hung04cb8f72020-03-20 13:44:33 -07002272 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002273 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002274 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2275 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002276 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2277 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2278 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2279 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002280 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002281 dprintf(fd, " Total writes: %d\n", mNumWrites);
2282 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2283 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2284 dprintf(fd, " Suspend count: %d\n", mSuspended);
2285 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2286 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2287 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2288 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002289 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002290 AudioStreamOut *output = mOutput;
2291 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002292 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002293 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002294 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2295 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2296 if (mPipeSink.get() != nullptr) {
2297 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2298 }
2299 if (output != nullptr) {
2300 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002301 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002302 }
Eric Laurent81784c32012-11-19 14:55:58 -08002303}
2304
Eric Laurent81784c32012-11-19 14:55:58 -08002305// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002306sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hungd65869f2023-06-27 17:05:02 -07002307 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002308 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002309 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002310 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002311 audio_format_t format,
2312 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002313 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002314 size_t *pNotificationFrameCount,
2315 uint32_t notificationsPerBuffer,
2316 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002317 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002318 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002319 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002320 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002321 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002322 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002323 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002324 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002325 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002326 bool isSpatialized,
2327 bool isBitPerfect)
Eric Laurent81784c32012-11-19 14:55:58 -08002328{
Glenn Kasten74935e42013-12-19 08:56:45 -08002329 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002330 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung3ff4b552023-06-26 19:20:57 -07002331 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002332 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002333 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002334 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002335 uint32_t sampleRate;
2336
2337 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2338 lStatus = BAD_VALUE;
2339 goto Exit;
2340 }
Eric Laurent21da6472017-11-09 16:29:26 -08002341
2342 if (*pSampleRate == 0) {
2343 *pSampleRate = mSampleRate;
2344 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002345 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002346
2347 // special case for FAST flag considered OK if fast mixer is present
2348 if (hasFastMixer()) {
2349 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2350 }
2351
2352 // Check if requested flags are compatible with output stream flags
2353 if ((*flags & outputFlags) != *flags) {
2354 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2355 *flags, outputFlags);
2356 *flags = (audio_output_flags_t)(*flags & outputFlags);
2357 }
Eric Laurent81784c32012-11-19 14:55:58 -08002358
jiabinc658e452022-10-21 20:52:21 +00002359 if (isBitPerfect) {
Andy Hungbd72c542023-06-20 18:56:17 -07002360 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002361 if (chain.get() != nullptr) {
2362 // Bit-perfect is required according to the configuration and preferred mixer
2363 // attributes, but it is not in the output flag from the client's request. Explicitly
2364 // adding bit-perfect flag to check the compatibility
2365 audio_output_flags_t flagsToCheck =
2366 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2367 chain->checkOutputFlagCompatibility(&flagsToCheck);
2368 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2369 ALOGE("%s cannot create track as there is data-processing effect attached to "
2370 "given session id(%d)", __func__, sessionId);
2371 lStatus = BAD_VALUE;
2372 goto Exit;
2373 }
2374 *flags = flagsToCheck;
2375 }
2376 }
2377
Eric Laurent81784c32012-11-19 14:55:58 -08002378 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002379 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002380 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002381 // PCM data
2382 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002383 // TODO: extract as a data library function that checks that a computationally
2384 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002385 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002386 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2387 (channelMask == AUDIO_CHANNEL_OUT_MONO
2388 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002389 // hardware sample rate
2390 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002391 // normal mixer has an associated fast mixer
2392 hasFastMixer() &&
2393 // there are sufficient fast track slots available
2394 (mFastTrackAvailMask != 0)
2395 // FIXME test that MixerThread for this fast track has a capable output HAL
2396 // FIXME add a permission test also?
2397 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002398 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2399 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002400 // read the fast track multiplier property the first time it is needed
2401 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2402 if (ok != 0) {
2403 ALOGE("%s pthread_once failed: %d", __func__, ok);
2404 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002405 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002406 }
Eric Laurent4c415062016-06-17 16:14:16 -07002407
2408 // check compatibility with audio effects.
2409 { // scope for mLock
2410 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002411 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002412 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002413 AUDIO_SESSION_OUTPUT_STAGE,
2414 AUDIO_SESSION_OUTPUT_MIX,
2415 sessionId,
2416 }) {
Andy Hungbd72c542023-06-20 18:56:17 -07002417 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002418 if (chain.get() != nullptr) {
2419 audio_output_flags_t old = *flags;
2420 chain->checkOutputFlagCompatibility(flags);
2421 if (old != *flags) {
2422 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2423 (int)session, (int)old, (int)*flags);
2424 }
Eric Laurent4c415062016-06-17 16:14:16 -07002425 }
2426 }
2427 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002428 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002429 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2430 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002431 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002432 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002433 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002434 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002435 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002436 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002437 audio_is_linear_pcm(format), channelMask, sampleRate,
2438 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002439 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002440 }
2441 }
Eric Laurent21da6472017-11-09 16:29:26 -08002442
2443 if (!audio_has_proportional_frames(format)) {
2444 if (sharedBuffer != 0) {
2445 // Same comment as below about ignoring frameCount parameter for set()
2446 frameCount = sharedBuffer->size();
2447 } else if (frameCount == 0) {
2448 frameCount = mNormalFrameCount;
2449 }
2450 if (notificationFrameCount != frameCount) {
2451 notificationFrameCount = frameCount;
2452 }
2453 } else if (sharedBuffer != 0) {
2454 // FIXME: Ensure client side memory buffers need
2455 // not have additional alignment beyond sample
2456 // (e.g. 16 bit stereo accessed as 32 bit frame).
2457 size_t alignment = audio_bytes_per_sample(format);
2458 if (alignment & 1) {
2459 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2460 alignment = 1;
2461 }
2462 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2463 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2464 if (channelCount > 1) {
2465 // More than 2 channels does not require stronger alignment than stereo
2466 alignment <<= 1;
2467 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002468 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002469 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002470 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002471 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002472 goto Exit;
2473 }
Eric Laurent21da6472017-11-09 16:29:26 -08002474
2475 // When initializing a shared buffer AudioTrack via constructors,
2476 // there's no frameCount parameter.
2477 // But when initializing a shared buffer AudioTrack via set(),
2478 // there _is_ a frameCount parameter. We silently ignore it.
2479 frameCount = sharedBuffer->size() / frameSize;
2480 } else {
2481 size_t minFrameCount = 0;
2482 // For fast tracks we try to respect the application's request for notifications per buffer.
2483 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2484 if (notificationsPerBuffer > 0) {
2485 // Avoid possible arithmetic overflow during multiplication.
2486 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2487 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2488 notificationsPerBuffer, mFrameCount);
2489 } else {
2490 minFrameCount = mFrameCount * notificationsPerBuffer;
2491 }
2492 }
2493 } else {
2494 // For normal PCM streaming tracks, update minimum frame count.
2495 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2496 // cover audio hardware latency.
2497 // This is probably too conservative, but legacy application code may depend on it.
2498 // If you change this calculation, also review the start threshold which is related.
2499 uint32_t latencyMs = latency_l();
2500 if (latencyMs == 0) {
2501 ALOGE("Error when retrieving output stream latency");
2502 lStatus = UNKNOWN_ERROR;
2503 goto Exit;
2504 }
2505
2506 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2507 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2508
Eric Laurent81784c32012-11-19 14:55:58 -08002509 }
Eric Laurent21da6472017-11-09 16:29:26 -08002510 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002511 frameCount = minFrameCount;
2512 }
Eric Laurent81784c32012-11-19 14:55:58 -08002513 }
Eric Laurent21da6472017-11-09 16:29:26 -08002514
2515 // Make sure that application is notified with sufficient margin before underrun.
2516 // The client can divide the AudioTrack buffer into sub-buffers,
2517 // and expresses its desire to server as the notification frame count.
2518 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2519 size_t maxNotificationFrames;
2520 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2521 // notify every HAL buffer, regardless of the size of the track buffer
2522 maxNotificationFrames = mFrameCount;
2523 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002524 // Triple buffer the notification period for a triple buffered mixer period;
2525 // otherwise, double buffering for the notification period is fine.
2526 //
2527 // TODO: This should be moved to AudioTrack to modify the notification period
2528 // on AudioTrack::setBufferSizeInFrames() changes.
2529 const int nBuffering =
2530 (uint64_t{frameCount} * mSampleRate)
2531 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2532
Eric Laurent21da6472017-11-09 16:29:26 -08002533 maxNotificationFrames = frameCount / nBuffering;
2534 // If client requested a fast track but this was denied, then use the smaller maximum.
2535 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2536 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2537 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2538 maxNotificationFrames = maxNotificationFramesFastDenied;
2539 }
2540 }
2541 }
2542 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2543 if (notificationFrameCount == 0) {
2544 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2545 maxNotificationFrames, frameCount);
2546 } else {
2547 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2548 notificationFrameCount, maxNotificationFrames, frameCount);
2549 }
2550 notificationFrameCount = maxNotificationFrames;
2551 }
2552 }
2553
Glenn Kasten74935e42013-12-19 08:56:45 -08002554 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002555 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002556
Glenn Kastenc3df8382014-03-13 15:05:25 -07002557 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002558 case BIT_PERFECT:
2559 if (isBitPerfect) {
2560 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2561 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2562 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2563 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2564 mChannelMask);
2565 lStatus = BAD_VALUE;
2566 goto Exit;
2567 }
2568 }
2569 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002570
2571 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002572 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002573 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002574 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2575 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002576 sampleRate, format, channelMask, mOutput, mFormat);
2577 lStatus = BAD_VALUE;
2578 goto Exit;
2579 }
2580 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002581 break;
2582
2583 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002584 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002585 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2586 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002587 sampleRate, format, channelMask, mOutput, mFormat);
2588 lStatus = BAD_VALUE;
2589 goto Exit;
2590 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002591 break;
2592
2593 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002594 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002595 ALOGE("createTrack_l() Bad parameter: format %#x \""
2596 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002597 format, mOutput, mFormat);
2598 lStatus = BAD_VALUE;
2599 goto Exit;
2600 }
Andy Hungcd044842014-08-07 11:04:34 -07002601 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002602 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2603 lStatus = BAD_VALUE;
2604 goto Exit;
2605 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002606 break;
2607
Eric Laurent81784c32012-11-19 14:55:58 -08002608 }
2609
2610 lStatus = initCheck();
2611 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002612 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002613 goto Exit;
2614 }
2615
2616 { // scope for mLock
2617 Mutex::Autolock _l(mLock);
2618
2619 // all tracks in same audio session must share the same routing strategy otherwise
2620 // conflicts will happen when tracks are moved from one output to another by audio policy
2621 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002622 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002623 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002624 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002625 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002626 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002627 if (sessionId == t->sessionId() && strategy != actual) {
2628 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2629 strategy, actual);
2630 lStatus = BAD_VALUE;
2631 goto Exit;
2632 }
2633 }
2634 }
2635
yucliuc9c49cd2020-07-13 16:25:21 -07002636 // Set DIRECT flag if current thread is DirectOutputThread. This can
2637 // happen when the playback is rerouted to direct output thread by
2638 // dynamic audio policy.
2639 // Do NOT report the flag changes back to client, since the client
2640 // doesn't explicitly request a direct flag.
2641 audio_output_flags_t trackFlags = *flags;
2642 if (mType == DIRECT) {
2643 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2644 }
2645
Andy Hung3ff4b552023-06-26 19:20:57 -07002646 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002647 channelMask, frameCount,
2648 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002649 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung3ff4b552023-06-26 19:20:57 -07002650 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002651 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002652
Glenn Kasten03003332013-08-06 15:40:54 -07002653 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2654 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002655 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002656 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002657 goto Exit;
2658 }
2659 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002660 {
2661 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2662 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002663 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002664 }
2665 }
Eric Laurent81784c32012-11-19 14:55:58 -08002666
Andy Hungbd72c542023-06-20 18:56:17 -07002667 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002668 if (chain != 0) {
2669 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2670 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002671 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002672 chain->incTrackCnt();
2673 }
2674
Eric Laurent05067782016-06-01 18:27:28 -07002675 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002676 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2677 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2678 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002679 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002680 }
2681 }
2682
2683 lStatus = NO_ERROR;
2684
2685Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002686 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002687 return track;
2688}
2689
Andy Hung1bc088a2018-02-09 15:57:31 -08002690template<typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07002691ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002692{
Andy Hungc0691382018-09-12 18:01:57 -07002693 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002694 const ssize_t index = mTracks.remove(track);
2695 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002696 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002697 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002698 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002699 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002700 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002701 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002702 }
2703 return index;
2704}
2705
Andy Hung71742ab2023-07-07 13:47:37 -07002706uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002707{
2708 return latency;
2709}
2710
Andy Hung71742ab2023-07-07 13:47:37 -07002711uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002712{
2713 Mutex::Autolock _l(mLock);
2714 return latency_l();
2715}
Andy Hung71742ab2023-07-07 13:47:37 -07002716uint32_t PlaybackThread::latency_l() const
Eric Laurent81784c32012-11-19 14:55:58 -08002717{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002718 uint32_t latency;
2719 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2720 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002721 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002722 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002723}
2724
Andy Hung71742ab2023-07-07 13:47:37 -07002725void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002726{
2727 Mutex::Autolock _l(mLock);
2728 // Don't apply master volume in SW if our HAL can do it for us.
2729 if (mOutput && mOutput->audioHwDev &&
2730 mOutput->audioHwDev->canSetMasterVolume()) {
2731 mMasterVolume = 1.0;
2732 } else {
2733 mMasterVolume = value;
2734 }
2735}
2736
Andy Hung71742ab2023-07-07 13:47:37 -07002737void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002738{
2739 mMasterBalance.store(balance);
2740}
2741
Andy Hung71742ab2023-07-07 13:47:37 -07002742void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002743{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002744 if (isDuplicating()) {
2745 return;
2746 }
Eric Laurent81784c32012-11-19 14:55:58 -08002747 Mutex::Autolock _l(mLock);
2748 // Don't apply master mute in SW if our HAL can do it for us.
2749 if (mOutput && mOutput->audioHwDev &&
2750 mOutput->audioHwDev->canSetMasterMute()) {
2751 mMasterMute = false;
2752 } else {
2753 mMasterMute = muted;
2754 }
2755}
2756
Andy Hung71742ab2023-07-07 13:47:37 -07002757void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002758{
2759 Mutex::Autolock _l(mLock);
2760 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002761 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002762}
2763
Andy Hung71742ab2023-07-07 13:47:37 -07002764void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002765{
2766 Mutex::Autolock _l(mLock);
2767 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002768 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002769}
2770
Andy Hung71742ab2023-07-07 13:47:37 -07002771float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002772{
2773 Mutex::Autolock _l(mLock);
2774 return mStreamTypes[stream].volume;
2775}
2776
Andy Hung71742ab2023-07-07 13:47:37 -07002777void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002778{
2779 mOutput->stream->setVolume(left, right);
2780}
2781
Eric Laurent81784c32012-11-19 14:55:58 -08002782// addTrack_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002783status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Andy Hung71ba4b32022-10-06 12:09:49 -07002784NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent81784c32012-11-19 14:55:58 -08002785{
2786 status_t status = ALREADY_EXISTS;
2787
Eric Laurent81784c32012-11-19 14:55:58 -08002788 if (mActiveTracks.indexOf(track) < 0) {
2789 // the track is newly added, make sure it fills up all its
2790 // buffers before playing. This is to ensure the client will
2791 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002792 if (track->isExternalTrack()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002793 IAfTrackBase::track_state state = track->state();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002794 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002795 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002796 mLock.lock();
2797 // abort track was stopped/paused while we released the lock
Andy Hung3ff4b552023-06-26 19:20:57 -07002798 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002799 if (status == NO_ERROR) {
2800 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002801 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002802 mLock.lock();
2803 }
2804 return INVALID_OPERATION;
2805 }
2806 // abort if start is rejected by audio policy manager
2807 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002808 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2809 // current playback thread is reopened, which may happen when clients set preferred
2810 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2811 // immediately.
2812 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002813 }
2814#ifdef ADD_BATTERY_DATA
2815 // to track the speaker usage
2816 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2817#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002818 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002819 }
2820
Eric Laurent51716182016-02-29 18:00:56 -08002821 // set retry count for buffer fill
2822 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002823 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002824 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002825 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07002826 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002827 }
Andy Hung3ff4b552023-06-26 19:20:57 -07002828 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002829 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07002830 track->retryCount() = kMaxTrackStartupRetries;
2831 track->fillingStatus() =
2832 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002833 }
2834
Andy Hungbd72c542023-06-20 18:56:17 -07002835 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002836 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2837 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2838 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002839 // Unlock due to VibratorService will lock for this call and will
2840 // call Tracks.mute/unmute which also require thread's lock.
2841 mLock.unlock();
Andy Hung9554ec02023-07-20 21:23:42 -07002842 const os::HapticScale intensity = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002843 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002844 std::optional<media::AudioVibratorInfo> vibratorInfo;
2845 {
2846 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2847 // used to play this track.
Andy Hung2cbc2722023-07-17 17:05:00 -07002848 Mutex::Autolock _l(mAfThreadCallback->mutex());
2849 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002850 }
jiabin57303cc2018-12-18 15:45:57 -08002851 mLock.lock();
Simon Bowden62823412022-10-17 14:52:26 +00002852 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002853 if (vibratorInfo) {
2854 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2855 }
2856
jiabin57303cc2018-12-18 15:45:57 -08002857 // Haptic playback should be enabled by vibrator service.
2858 if (track->getHapticPlaybackEnabled()) {
2859 // Disable haptic playback of all active track to ensure only
2860 // one track playing haptic if current track should play haptic.
2861 for (const auto &t : mActiveTracks) {
2862 t->setHapticPlaybackEnabled(false);
2863 }
jiabin245cdd92018-12-07 17:55:15 -08002864 }
jiabine70bc7f2020-06-30 22:07:55 -07002865
2866 // Set haptic intensity for effect
2867 if (chain != nullptr) {
2868 chain->setHapticIntensity_l(track->id(), intensity);
2869 }
jiabin245cdd92018-12-07 17:55:15 -08002870 }
2871
Andy Hung3ff4b552023-06-26 19:20:57 -07002872 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002873 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002874 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002875 if (chain != 0) {
2876 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2877 track->sessionId());
2878 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002879 }
2880
Andy Hungc2b11cb2020-04-22 09:04:01 -07002881 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002882 status = NO_ERROR;
2883 }
2884
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002885 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002886 return status;
2887}
2888
Andy Hung71742ab2023-07-07 13:47:37 -07002889bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002890{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002891 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002892 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002893 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung3ff4b552023-06-26 19:20:57 -07002894 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002895 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002896 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002897 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002898 if (track->isPausePending()) {
2899 track->pauseAck();
2900 }
Andy Hung3ff4b552023-06-26 19:20:57 -07002901 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002902 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002903
2904 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002905}
2906
Andy Hung71742ab2023-07-07 13:47:37 -07002907void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002908{
2909 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002910
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002911 String8 result;
2912 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002913 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002914
Eric Laurent81784c32012-11-19 14:55:58 -08002915 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002916 {
2917 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2918 mAudioTrackCallbacks.erase(track);
2919 }
Eric Laurent81784c32012-11-19 14:55:58 -08002920 if (track->isFastTrack()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002921 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002922 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002923 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2924 mFastTrackAvailMask |= 1 << index;
2925 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung3ff4b552023-06-26 19:20:57 -07002926 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002927 }
Andy Hungbd72c542023-06-20 18:56:17 -07002928 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002929 if (chain != 0) {
2930 chain->decTrackCnt();
2931 }
2932}
2933
Andy Hung71742ab2023-07-07 13:47:37 -07002934String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08002935{
Eric Laurent81784c32012-11-19 14:55:58 -08002936 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002937 String8 out_s8;
2938 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2939 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002940 }
Andy Hung71ba4b32022-10-06 12:09:49 -07002941 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08002942}
2943
Andy Hung71742ab2023-07-07 13:47:37 -07002944status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002945 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002946 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002947 return NO_INIT;
2948 }
2949 return mOutput->stream->selectPresentation(presentationId, programId);
2950}
2951
Andy Hung71742ab2023-07-07 13:47:37 -07002952void PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002953 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002954 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07002955 sp<AudioIoDescriptor> desc;
2956 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002957 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002958 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002959 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002960 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002961 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
2962 mSampleRate, mFormat, mChannelMask,
2963 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
2964 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08002965 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002966 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002967 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07002968 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002969 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002970 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002971 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08002972 break;
2973 }
Andy Hung2cbc2722023-07-17 17:05:00 -07002974 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002975}
2976
Andy Hung71742ab2023-07-07 13:47:37 -07002977void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002978{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002979 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002980}
2981
Andy Hung71742ab2023-07-07 13:47:37 -07002982void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002983{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002984 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002985}
2986
Andy Hung71742ab2023-07-07 13:47:37 -07002987void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002988{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002989 mCallbackThread->setAsyncError();
2990}
2991
Andy Hung71742ab2023-07-07 13:47:37 -07002992void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08002993 const std::basic_string<uint8_t>& metadataBs)
2994{
Andy Hung71742ab2023-07-07 13:47:37 -07002995 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08002996 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hung71742ab2023-07-07 13:47:37 -07002997 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08002998 if (playbackThread == nullptr) {
2999 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3000 return;
3001 }
3002
jiabinf6eb4c32020-02-25 14:06:25 -08003003 audio_utils::metadata::Data metadata =
3004 audio_utils::metadata::dataFromByteString(metadataBs);
3005 if (metadata.empty()) {
3006 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3007 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3008 (int)metadataBs.size());
3009 return;
3010 }
3011
3012 audio_utils::metadata::ByteString metaDataStr =
3013 audio_utils::metadata::byteStringFromData(metadata);
3014 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
3015 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07003016 for (const auto& callbackPair : mAudioTrackCallbacks) {
3017 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003018 }
3019 }).detach();
3020}
3021
Andy Hung71742ab2023-07-07 13:47:37 -07003022void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003023{
3024 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003025 // reject out of sequence requests
3026 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3027 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003028 mWaitWorkCV.signal();
3029 }
3030}
3031
Andy Hung71742ab2023-07-07 13:47:37 -07003032void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003033{
3034 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003035 // reject out of sequence requests
3036 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003037 // Register discontinuity when HW drain is completed because that can cause
3038 // the timestamp frame position to reset to 0 for direct and offload threads.
3039 // (Out of sequence requests are ignored, since the discontinuity would be handled
3040 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003041 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003042 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003043 mWaitWorkCV.signal();
3044 }
3045}
3046
Andy Hung71742ab2023-07-07 13:47:37 -07003047void PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003048{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003049 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003050 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3051 mSampleRate = audioConfig.sample_rate;
3052 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003053 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003054 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003055 }
Andy Hung71742ab2023-07-07 13:47:37 -07003056 if (hasMixer() && !AudioFlinger::isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003057 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3058 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003059 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003060
3061 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3062 mMixerChannelMask = mChannelMask;
3063 }
3064
Andy Hunge5412692014-05-16 11:25:07 -07003065 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003066 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003067
Eric Laurentf1f22e72021-07-13 14:04:14 +02003068 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3069
Phil Burkca5e6142015-07-14 09:42:29 -07003070 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003071 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003072 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003073 // Get format from the shim, which will be different than the HAL format
3074 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003075 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003076 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003077 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003078 }
Andy Hung71742ab2023-07-07 13:47:37 -07003079 if (hasMixer() && !AudioFlinger::isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003080 LOG_FATAL("HAL format %#x not supported for mixed output",
3081 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003082 }
Phil Burk062e67a2015-02-11 13:40:50 -08003083 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003084 result = mOutput->stream->getBufferSize(&mBufferSize);
3085 LOG_ALWAYS_FATAL_IF(result != OK,
3086 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003087 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003088 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003089 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003090 mFrameCount);
3091 }
3092
Eric Laurentd1f69b02014-12-15 14:33:13 -08003093 mHwSupportsPause = false;
3094 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003095 bool supportsPause = false, supportsResume = false;
3096 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3097 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003098 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003099 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003100 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003101 } else if (supportsResume) {
3102 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003103 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003104 }
3105 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003106 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3107 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3108 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003109
Andy Hungfbfc3952015-01-15 13:33:51 -08003110 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3111 // For best precision, we use float instead of the associated output
3112 // device format (typically PCM 16 bit).
3113
3114 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3115 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3116 mBufferSize = mFrameSize * mFrameCount;
3117
3118 // TODO: We currently use the associated output device channel mask and sample rate.
3119 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3120 // (if a valid mask) to avoid premature downmix.
3121 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3122 // instead of the output device sample rate to avoid loss of high frequency information.
3123 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3124 }
3125
Andy Hung09a50072014-02-27 14:30:47 -08003126 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003127 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003128 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003129 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3130 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003131 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3132 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003133
Eric Laurent81784c32012-11-19 14:55:58 -08003134 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3135 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3136 maxNormalFrameCount = maxNormalFrameCount & ~15;
3137 if (maxNormalFrameCount < minNormalFrameCount) {
3138 maxNormalFrameCount = minNormalFrameCount;
3139 }
3140 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3141 if (multiplier <= 1.0) {
3142 multiplier = 1.0;
3143 } else if (multiplier <= 2.0) {
3144 if (2 * mFrameCount <= maxNormalFrameCount) {
3145 multiplier = 2.0;
3146 } else {
3147 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3148 }
3149 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003150 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003151 }
3152 }
3153 mNormalFrameCount = multiplier * mFrameCount;
3154 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003155 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003156 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3157 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003158 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003159 mNormalFrameCount);
3160
Andy Hung08fb1742015-05-31 23:22:10 -07003161 // Check if we want to throttle the processing to no more than 2x normal rate
3162 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003163 mThreadThrottleTimeMs = 0;
3164 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003165 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3166
Andy Hung010a1a12014-03-13 13:57:33 -07003167 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3168 // Originally this was int16_t[] array, need to remove legacy implications.
3169 free(mSinkBuffer);
3170 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003171
Andy Hung5b10a202014-03-13 13:59:29 -07003172 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3173 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3174 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003175 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003176
Andy Hung69aed5f2014-02-25 17:24:40 -08003177 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3178 // drives the output.
3179 free(mMixerBuffer);
3180 mMixerBuffer = NULL;
3181 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003182 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003183 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003184 * audio_bytes_per_sample(mMixerBufferFormat);
3185 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3186 }
Andy Hung98ef9782014-03-04 14:46:50 -08003187 free(mEffectBuffer);
3188 mEffectBuffer = NULL;
3189 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003190 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003191 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003192 * audio_bytes_per_sample(mEffectBufferFormat);
3193 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3194 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003195
Eric Laurentb62d0362021-10-26 17:40:18 +02003196 if (mType == SPATIALIZER) {
3197 free(mPostSpatializerBuffer);
3198 mPostSpatializerBuffer = nullptr;
3199 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3200 * audio_bytes_per_sample(mEffectBufferFormat);
3201 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3202 }
3203
Mikhail Naganov55773032020-10-01 15:08:13 -07003204 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3205 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003206 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3207 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003208 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003209
Eric Laurent81784c32012-11-19 14:55:58 -08003210 // force reconfiguration of effect chains and engines to take new buffer size and audio
3211 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003212 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003213 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3214 // matter.
3215 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
Andy Hungbd72c542023-06-20 18:56:17 -07003216 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003217 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung2cbc2722023-07-17 17:05:00 -07003218 mAfThreadCallback->moveEffectChain_l(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003219 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003220 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003221
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003222 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003223 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003224 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3225 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3226 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3227 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3228 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3229 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3230 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3231 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3232 (int32_t)mHapticChannelMask)
3233 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3234 (int32_t)mHapticChannelCount)
3235 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3236 formatToString(mHALFormat).c_str())
3237 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3238 (int32_t)mFrameCount) // sic - added HAL
3239 ;
3240 uint32_t latencyMs;
3241 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3242 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3243 }
3244 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003245}
3246
Andy Hung71742ab2023-07-07 13:47:37 -07003247ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003248{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003249 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003250 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003251 }
3252 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003253 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung3ff4b552023-06-26 19:20:57 -07003254 for (const sp<IAfTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -07003255 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003256 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003257 }
Kevin Rocard12381092018-04-11 09:19:59 -07003258 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003259 MetadataUpdate change;
3260 change.playbackMetadataUpdate = metadata.tracks;
3261 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003262}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003263
Andy Hung71742ab2023-07-07 13:47:37 -07003264void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003265 const StreamOutHalInterface::SourceMetadata& metadata)
3266{
3267 mOutput->stream->updateSourceMetadata(metadata);
3268};
3269
Andy Hung71742ab2023-07-07 13:47:37 -07003270status_t PlaybackThread::getRenderPosition(
Andy Hung4989d312023-06-29 21:19:25 -07003271 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003272{
3273 if (halFrames == NULL || dspFrames == NULL) {
3274 return BAD_VALUE;
3275 }
3276 Mutex::Autolock _l(mLock);
3277 if (initCheck() != NO_ERROR) {
3278 return INVALID_OPERATION;
3279 }
Andy Hung818e7a32016-02-16 18:08:07 -08003280 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003281 *halFrames = framesWritten;
3282
3283 if (isSuspended()) {
3284 // return an estimation of rendered frames when the output is suspended
3285 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003286 *dspFrames = (uint32_t)
3287 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003288 return NO_ERROR;
3289 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003290 status_t status;
3291 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003292 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003293 *dspFrames = (size_t)frames;
3294 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003295 }
3296}
3297
Andy Hung71742ab2023-07-07 13:47:37 -07003298product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003299{
3300 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3301 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3302 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003303 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003304 }
3305 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003306 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003307 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003308 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003309 }
3310 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003311 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003312}
3313
3314
Andy Hung71742ab2023-07-07 13:47:37 -07003315AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003316{
3317 Mutex::Autolock _l(mLock);
3318 return mOutput;
3319}
3320
Andy Hung71742ab2023-07-07 13:47:37 -07003321AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003322{
3323 Mutex::Autolock _l(mLock);
3324 AudioStreamOut *output = mOutput;
3325 mOutput = NULL;
3326 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3327 // must push a NULL and wait for ack
3328 mOutputSink.clear();
3329 mPipeSink.clear();
3330 mNormalSink.clear();
3331 return output;
3332}
3333
3334// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hung71742ab2023-07-07 13:47:37 -07003335sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003336{
3337 if (mOutput == NULL) {
3338 return NULL;
3339 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003340 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003341}
3342
Andy Hung71742ab2023-07-07 13:47:37 -07003343uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003344{
3345 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3346}
3347
Andy Hung71742ab2023-07-07 13:47:37 -07003348status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003349{
3350 if (!isValidSyncEvent(event)) {
3351 return BAD_VALUE;
3352 }
3353
3354 Mutex::Autolock _l(mLock);
3355
3356 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003357 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003358 if (event->triggerSession() == track->sessionId()) {
3359 (void) track->setSyncEvent(event);
3360 return NO_ERROR;
3361 }
3362 }
3363
3364 return NAME_NOT_FOUND;
3365}
3366
Andy Hung71742ab2023-07-07 13:47:37 -07003367bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003368{
3369 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3370}
3371
Andy Hung71742ab2023-07-07 13:47:37 -07003372void PlaybackThread::threadLoop_removeTracks(
Andy Hung3ff4b552023-06-26 19:20:57 -07003373 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003374{
Andy Hungfe726a62018-09-27 15:17:25 -07003375 // Miscellaneous track cleanup when removed from the active list,
3376 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003377#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003378 for (const auto& track : tracksToRemove) {
3379 if (track->isExternalTrack()) {
3380 // to track the speaker usage
3381 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003382 }
3383 }
Andy Hungfe726a62018-09-27 15:17:25 -07003384#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003385}
3386
Andy Hung71742ab2023-07-07 13:47:37 -07003387void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003388{
3389 if (!mMasterMute) {
3390 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003391 if (mOutDeviceTypeAddrs.empty()) {
3392 ALOGD("ro.audio.silent is ignored since no output device is set");
3393 return;
3394 }
jiabinc52b1ff2019-10-31 17:20:42 -07003395 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003396 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3397 return;
3398 }
Eric Laurent81784c32012-11-19 14:55:58 -08003399 if (property_get("ro.audio.silent", value, "0") > 0) {
3400 char *endptr;
3401 unsigned long ul = strtoul(value, &endptr, 0);
3402 if (*endptr == '\0' && ul != 0) {
3403 ALOGD("Silence is golden");
3404 // The setprop command will not allow a property to be changed after
3405 // the first time it is set, so we don't have to worry about un-muting.
3406 setMasterMute_l(true);
3407 }
3408 }
3409 }
3410}
3411
3412// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung71742ab2023-07-07 13:47:37 -07003413ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003414{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003415 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003416 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003417 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003418 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003419
3420 // If an NBAIO sink is present, use it to write the normal mixer's submix
3421 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003422
Andy Hung010a1a12014-03-13 13:57:33 -07003423 const size_t count = mBytesRemaining / mFrameSize;
3424
Simon Wilson2d590962012-11-29 15:18:50 -08003425 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003426 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung01b29482023-07-19 16:22:58 -07003427 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003428 if (screenState != mScreenState) {
3429 mScreenState = screenState;
3430 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3431 if (pipe != NULL) {
3432 pipe->setAvgFrames((mScreenState & 1) ?
3433 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3434 }
3435 }
Andy Hung010a1a12014-03-13 13:57:33 -07003436 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003437 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003438
Eric Laurent81784c32012-11-19 14:55:58 -08003439 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003440 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003441
Andy Hung8946a282018-04-19 20:04:56 -07003442#ifdef TEE_SINK
3443 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3444#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003445 } else {
3446 bytesWritten = framesWritten;
3447 }
3448 // otherwise use the HAL / AudioStreamOut directly
3449 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003450 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003451
Eric Laurentbfb1b832013-01-07 09:53:42 -08003452 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003453 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3454 mWriteAckSequence += 2;
3455 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003456 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003457 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003458 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003459 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003460 // FIXME We should have an implementation of timestamps for direct output threads.
3461 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003462 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003463 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003464
Eric Laurentbfb1b832013-01-07 09:53:42 -08003465 if (mUseAsyncWrite &&
3466 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3467 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003468 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003469 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003470 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003471 }
Eric Laurent81784c32012-11-19 14:55:58 -08003472 }
3473
Eric Laurent81784c32012-11-19 14:55:58 -08003474 mNumWrites++;
3475 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003476 if (mStandby) {
3477 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003478 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003479 mStandby = false;
3480 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003481 return bytesWritten;
3482}
3483
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003484// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07003485void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003486 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003487{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003488 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003489 if (outputSink != nullptr) {
3490 outputSink->startMelComputation(processor);
3491 }
Vlad Popab042ee62022-10-20 18:05:00 +02003492}
3493
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003494// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07003495void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003496{
3497 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003498 if (outputSink != nullptr) {
3499 outputSink->stopMelComputation();
3500 }
Vlad Popab042ee62022-10-20 18:05:00 +02003501}
3502
Andy Hung71742ab2023-07-07 13:47:37 -07003503void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003504{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003505 bool supportsDrain = false;
3506 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003507 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3508 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003509 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3510 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003511 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003512 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003513 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003514 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003515 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003516 }
3517}
3518
Andy Hung71742ab2023-07-07 13:47:37 -07003519void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003520{
Eric Laurent275e8e92014-11-30 15:14:47 -08003521 {
3522 Mutex::Autolock _l(mLock);
3523 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003524 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003525 track->invalidate();
3526 }
Andy Hungdae27702016-10-31 14:01:16 -07003527 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3528 // After we exit there are no more track changes sent to BatteryNotifier
3529 // because that requires an active threadLoop.
3530 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3531 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003532 }
Eric Laurent81784c32012-11-19 14:55:58 -08003533}
3534
3535/*
3536The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003537 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003538 - mActiveSleepTimeUs from activeSleepTimeUs()
3539 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003540 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3541 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003542 - maxPeriod from frame count and sample rate (MIXER only)
3543
3544The parameters that affect these derived values are:
3545 - frame count
3546 - frame size
3547 - sample rate
3548 - device type: A2DP or not
3549 - device latency
3550 - format: PCM or not
3551 - active sleep time
3552 - idle sleep time
3553*/
3554
Andy Hung71742ab2023-07-07 13:47:37 -07003555void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003556{
Andy Hung25c2dac2014-02-27 14:56:00 -08003557 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003558 mActiveSleepTimeUs = activeSleepTimeUs();
3559 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003560
Eric Laurent52568142022-10-28 11:23:28 +02003561 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
Carter Hsu0ca47c22023-06-02 18:01:45 +08003562
Eric Laurent42537be2016-01-08 17:16:42 -08003563 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3564 // truncating audio when going to standby.
jiabinc52b1ff2019-10-31 17:20:42 -07003565 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003566 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3567 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3568 }
3569 }
Eric Laurent81784c32012-11-19 14:55:58 -08003570}
3571
Andy Hung71742ab2023-07-07 13:47:37 -07003572bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003573{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003574 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003575 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003576 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003577 size_t size = mTracks.size();
3578 for (size_t i = 0; i < size; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003579 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003580 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003581 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003582 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003583 }
3584 }
Eric Laurent13084622016-05-17 10:51:49 -07003585 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003586}
3587
Andy Hung71742ab2023-07-07 13:47:37 -07003588void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003589{
3590 Mutex::Autolock _l(mLock);
3591 invalidateTracks_l(streamType);
3592}
3593
Andy Hung71742ab2023-07-07 13:47:37 -07003594void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003595 Mutex::Autolock _l(mLock);
3596 invalidateTracks_l(portIds);
3597}
3598
Andy Hung71742ab2023-07-07 13:47:37 -07003599bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003600 bool trackMatch = false;
3601 const size_t size = mTracks.size();
3602 for (size_t i = 0; i < size; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003603 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003604 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3605 t->invalidate();
3606 portIds.erase(t->portId());
3607 trackMatch = true;
3608 }
3609 if (portIds.empty()) {
3610 break;
3611 }
3612 }
3613 return trackMatch;
3614}
3615
jiabinf042b9b2021-05-07 23:46:28 +00003616// getTrackById_l must be called with holding thread lock
Andy Hung71742ab2023-07-07 13:47:37 -07003617IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003618 audio_port_handle_t trackPortId) {
3619 for (size_t i = 0; i < mTracks.size(); i++) {
3620 if (mTracks[i]->portId() == trackPortId) {
3621 return mTracks[i].get();
3622 }
3623 }
3624 return nullptr;
3625}
3626
Andy Hung71742ab2023-07-07 13:47:37 -07003627status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003628{
Glenn Kastend848eb42016-03-08 13:42:11 -08003629 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003630 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003631 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003632
Andy Hungd3639922022-04-28 18:00:49 -07003633 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003634 if (!audio_is_global_session(session)) {
3635 // player sessions on a spatializer output will use a dedicated input buffer and
3636 // will either output multi channel to mEffectBuffer if the track is spatilaized
3637 // or stereo to mPostSpatializerBuffer if not spatialized.
3638 uint32_t channelMask;
3639 bool isSessionSpatialized =
3640 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3641 if (isSessionSpatialized) {
3642 channelMask = mMixerChannelMask;
3643 } else {
3644 channelMask = mChannelMask;
3645 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003646 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003647 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung2cbc2722023-07-17 17:05:00 -07003648 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003649 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003650 &halInBuffer);
3651 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003652
Andy Hung2cbc2722023-07-17 17:05:00 -07003653 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003654 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3655 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3656 &halOutBuffer);
3657 if (result != OK) return result;
3658
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003659 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003660
Mikhail Naganov022b9952017-01-04 16:36:51 -08003661 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3662 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003663 } else {
3664 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3665 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3666 // mPostSpatializerBuffer as output buffer
3667 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung2cbc2722023-07-17 17:05:00 -07003668 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003669 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3670 if (result != OK) return result;
Andy Hung2cbc2722023-07-17 17:05:00 -07003671 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003672 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3673 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003674
Eric Laurentb62d0362021-10-26 17:40:18 +02003675 if (session == AUDIO_SESSION_DEVICE) {
3676 halInBuffer = halOutBuffer;
3677 }
3678 }
3679 } else {
Andy Hung2cbc2722023-07-17 17:05:00 -07003680 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003681 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3682 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3683 &halInBuffer);
3684 if (result != OK) return result;
3685 halOutBuffer = halInBuffer;
3686 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3687 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003688 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003689 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003690 // Only one effect chain can be present in direct output thread and it uses
3691 // the sink buffer as input
3692 if (mType != DIRECT) {
3693 size_t numSamples = mNormalFrameCount
3694 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3695 + mHapticChannelCount);
Andy Hung2cbc2722023-07-17 17:05:00 -07003696 const status_t allocateStatus =
3697 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003698 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003699 &halInBuffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07003700 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003701
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003702 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003703 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3704 buffer, session);
3705 }
3706 }
3707 }
3708
3709 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003710 // Attach all tracks with same session ID to this chain.
3711 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003712 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003713 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003714 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3715 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003716 track->setMainBuffer(buffer);
3717 chain->incTrackCnt();
3718 }
3719 }
3720
3721 // indicate all active tracks in the chain
Andy Hung3ff4b552023-06-26 19:20:57 -07003722 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003723 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003724 ALOGV("addEffectChain_l() activating track %p on session %d",
3725 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003726 chain->incActiveTrackCnt();
3727 }
3728 }
3729 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003730
Eric Laurentaaa44472014-09-12 17:41:50 -07003731 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003732 chain->setInBuffer(halInBuffer);
3733 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003734 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3735 // chains list in order to be processed last as it contains output device effects.
3736 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3737 // processing effects specific to an output stream before effects applied to all streams
3738 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003739 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3740 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003741 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003742 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003743 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003744 // Effect chain for other sessions are inserted at beginning of effect
3745 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003746 // sessions is not important.
3747 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003748 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3749 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003750 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003751 size_t size = mEffectChains.size();
3752 size_t i = 0;
3753 for (i = 0; i < size; i++) {
3754 if (mEffectChains[i]->sessionId() < session) {
3755 break;
3756 }
3757 }
3758 mEffectChains.insertAt(chain, i);
3759 checkSuspendOnAddEffectChain_l(chain);
3760
3761 return NO_ERROR;
3762}
3763
Andy Hung71742ab2023-07-07 13:47:37 -07003764size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003765{
Glenn Kastend848eb42016-03-08 13:42:11 -08003766 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003767
3768 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3769
3770 for (size_t i = 0; i < mEffectChains.size(); i++) {
3771 if (chain == mEffectChains[i]) {
3772 mEffectChains.removeAt(i);
3773 // detach all active tracks from the chain
Andy Hung3ff4b552023-06-26 19:20:57 -07003774 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003775 if (session == track->sessionId()) {
3776 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3777 chain.get(), session);
3778 chain->decActiveTrackCnt();
3779 }
3780 }
3781
3782 // detach all tracks with same session ID from this chain
Andy Hung71ba4b32022-10-06 12:09:49 -07003783 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003784 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003785 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003786 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003787 chain->decTrackCnt();
3788 }
3789 }
3790 break;
3791 }
3792 }
3793 return mEffectChains.size();
3794}
3795
Andy Hung71742ab2023-07-07 13:47:37 -07003796status_t PlaybackThread::attachAuxEffect(
Andy Hung3ff4b552023-06-26 19:20:57 -07003797 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003798{
3799 Mutex::Autolock _l(mLock);
3800 return attachAuxEffect_l(track, EffectId);
3801}
3802
Andy Hung71742ab2023-07-07 13:47:37 -07003803status_t PlaybackThread::attachAuxEffect_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07003804 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003805{
3806 status_t status = NO_ERROR;
3807
3808 if (EffectId == 0) {
3809 track->setAuxBuffer(0, NULL);
3810 } else {
3811 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hungbd72c542023-06-20 18:56:17 -07003812 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003813 if (effect != 0) {
3814 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3815 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3816 } else {
3817 status = INVALID_OPERATION;
3818 }
3819 } else {
3820 status = BAD_VALUE;
3821 }
3822 }
3823 return status;
3824}
3825
Andy Hung71742ab2023-07-07 13:47:37 -07003826void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003827{
3828 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003829 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003830 if (track->auxEffectId() == effectId) {
3831 attachAuxEffect_l(track, 0);
3832 }
3833 }
3834}
3835
Andy Hung71742ab2023-07-07 13:47:37 -07003836bool PlaybackThread::threadLoop()
Andy Hung71ba4b32022-10-06 12:09:49 -07003837NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003838{
Andy Hung4bf583b2023-05-30 18:10:23 -07003839 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003840
Andy Hung3ff4b552023-06-26 19:20:57 -07003841 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003842
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003843 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003844 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003845
3846 // MIXER
3847 nsecs_t lastWarning = 0;
3848
3849 // DUPLICATING
3850 // FIXME could this be made local to while loop?
3851 writeFrames = 0;
3852
3853 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003854 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003855
Andy Hungd3639922022-04-28 18:00:49 -07003856 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003857 sleepTimeShift = 0;
3858 }
3859
3860 CpuStats cpuStats;
3861 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3862
3863 acquireWakeLock();
3864
Glenn Kasteneef598c2017-04-03 14:41:13 -07003865 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3866 // thread associated with this PlaybackThread.
3867 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3868 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003869 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3870 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003871 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003872 const char *logString = NULL;
3873
rago1bb90822017-05-02 18:31:48 -07003874 // Estimated time for next buffer to be written to hal. This is used only on
3875 // suspended mode (for now) to help schedule the wait time until next iteration.
3876 nsecs_t timeLoopNextNs = 0;
3877
Eric Laurent664539d2013-09-23 18:24:31 -07003878 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003879
Andy Hung2dbffc22018-08-08 18:50:41 -07003880 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003881
Eric Laurentb3f315a2021-07-13 15:09:05 +02003882 sendCheckOutputStageEffectsEvent();
3883
Andy Hung446f4df2019-02-21 12:26:41 -08003884 // loopCount is used for statistics and diagnostics.
3885 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003886 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003887 // Log merge requests are performed during AudioFlinger binder transactions, but
3888 // that does not cover audio playback. It's requested here for that reason.
Andy Hung2cbc2722023-07-17 17:05:00 -07003889 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003890
Eric Laurent81784c32012-11-19 14:55:58 -08003891 cpuStats.sample(myName);
3892
Andy Hungbd72c542023-06-20 18:56:17 -07003893 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003894 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003895 bool isHapticSessionSpatialized = false;
Andy Hung3ff4b552023-06-26 19:20:57 -07003896 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003897
Andy Hung2dbffc22018-08-08 18:50:41 -07003898 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3899 //
jiabinc52b1ff2019-10-31 17:20:42 -07003900 // Note: we access outDeviceTypes() outside of mLock.
3901 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003902 // Here, we try for the AF lock, but do not block on it as the latency
3903 // is more informational.
Andy Hung2cbc2722023-07-17 17:05:00 -07003904 if (mAfThreadCallback->mutex().tryLock() == NO_ERROR) {
Andy Hungd63e79d2023-07-13 16:52:46 -07003905 std::vector<SoftwarePatch> swPatches;
Andy Hung71ba4b32022-10-06 12:09:49 -07003906 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07003907 status_t status = INVALID_OPERATION;
3908 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung2cbc2722023-07-17 17:05:00 -07003909 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungd63e79d2023-07-13 16:52:46 -07003910 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07003911 && swPatches.size() > 0) {
3912 status = swPatches[0].getLatencyMs_l(&latencyMs);
3913 downstreamPatchHandle = swPatches[0].getPatchHandle();
3914 }
3915 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003916 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003917 lastDownstreamPatchHandle = downstreamPatchHandle;
3918 }
3919 if (status == OK) {
3920 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003921 // latency of 5 seconds).
3922 const double minLatency = 0., maxLatency = 5000.;
3923 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003924 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003925 } else {
3926 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung71ba4b32022-10-06 12:09:49 -07003927 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07003928 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003929 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003930 }
Andy Hung2cbc2722023-07-17 17:05:00 -07003931 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07003932 }
3933 } else {
3934 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3935 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003936 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003937 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3938 }
3939 }
3940
Eric Laurentb3f315a2021-07-13 15:09:05 +02003941 if (mCheckOutputStageEffects.exchange(false)) {
3942 checkOutputStageEffects();
3943 }
3944
Vlad Popa7e81cea2023-01-19 16:34:16 +01003945 MetadataUpdate metadataUpdate;
Eric Laurent81784c32012-11-19 14:55:58 -08003946 { // scope for mLock
3947
3948 Mutex::Autolock _l(mLock);
3949
Eric Laurent021cf962014-05-13 10:18:14 -07003950 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003951 if (mCheckOutputStageEffects.load()) {
3952 continue;
3953 }
Eric Laurent10351942014-05-08 18:49:52 -07003954
Glenn Kasteneef598c2017-04-03 14:41:13 -07003955 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003956 if (logString != NULL) {
3957 mNBLogWriter->logTimestamp();
3958 mNBLogWriter->log(logString);
3959 logString = NULL;
3960 }
3961
Dean Wheatley12473e92021-03-18 23:00:55 +11003962 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003963
Eric Laurent81784c32012-11-19 14:55:58 -08003964 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003965 if (mSignalPending) {
3966 // A signal was raised while we were unlocked
3967 mSignalPending = false;
3968 } else if (waitingAsyncCallback_l()) {
3969 if (exitPending()) {
3970 break;
3971 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003972 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003973 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003974 releaseWakeLock_l();
3975 released = true;
3976 }
Andy Hung10cbff12017-02-21 17:30:14 -08003977
3978 const int64_t waitNs = computeWaitTimeNs_l();
3979 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3980 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3981 if (status == TIMED_OUT) {
3982 mSignalPending = true; // if timeout recheck everything
3983 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003984 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003985 if (released) {
3986 acquireWakeLock_l();
3987 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003988 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3989 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003990
3991 continue;
3992 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003993 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003994 isSuspended()) {
3995 // put audio hardware into standby after short delay
3996 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003997
3998 threadLoop_standby();
3999
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004000 // This is where we go into standby
4001 if (!mStandby) {
4002 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004003 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004004 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004005 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004006 }
Andy Hungd0979812019-02-21 15:51:44 -08004007 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004008 }
4009
Eric Tan39ec8d62018-07-24 09:49:29 -07004010 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004011 // we're about to wait, flush the binder command buffer
4012 IPCThreadState::self()->flushCommands();
4013
4014 clearOutputTracks();
4015
4016 if (exitPending()) {
4017 break;
4018 }
4019
4020 releaseWakeLock_l();
4021 // wait until we have something to do...
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00004022 ALOGV("%s going to sleep", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004023 mWaitWorkCV.wait(mLock);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00004024 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004025 acquireWakeLock_l();
4026
4027 mMixerStatus = MIXER_IDLE;
4028 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4029 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004030 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004031 checkSilentMode_l();
4032
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004033 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4034 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004035 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004036 sleepTimeShift = 0;
4037 }
4038
4039 continue;
4040 }
4041 }
Eric Laurent81784c32012-11-19 14:55:58 -08004042 // mMixerStatusIgnoringFastTracks is also updated internally
4043 mMixerStatus = prepareTracks_l(&tracksToRemove);
4044
Andy Hungdae27702016-10-31 14:01:16 -07004045 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004046
Vlad Popa7e81cea2023-01-19 16:34:16 +01004047 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004048
Eric Laurent81784c32012-11-19 14:55:58 -08004049 // prevent any changes in effect chain list and in each effect chain
4050 // during mixing and effect process as the audio buffers could be deleted
4051 // or modified if an effect is created or deleted
4052 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004053
4054 // Determine which session to pick up haptic data.
4055 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004056 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004057 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004058 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004059 for (const auto& track : mActiveTracks) {
Andy Hungbd72c542023-06-20 18:56:17 -07004060 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004061 if (effectChain != nullptr
4062 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004063 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004064 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004065 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004066 break;
4067 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004068 if (activeHapticSessionId == AUDIO_SESSION_NONE
4069 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004070 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004071 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004072 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004073 }
4074 }
4075 }
4076
Andy Hungc1646382019-04-30 16:12:10 -07004077 // Acquire a local copy of active tracks with lock (release w/o lock).
4078 //
4079 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4080 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4081 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4082 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent6f9534f2022-05-03 18:15:04 +02004083
4084 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004085
Jiabin Huangfb476842022-12-06 03:18:10 +00004086 for (const auto &track : mActiveTracks ) {
4087 track->updateTeePatches();
4088 }
4089
Eric Laurent19952e12023-04-20 10:08:29 +02004090 // signal actual start of output stream when the render position reported by the kernel
4091 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004092 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4093 && (mKernelPositionOnStandby
4094 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004095 mHalStarted = true;
4096 mWaitHalStartCV.broadcast();
4097 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004098 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004099
Eric Laurentbfb1b832013-01-07 09:53:42 -08004100 if (mBytesRemaining == 0) {
4101 mCurrentWriteLength = 0;
4102 if (mMixerStatus == MIXER_TRACKS_READY) {
4103 // threadLoop_mix() sets mCurrentWriteLength
4104 threadLoop_mix();
4105 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4106 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004107 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004108 // must be written to HAL
4109 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004110 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004111 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004112
4113 // Tally underrun frames as we are inserting 0s here.
4114 for (const auto& track : activeTracks) {
Andy Hung3ff4b552023-06-26 19:20:57 -07004115 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004116 && !track->isStopped()
4117 && !track->isPaused()
4118 && !track->isTerminated()) {
4119 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4120 __func__, track->id(), track->getTrackStateAsString(),
4121 mNormalFrameCount);
Andy Hung3ff4b552023-06-26 19:20:57 -07004122 track->audioTrackServerProxy()->tallyUnderrunFrames(
4123 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004124 }
4125 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004126 }
4127 }
Andy Hung98ef9782014-03-04 14:46:50 -08004128 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004129 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004130 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004131 // or mSinkBuffer (if there are no effects and there is no data already copied to
4132 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004133 //
4134 // This is done pre-effects computation; if effects change to
4135 // support higher precision, this needs to move.
4136 //
4137 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004138 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004139 uint32_t mixerChannelCount = mEffectBufferValid ?
4140 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004141 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004142 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4143 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4144
David Li88ee0902022-06-22 10:01:21 +08004145 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4146 // do these processes after effects are applied.
4147 if (!mEffectBufferValid) {
4148 // mono blend occurs for mixer threads only (not direct or offloaded)
4149 // and is handled here if we're going directly to the sink.
4150 if (requireMonoBlend()) {
4151 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4152 mNormalFrameCount, true /*limit*/);
4153 }
Andy Hung2ddee192015-12-18 17:34:44 -08004154
David Li88ee0902022-06-22 10:01:21 +08004155 if (!hasFastMixer()) {
4156 // Balance must take effect after mono conversion.
4157 // We do it here if there is no FastMixer.
4158 // mBalance detects zero balance within the class for speed
4159 // (not needed here).
4160 mBalance.setBalance(mMasterBalance.load());
4161 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4162 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004163 }
4164
Andy Hung98ef9782014-03-04 14:46:50 -08004165 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004166 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004167
4168 // If we're going directly to the sink and there are haptic channels,
4169 // we should adjust channels as the sample data is partially interleaved
4170 // in this case.
4171 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4172 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4173 mChannelCount + mHapticChannelCount,
4174 audio_bytes_per_sample(format),
4175 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4176 }
Andy Hung98ef9782014-03-04 14:46:50 -08004177 }
4178
Eric Laurentbfb1b832013-01-07 09:53:42 -08004179 mBytesRemaining = mCurrentWriteLength;
4180 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004181 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4182 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4183 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4184 mBytesWritten += mBytesRemaining;
4185 mFramesWritten += framesRemaining;
4186 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004187 mBytesRemaining = 0;
4188 }
Eric Laurent81784c32012-11-19 14:55:58 -08004189
Eric Laurentbfb1b832013-01-07 09:53:42 -08004190 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004191 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004192 for (size_t i = 0; i < effectChains.size(); i ++) {
4193 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004194 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004195 if (activeHapticSessionId != AUDIO_SESSION_NONE
4196 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004197 // Haptic data is active in this case, copy it directly from
4198 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004199 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4200 audio_channel_count_from_out_mask(mMixerChannelMask) :
4201 mChannelCount;
4202 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4203 hapticSessionChannelCount = mChannelCount;
4204 }
4205
jiabin47affe52019-04-04 18:02:07 -07004206 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004207 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004208 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004209 memcpy_by_audio_format(
4210 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004211 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004212 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004213 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004214 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004215 }
Eric Laurent81784c32012-11-19 14:55:58 -08004216 }
4217 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004218 // Process effect chains for offloaded thread even if no audio
4219 // was read from audio track: process only updates effect state
4220 // and thus does have to be synchronized with audio writes but may have
4221 // to be called while waiting for async write callback
4222 if (mType == OFFLOAD) {
4223 for (size_t i = 0; i < effectChains.size(); i ++) {
4224 effectChains[i]->process_l();
4225 }
4226 }
Eric Laurent81784c32012-11-19 14:55:58 -08004227
Andy Hung98ef9782014-03-04 14:46:50 -08004228 // Only if the Effects buffer is enabled and there is data in the
4229 // Effects buffer (buffer valid), we need to
4230 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004231 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004232 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004233 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004234 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004235 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004236 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004237 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004238 }
4239
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004240 if (!hasFastMixer()) {
4241 // Balance must take effect after mono conversion.
4242 // We do it here if there is no FastMixer.
4243 // mBalance detects zero balance within the class for speed (not needed here).
4244 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004245 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004246 }
4247
Eric Laurentb62d0362021-10-26 17:40:18 +02004248 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4249 // mPostSpatializerBuffer if the haptics track is spatialized.
4250 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4251 // For other thread types, the haptics channels are already in mEffectBuffer.
4252 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4253 const size_t srcBufferSize = mNormalFrameCount *
4254 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4255 mEffectBufferFormat);
4256 const size_t dstBufferSize = mNormalFrameCount
4257 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4258
4259 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4260 mEffectBufferFormat,
4261 (uint8_t*)mEffectBuffer + srcBufferSize,
4262 mEffectBufferFormat,
4263 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004264 }
Atneya Nair68436cf2022-09-19 17:51:37 -07004265 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4266 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4267 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4268 // Clamp PCM float values more than this distance from 0 to insulate
4269 // a HAL which doesn't handle NaN correctly.
4270 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4271 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4272 static_cast<const float*>(effectBuffer),
4273 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4274 } else {
4275 memcpy_by_audio_format(mSinkBuffer, mFormat,
4276 effectBuffer, mEffectBufferFormat, framesToCopy);
4277 }
jiabin245cdd92018-12-07 17:55:15 -08004278 // The sample data is partially interleaved when haptic channels exist,
4279 // we need to adjust channels here.
4280 if (mHapticChannelCount > 0) {
4281 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4282 mChannelCount + mHapticChannelCount,
4283 audio_bytes_per_sample(mFormat),
4284 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4285 }
Andy Hung98ef9782014-03-04 14:46:50 -08004286 }
4287
Eric Laurent81784c32012-11-19 14:55:58 -08004288 // enable changes in effect chain
4289 unlockEffectChains(effectChains);
4290
Vlad Popafce10862023-02-03 10:37:07 +01004291 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung2cbc2722023-07-17 17:05:00 -07004292 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004293 metadataUpdate.playbackMetadataUpdate);
4294 }
4295
Eric Laurentbfb1b832013-01-07 09:53:42 -08004296 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004297 // mSleepTimeUs == 0 means we must write to audio hardware
4298 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004299 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004300 // writePeriodNs is updated >= 0 when ret > 0.
4301 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004302 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004303 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004304 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004305 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004306 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004307 if (ret < 0) {
4308 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004309 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004310 mBytesWritten += ret;
4311 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004312 const int64_t frames = ret / mFrameSize;
4313 mFramesWritten += frames;
4314
4315 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4316 // process information relating to write time.
4317 if (audio_has_proportional_frames(mFormat)) {
4318 // we are in a continuous mixing cycle
4319 if (mMixerStatus == MIXER_TRACKS_READY &&
4320 loopCount == lastLoopCountWritten + 1) {
4321
4322 const double jitterMs =
4323 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4324 {frames, writePeriodNs},
4325 {0, 0} /* lastTimestamp */, mSampleRate);
4326 const double processMs =
4327 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4328
4329 Mutex::Autolock _l(mLock);
4330 mIoJitterMs.add(jitterMs);
4331 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004332
4333 if (mPipeSink.get() != nullptr) {
4334 // Using the Monopipe availableToWrite, we estimate the current
4335 // buffer size.
4336 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4337 const ssize_t
4338 availableToWrite = mPipeSink->availableToWrite();
4339 const size_t pipeFrames = monoPipe->maxFrames();
4340 const size_t
4341 remainingFrames = pipeFrames - max(availableToWrite, 0);
4342 mMonopipePipeDepthStats.add(remainingFrames);
4343 }
Andy Hung446f4df2019-02-21 12:26:41 -08004344 }
4345
4346 // write blocked detection
4347 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004348 if ((mType == MIXER || mType == SPATIALIZER)
4349 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004350 mNumDelayedWrites++;
4351 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4352 ATRACE_NAME("underrun");
4353 ALOGW("write blocked for %lld msecs, "
4354 "%d delayed writes, thread %d",
4355 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4356 mNumDelayedWrites, mId);
4357 lastWarning = lastIoEndNs;
4358 }
4359 }
4360 }
4361 // update timing info.
4362 mLastIoBeginNs = lastIoBeginNs;
4363 mLastIoEndNs = lastIoEndNs;
4364 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004365 }
4366 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4367 (mMixerStatus == MIXER_DRAIN_ALL)) {
4368 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004369 }
Andy Hungd3639922022-04-28 18:00:49 -07004370 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004371
4372 if (mThreadThrottle
4373 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004374 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004375 // Limit MixerThread data processing to no more than twice the
4376 // expected processing rate.
4377 //
4378 // This helps prevent underruns with NuPlayer and other applications
4379 // which may set up buffers that are close to the minimum size, or use
4380 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4381 //
4382 // The throttle smooths out sudden large data drains from the device,
4383 // e.g. when it comes out of standby, which often causes problems with
4384 // (1) mixer threads without a fast mixer (which has its own warm-up)
4385 // (2) minimum buffer sized tracks (even if the track is full,
4386 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004387 //
4388 // Total time spent in last processing cycle equals time spent in
4389 // 1. threadLoop_write, as well as time spent in
4390 // 2. threadLoop_mix (significant for heavy mixing, especially
4391 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004392
Andy Hung446f4df2019-02-21 12:26:41 -08004393 // it's OK if deltaMs is an overestimate.
4394
4395 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004396
Ivan Lozanoea04d392017-11-07 14:37:07 -08004397 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004398 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004399 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004400
Andy Hung08fb1742015-05-31 23:22:10 -07004401 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004402 // notify of throttle start on verbose log
4403 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4404 "mixer(%p) throttle begin:"
4405 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004406 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004407 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004408 // Throttle must be attributed to the previous mixer loop's write time
4409 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004410 // This also ensures proper timing statistics.
4411 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004412 } else {
4413 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4414 if (diff > 0) {
4415 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004416 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004417 ALOGD_IF(!isSingleDeviceType(
4418 outDeviceTypes(), audio_is_a2dp_out_device) &&
4419 !isSingleDeviceType(
4420 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004421 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004422 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4423 }
Andy Hung08fb1742015-05-31 23:22:10 -07004424 }
4425 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004426 }
Eric Laurent81784c32012-11-19 14:55:58 -08004427
Eric Laurentbfb1b832013-01-07 09:53:42 -08004428 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004429 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004430 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004431 // suspended requires accurate metering of sleep time.
4432 if (isSuspended()) {
4433 // advance by expected sleepTime
4434 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4435 const nsecs_t nowNs = systemTime();
4436
4437 // compute expected next time vs current time.
4438 // (negative deltas are treated as delays).
4439 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4440 if (deltaNs < -kMaxNextBufferDelayNs) {
4441 // Delays longer than the max allowed trigger a reset.
4442 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4443 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4444 timeLoopNextNs = nowNs + deltaNs;
4445 } else if (deltaNs < 0) {
4446 // Delays within the max delay allowed: zero the delta/sleepTime
4447 // to help the system catch up in the next iteration(s)
4448 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4449 deltaNs = 0;
4450 }
4451 // update sleep time (which is >= 0)
4452 mSleepTimeUs = deltaNs / 1000;
4453 }
Eric Laurente93cc032016-05-05 10:15:10 -07004454 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4455 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004456 }
Glenn Kastene7754022014-10-31 12:11:26 -07004457 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004458 }
Eric Laurent81784c32012-11-19 14:55:58 -08004459 }
4460
4461 // Finally let go of removed track(s), without the lock held
4462 // since we can't guarantee the destructors won't acquire that
4463 // same lock. This will also mutate and push a new fast mixer state.
4464 threadLoop_removeTracks(tracksToRemove);
4465 tracksToRemove.clear();
4466
4467 // FIXME I don't understand the need for this here;
4468 // it was in the original code but maybe the
4469 // assignment in saveOutputTracks() makes this unnecessary?
4470 clearOutputTracks();
4471
4472 // Effect chains will be actually deleted here if they were removed from
4473 // mEffectChains list during mixing or effects processing
4474 effectChains.clear();
4475
4476 // FIXME Note that the above .clear() is no longer necessary since effectChains
4477 // is now local to this block, but will keep it for now (at least until merge done).
4478 }
4479
Eric Laurentbfb1b832013-01-07 09:53:42 -08004480 threadLoop_exit();
4481
Eric Laurentcf817a22014-08-04 20:36:31 -07004482 if (!mStandby) {
4483 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004484 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004485 }
4486
4487 releaseWakeLock();
4488
4489 ALOGV("Thread %p type %d exiting", this, mType);
4490 return false;
4491}
4492
Andy Hung71742ab2023-07-07 13:47:37 -07004493void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004494{
Dean Wheatley12473e92021-03-18 23:00:55 +11004495 if (mStandby) {
4496 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4497 return;
4498 } else if (mHwPaused) {
4499 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4500 return;
4501 }
4502
4503 // Gather the framesReleased counters for all active tracks,
4504 // and associate with the sink frames written out. We need
4505 // this to convert the sink timestamp to the track timestamp.
4506 bool kernelLocationUpdate = false;
4507 ExtendedTimestamp timestamp; // use private copy to fetch
4508
4509 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4510 // HAL may be draining some small duration buffered data for fade out.
4511 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4512 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4513 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4514 mSampleRate);
4515
4516 if (isTimestampCorrectionEnabled()) {
4517 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4518 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4519 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4520 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4521 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4522 = correctedTimestamp.mFrames;
4523 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4524 = correctedTimestamp.mTimeNs;
4525 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4526 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4527 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4528
4529 // Note: Downstream latency only added if timestamp correction enabled.
4530 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4531 const int64_t newPosition =
4532 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4533 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4534 // prevent retrograde
4535 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4536 newPosition,
4537 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4538 - mSuspendedFrames));
4539 }
4540 }
4541
4542 // We always fetch the timestamp here because often the downstream
4543 // sink will block while writing.
4544
4545 // We keep track of the last valid kernel position in case we are in underrun
4546 // and the normal mixer period is the same as the fast mixer period, or there
4547 // is some error from the HAL.
4548 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4549 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4550 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4551 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4552 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4553
4554 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4555 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4556 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4557 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4558 }
4559
4560 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4561 kernelLocationUpdate = true;
4562 } else {
4563 ALOGVV("getTimestamp error - no valid kernel position");
4564 }
4565
4566 // copy over kernel info
4567 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4568 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4569 + mSuspendedFrames; // add frames discarded when suspended
4570 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4571 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4572 } else {
4573 mTimestampVerifier.error();
4574 }
4575
4576 // mFramesWritten for non-offloaded tracks are contiguous
4577 // even after standby() is called. This is useful for the track frame
4578 // to sink frame mapping.
4579 bool serverLocationUpdate = false;
4580 if (mFramesWritten != mLastFramesWritten) {
4581 serverLocationUpdate = true;
4582 mLastFramesWritten = mFramesWritten;
4583 }
4584 // Only update timestamps if there is a meaningful change.
4585 // Either the kernel timestamp must be valid or we have written something.
4586 if (kernelLocationUpdate || serverLocationUpdate) {
4587 if (serverLocationUpdate) {
4588 // use the time before we called the HAL write - it is a bit more accurate
4589 // to when the server last read data than the current time here.
4590 //
4591 // If we haven't written anything, mLastIoBeginNs will be -1
4592 // and we use systemTime().
4593 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4594 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4595 ? systemTime() : mLastIoBeginNs;
4596 }
4597
Andy Hung3ff4b552023-06-26 19:20:57 -07004598 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004599 if (!t->isFastTrack()) {
4600 t->updateTrackFrameInfo(
Andy Hung3ff4b552023-06-26 19:20:57 -07004601 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004602 mFramesWritten,
4603 mSampleRate,
4604 mTimestamp);
4605 }
4606 }
4607 }
4608
4609 if (audio_has_proportional_frames(mFormat)) {
4610 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4611 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4612 mLatencyMs.add(latencyMs);
4613 }
4614 }
4615#if 0
4616 // logFormat example
4617 if (z % 100 == 0) {
4618 timespec ts;
4619 clock_gettime(CLOCK_MONOTONIC, &ts);
4620 LOGT("This is an integer %d, this is a float %f, this is my "
4621 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4622 LOGT("A deceptive null-terminated string %\0");
4623 }
4624 ++z;
4625#endif
4626}
4627
Eric Laurentbfb1b832013-01-07 09:53:42 -08004628// removeTracks_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07004629void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hung71ba4b32022-10-06 12:09:49 -07004630NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurentbfb1b832013-01-07 09:53:42 -08004631{
Andy Hungfe726a62018-09-27 15:17:25 -07004632 for (const auto& track : tracksToRemove) {
4633 mActiveTracks.remove(track);
4634 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hungbd72c542023-06-20 18:56:17 -07004635 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004636 if (chain != 0) {
4637 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4638 __func__, track->id(), chain.get(), track->sessionId());
4639 chain->decActiveTrackCnt();
4640 }
4641 // If an external client track, inform APM we're no longer active, and remove if needed.
4642 // We do this under lock so that the state is consistent if the Track is destroyed.
4643 if (track->isExternalTrack()) {
4644 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004645 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004646 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004647 }
4648 }
Andy Hungfe726a62018-09-27 15:17:25 -07004649 if (track->isTerminated()) {
4650 // remove from our tracks vector
4651 removeTrack_l(track);
4652 }
jiabineb3bda02020-06-30 14:07:03 -07004653 if (mHapticChannelCount > 0 &&
4654 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4655 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004656 mLock.unlock();
4657 // Unlock due to VibratorService will lock for this call and will
4658 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung9554ec02023-07-20 21:23:42 -07004659 afutils::onExternalVibrationStop(track->getExternalVibration());
jiabin57303cc2018-12-18 15:45:57 -08004660 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004661
4662 // When the track is stop, set the haptic intensity as MUTE
4663 // for the HapticGenerator effect.
4664 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004665 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004666 }
jiabin245cdd92018-12-07 17:55:15 -08004667 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004668 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004669}
Eric Laurent81784c32012-11-19 14:55:58 -08004670
Andy Hung71742ab2023-07-07 13:47:37 -07004671status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004672{
4673 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004674 ExtendedTimestamp ets;
4675 status_t status = mNormalSink->getTimestamp(ets);
4676 if (status == NO_ERROR) {
4677 status = ets.getBestTimestamp(&timestamp);
4678 }
4679 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004680 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004681 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004682 collectTimestamps_l();
4683 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4684 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004685 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004686 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4687 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4688 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4689 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4690 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004691 }
4692 return INVALID_OPERATION;
4693}
Eric Laurent1c333e22014-05-20 10:48:17 -07004694
Eric Laurenteab90452019-06-24 15:17:46 -07004695// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4696// still applied by the mixer.
4697// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4698// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4699// if more than one track are active
Andy Hung71742ab2023-07-07 13:47:37 -07004700status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004701{
4702 status_t result = NO_ERROR;
4703 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4704 if (*volume != mLeftVolFloat) {
4705 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004706 // HAL can return INVALID_OPERATION if operation is not supported.
4707 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004708 "Error when setting output stream volume: %d", result);
4709 if (result == NO_ERROR) {
4710 mLeftVolFloat = *volume;
4711 }
4712 }
4713 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4714 // remove stream volume contribution from software volume.
4715 if (mLeftVolFloat == *volume) {
4716 *volume = 1.0f;
4717 }
4718 }
4719 return result;
4720}
4721
Andy Hung71742ab2023-07-07 13:47:37 -07004722status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004723 audio_patch_handle_t *handle)
4724{
Andy Hungf60abce2016-08-26 11:37:54 -07004725 status_t status;
4726 if (property_get_bool("af.patch_park", false /* default_value */)) {
4727 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4728 // or if HAL does not properly lock against access.
4729 AutoPark<FastMixer> park(mFastMixer);
4730 status = PlaybackThread::createAudioPatch_l(patch, handle);
4731 } else {
4732 status = PlaybackThread::createAudioPatch_l(patch, handle);
4733 }
Eric Laurentb0463942022-12-20 16:31:10 +01004734
4735 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004736 return status;
4737}
4738
Andy Hung71742ab2023-07-07 13:47:37 -07004739status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004740 audio_patch_handle_t *handle)
4741{
4742 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004743
4744 // store new device and send to effects
4745 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004746 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004747 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004748 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4749 && !mOutput->audioHwDev->supportsAudioPatches(),
4750 "Enumerated device type(%#x) must not be used "
4751 "as it does not support audio patches",
4752 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004753 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung71ba4b32022-10-06 12:09:49 -07004754 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4755 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004756 }
4757
François Gaffie0c280aa2018-07-25 10:02:15 +02004758 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004759#ifdef ADD_BATTERY_DATA
4760 // when changing the audio output device, call addBatteryData to notify
4761 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004762 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004763 uint32_t params = 0;
4764 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004765 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004766 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004767 }
4768
Eric Laurent054d9d32015-04-24 08:48:48 -07004769 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004770 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004771 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4772 }
4773
4774 if (params != 0) {
4775 addBatteryData(params);
4776 }
4777 }
4778#endif
4779
4780 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004781 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004782 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004783
jiabinc52b1ff2019-10-31 17:20:42 -07004784 // mPatch.num_sinks is not set when the thread is created so that
4785 // the first patch creation triggers an ioConfigChanged callback
4786 bool configChanged = (mPatch.num_sinks == 0) ||
4787 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004788 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004789 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004790 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004791
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004792 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004793 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4794 status = hwDevice->createAudioPatch(patch->num_sources,
4795 patch->sources,
4796 patch->num_sinks,
4797 patch->sinks,
4798 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004799 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004800 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004801 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004802 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004803 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004804
4805 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004806 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004807 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004808 // also dispatch to active AudioTracks for MediaMetrics
4809 for (const auto &track : mActiveTracks) {
4810 track->logEndInterval();
4811 track->logBeginInterval(patchSinksAsString);
4812 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004813
Eric Laurente8726fe2015-06-26 09:39:24 -07004814 if (configChanged) {
4815 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4816 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004817 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004818 mActiveTracks.setHasChanged();
4819
Eric Laurent1c333e22014-05-20 10:48:17 -07004820 return status;
4821}
4822
Andy Hung71742ab2023-07-07 13:47:37 -07004823status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004824{
Andy Hungf60abce2016-08-26 11:37:54 -07004825 status_t status;
4826 if (property_get_bool("af.patch_park", false /* default_value */)) {
4827 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4828 // or if HAL does not properly lock against access.
4829 AutoPark<FastMixer> park(mFastMixer);
4830 status = PlaybackThread::releaseAudioPatch_l(handle);
4831 } else {
4832 status = PlaybackThread::releaseAudioPatch_l(handle);
4833 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004834 return status;
4835}
4836
Andy Hung71742ab2023-07-07 13:47:37 -07004837status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004838{
4839 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004840
jiabinc52b1ff2019-10-31 17:20:42 -07004841 mPatch = audio_patch{};
4842 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004843
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004844 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004845 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4846 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004847 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004848 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004849 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004850 // Force meteadata update after a route change
4851 mActiveTracks.setHasChanged();
4852
Eric Laurent1c333e22014-05-20 10:48:17 -07004853 return status;
4854}
4855
Andy Hung71742ab2023-07-07 13:47:37 -07004856void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004857{
4858 Mutex::Autolock _l(mLock);
4859 mTracks.add(track);
4860}
4861
Andy Hung71742ab2023-07-07 13:47:37 -07004862void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004863{
4864 Mutex::Autolock _l(mLock);
4865 destroyTrack_l(track);
4866}
4867
Andy Hung71742ab2023-07-07 13:47:37 -07004868void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07004869{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004870 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004871 config->role = AUDIO_PORT_ROLE_SOURCE;
4872 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4873 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004874 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4875 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4876 config->flags.output = mOutput->flags;
4877 }
Eric Laurent83b88082014-06-20 18:31:16 -07004878}
4879
Eric Laurent81784c32012-11-19 14:55:58 -08004880// ----------------------------------------------------------------------------
4881
Andy Hung71742ab2023-07-07 13:47:37 -07004882/* static */
4883sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07004884 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hung71742ab2023-07-07 13:47:37 -07004885 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung2cbc2722023-07-17 17:05:00 -07004886 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hung71742ab2023-07-07 13:47:37 -07004887}
4888
Andy Hung2cbc2722023-07-17 17:05:00 -07004889MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004890 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung2cbc2722023-07-17 17:05:00 -07004891 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004892 // mAudioMixer below
4893 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01004894 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004895 mFastMixerFutex(0),
4896 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004897 // mOutputSink below
4898 // mPipeSink below
4899 // mNormalSink below
4900{
Andy Hung2cbc2722023-07-17 17:05:00 -07004901 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004902 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004903 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004904 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004905 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4906 mNormalFrameCount);
4907 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4908
Andy Hungfbfc3952015-01-15 13:33:51 -08004909 if (type == DUPLICATING) {
4910 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4911 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4912 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4913 return;
4914 }
Eric Laurent81784c32012-11-19 14:55:58 -08004915 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004916 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004917 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004918 const NBAIO_Format offers[1] = {Format_from_SR_C(
4919 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004920#if !LOG_NDEBUG
4921 ssize_t index =
4922#else
4923 (void)
4924#endif
4925 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004926 ALOG_ASSERT(index == 0);
4927
4928 // initialize fast mixer depending on configuration
4929 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00004930 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08004931 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004932 } else {
4933 switch (kUseFastMixer) {
4934 case FastMixer_Never:
4935 initFastMixer = false;
4936 break;
4937 case FastMixer_Always:
4938 initFastMixer = true;
4939 break;
4940 case FastMixer_Static:
4941 case FastMixer_Dynamic:
4942 initFastMixer = mFrameCount < mNormalFrameCount;
4943 break;
4944 }
4945 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4946 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4947 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004948 }
4949 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004950 audio_format_t fastMixerFormat;
4951 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4952 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4953 } else {
4954 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4955 }
4956 if (mFormat != fastMixerFormat) {
4957 // change our Sink format to accept our intermediate precision
4958 mFormat = fastMixerFormat;
4959 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004960 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004961 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4962 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4963 }
Eric Laurent81784c32012-11-19 14:55:58 -08004964
4965 // create a MonoPipe to connect our submix to FastMixer
4966 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004967
Andy Hung1258c1a2014-05-23 21:22:17 -07004968 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004969 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004970 format.mFormat = fastMixerFormat;
4971 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4972
Eric Laurent81784c32012-11-19 14:55:58 -08004973 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4974 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4975 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4976 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung71ba4b32022-10-06 12:09:49 -07004977 const NBAIO_Format offersFast[1] = {format};
4978 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004979#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02004980 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004981#else
4982 (void)
4983#endif
Andy Hung71ba4b32022-10-06 12:09:49 -07004984 monoPipe->negotiate(offersFast, std::size(offersFast),
4985 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08004986 ALOG_ASSERT(index == 0);
4987 monoPipe->setAvgFrames((mScreenState & 1) ?
4988 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4989 mPipeSink = monoPipe;
4990
Eric Laurent81784c32012-11-19 14:55:58 -08004991 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004992 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004993 FastMixerStateQueue *sq = mFastMixer->sq();
4994#ifdef STATE_QUEUE_DUMP
4995 sq->setObserverDump(&mStateQueueObserverDump);
4996 sq->setMutatorDump(&mStateQueueMutatorDump);
4997#endif
4998 FastMixerState *state = sq->begin();
4999 FastTrack *fastTrack = &state->mFastTracks[0];
5000 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5001 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5002 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005003 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5004 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5005 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005006 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005007 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07005008 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01005009 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005010 fastTrack->mGeneration++;
5011 state->mFastTracksGen++;
5012 state->mTrackMask = 1;
5013 // fast mixer will use the HAL output sink
5014 state->mOutputSink = mOutputSink.get();
5015 state->mOutputSinkGen++;
5016 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005017 // specify sink channel mask when haptic channel mask present as it can not
5018 // be calculated directly from channel count
5019 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005020 ? AUDIO_CHANNEL_NONE
5021 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005022 state->mCommand = FastMixerState::COLD_IDLE;
5023 // already done in constructor initialization list
5024 //mFastMixerFutex = 0;
5025 state->mColdFutexAddr = &mFastMixerFutex;
5026 state->mColdGen++;
5027 state->mDumpState = &mFastMixerDumpState;
Andy Hung2cbc2722023-07-17 17:05:00 -07005028 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005029 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005030 sq->end();
5031 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5032
Eric Tan0513b5d2018-09-17 10:32:48 -07005033 NBLog::thread_info_t info;
5034 info.id = mId;
5035 info.type = NBLog::FASTMIXER;
5036 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5037
Eric Laurent81784c32012-11-19 14:55:58 -08005038 // start the fast mixer
5039 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5040 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005041 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005042 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005043
5044#ifdef AUDIO_WATCHDOG
5045 // create and start the watchdog
5046 mAudioWatchdog = new AudioWatchdog();
5047 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5048 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5049 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005050 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005051#endif
Andy Hung8946a282018-04-19 20:04:56 -07005052 } else {
5053#ifdef TEE_SINK
5054 // Only use the MixerThread tee if there is no FastMixer.
5055 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5056 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5057#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005058 }
5059
5060 switch (kUseFastMixer) {
5061 case FastMixer_Never:
5062 case FastMixer_Dynamic:
5063 mNormalSink = mOutputSink;
5064 break;
5065 case FastMixer_Always:
5066 mNormalSink = mPipeSink;
5067 break;
5068 case FastMixer_Static:
5069 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5070 break;
5071 }
5072}
5073
Andy Hung71742ab2023-07-07 13:47:37 -07005074MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005075{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005076 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005077 FastMixerStateQueue *sq = mFastMixer->sq();
5078 FastMixerState *state = sq->begin();
5079 if (state->mCommand == FastMixerState::COLD_IDLE) {
5080 int32_t old = android_atomic_inc(&mFastMixerFutex);
5081 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005082 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005083 }
5084 }
5085 state->mCommand = FastMixerState::EXIT;
5086 sq->end();
5087 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5088 mFastMixer->join();
5089 // Though the fast mixer thread has exited, it's state queue is still valid.
5090 // We'll use that extract the final state which contains one remaining fast track
5091 // corresponding to our sub-mix.
5092 state = sq->begin();
5093 ALOG_ASSERT(state->mTrackMask == 1);
5094 FastTrack *fastTrack = &state->mFastTracks[0];
5095 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5096 delete fastTrack->mBufferProvider;
5097 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005098 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005099#ifdef AUDIO_WATCHDOG
5100 if (mAudioWatchdog != 0) {
5101 mAudioWatchdog->requestExit();
5102 mAudioWatchdog->requestExitAndWait();
5103 mAudioWatchdog.clear();
5104 }
5105#endif
5106 }
Andy Hung2cbc2722023-07-17 17:05:00 -07005107 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005108 delete mAudioMixer;
5109}
5110
Andy Hung71742ab2023-07-07 13:47:37 -07005111void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005112 PlaybackThread::onFirstRef();
5113
5114 Mutex::Autolock _l(mLock);
5115 if (mOutput != nullptr && mOutput->stream != nullptr) {
5116 status_t status = mOutput->stream->setLatencyModeCallback(this);
5117 if (status != INVALID_OPERATION) {
5118 updateHalSupportedLatencyModes_l();
5119 }
5120 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5121 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5122 mBluetoothLatencyModesEnabled.store(
5123 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5124 }
5125}
Eric Laurent81784c32012-11-19 14:55:58 -08005126
Andy Hung71742ab2023-07-07 13:47:37 -07005127uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005128{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005129 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005130 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5131 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5132 }
5133 return latency;
5134}
5135
Andy Hung71742ab2023-07-07 13:47:37 -07005136ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005137{
5138 // FIXME we should only do one push per cycle; confirm this is true
5139 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005140 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005141 FastMixerStateQueue *sq = mFastMixer->sq();
5142 FastMixerState *state = sq->begin();
5143 if (state->mCommand != FastMixerState::MIX_WRITE &&
5144 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5145 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005146
5147 // FIXME workaround for first HAL write being CPU bound on some devices
5148 ATRACE_BEGIN("write");
5149 mOutput->write((char *)mSinkBuffer, 0);
5150 ATRACE_END();
5151
Eric Laurent81784c32012-11-19 14:55:58 -08005152 int32_t old = android_atomic_inc(&mFastMixerFutex);
5153 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005154 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005155 }
5156#ifdef AUDIO_WATCHDOG
5157 if (mAudioWatchdog != 0) {
5158 mAudioWatchdog->resume();
5159 }
5160#endif
5161 }
5162 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005163#ifdef FAST_THREAD_STATISTICS
Andy Hung2cbc2722023-07-17 17:05:00 -07005164 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005165 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005166#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005167 sq->end();
5168 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5169 if (kUseFastMixer == FastMixer_Dynamic) {
5170 mNormalSink = mPipeSink;
5171 }
5172 } else {
5173 sq->end(false /*didModify*/);
5174 }
5175 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005176 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005177}
5178
Andy Hung71742ab2023-07-07 13:47:37 -07005179void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005180{
5181 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005182 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005183 FastMixerStateQueue *sq = mFastMixer->sq();
5184 FastMixerState *state = sq->begin();
5185 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005186 // Report any frames trapped in the Monopipe
5187 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5188 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5189 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5190 "monoPipeWritten:%lld monoPipeLeft:%lld",
5191 (long long)mFramesWritten, (long long)mSuspendedFrames,
5192 (long long)mPipeSink->framesWritten(), pipeFrames);
5193 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5194
Eric Laurent81784c32012-11-19 14:55:58 -08005195 state->mCommand = FastMixerState::COLD_IDLE;
5196 state->mColdFutexAddr = &mFastMixerFutex;
5197 state->mColdGen++;
5198 mFastMixerFutex = 0;
5199 sq->end();
5200 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5201 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5202 if (kUseFastMixer == FastMixer_Dynamic) {
5203 mNormalSink = mOutputSink;
5204 }
5205#ifdef AUDIO_WATCHDOG
5206 if (mAudioWatchdog != 0) {
5207 mAudioWatchdog->pause();
5208 }
5209#endif
5210 } else {
5211 sq->end(false /*didModify*/);
5212 }
5213 }
5214 PlaybackThread::threadLoop_standby();
5215}
5216
Andy Hung71742ab2023-07-07 13:47:37 -07005217bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005218{
5219 return false;
5220}
5221
Andy Hung71742ab2023-07-07 13:47:37 -07005222bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005223{
5224 return !mStandby;
5225}
5226
Andy Hung71742ab2023-07-07 13:47:37 -07005227bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005228{
5229 Mutex::Autolock _l(mLock);
5230 return waitingAsyncCallback_l();
5231}
5232
Eric Laurent81784c32012-11-19 14:55:58 -08005233// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung71742ab2023-07-07 13:47:37 -07005234void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005235{
5236 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005237 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005238 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005239 // discard any pending drain or write ack by incrementing sequence
5240 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5241 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005242 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005243 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5244 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005245 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005246 mHwPaused = false;
Eric Laurent6f9534f2022-05-03 18:15:04 +02005247 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005248}
5249
Andy Hung71742ab2023-07-07 13:47:37 -07005250void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005251{
5252 ALOGV("signal playback thread");
5253 broadcast_l();
5254}
5255
Andy Hung71742ab2023-07-07 13:47:37 -07005256void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005257{
5258 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5259 invalidateTracks((audio_stream_type_t)i);
5260 }
5261}
5262
Andy Hung71742ab2023-07-07 13:47:37 -07005263void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005264{
Eric Laurent81784c32012-11-19 14:55:58 -08005265 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005266 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005267 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005268 // increase sleep time progressively when application underrun condition clears.
5269 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5270 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5271 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005272 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005273 sleepTimeShift--;
5274 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005275 mSleepTimeUs = 0;
5276 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005277 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005278
Eric Laurent81784c32012-11-19 14:55:58 -08005279}
5280
Andy Hung71742ab2023-07-07 13:47:37 -07005281void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005282{
5283 // If no tracks are ready, sleep once for the duration of an output
5284 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005285 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005286 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005287 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5288 // Using the Monopipe availableToWrite, we estimate the
5289 // sleep time to retry for more data (before we underrun).
5290 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5291 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5292 const size_t pipeFrames = monoPipe->maxFrames();
5293 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5294 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5295 const size_t framesDelay = std::min(
5296 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5297 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5298 pipeFrames, framesLeft, framesDelay);
5299 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5300 } else {
5301 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5302 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5303 mSleepTimeUs = kMinThreadSleepTimeUs;
5304 }
5305 // reduce sleep time in case of consecutive application underruns to avoid
5306 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5307 // duration we would end up writing less data than needed by the audio HAL if
5308 // the condition persists.
5309 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5310 sleepTimeShift++;
5311 }
Eric Laurent81784c32012-11-19 14:55:58 -08005312 }
5313 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005314 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005315 }
5316 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005317 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5318 // before effects processing or output.
5319 if (mMixerBufferValid) {
5320 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005321 if (mType == SPATIALIZER) {
5322 memset(mSinkBuffer, 0, mSinkBufferSize);
5323 }
Andy Hung98ef9782014-03-04 14:46:50 -08005324 } else {
5325 memset(mSinkBuffer, 0, mSinkBufferSize);
5326 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005327 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005328 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5329 "anticipated start");
5330 }
5331 // TODO add standby time extension fct of effect tail
5332}
5333
5334// prepareTracks_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07005335PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07005336 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005337{
Andy Hungc0691382018-09-12 18:01:57 -07005338 // clean up deleted track ids in AudioMixer before allocating new tracks
5339 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5340 // for each trackId, destroy it in the AudioMixer
5341 if (mAudioMixer->exists(trackId)) {
5342 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005343 }
5344 });
Andy Hungc0691382018-09-12 18:01:57 -07005345 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005346
5347 mixer_state mixerStatus = MIXER_IDLE;
5348 // find out which tracks need to be processed
5349 size_t count = mActiveTracks.size();
5350 size_t mixedTracks = 0;
5351 size_t tracksWithEffect = 0;
5352 // counts only _active_ fast tracks
5353 size_t fastTracks = 0;
5354 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5355
5356 float masterVolume = mMasterVolume;
5357 bool masterMute = mMasterMute;
5358
5359 if (masterMute) {
5360 masterVolume = 0;
5361 }
5362 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hungbd72c542023-06-20 18:56:17 -07005363 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005364 if (chain != 0) {
5365 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5366 chain->setVolume_l(&v, &v);
5367 masterVolume = (float)((v + (1 << 23)) >> 24);
5368 chain.clear();
5369 }
5370
5371 // prepare a new state to push
5372 FastMixerStateQueue *sq = NULL;
5373 FastMixerState *state = NULL;
5374 bool didModify = false;
5375 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005376 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005377 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005378 sq = mFastMixer->sq();
5379 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005380 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005381 }
5382
Andy Hung69aed5f2014-02-25 17:24:40 -08005383 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005384 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005385
Andy Hungbd3b2b02018-05-21 10:53:11 -07005386 // DeferredOperations handles statistics after setting mixerStatus.
5387 class DeferredOperations {
5388 public:
Andy Hungea840382020-05-05 21:50:17 -07005389 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5390 : mMixerStatus(mixerStatus)
5391 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005392
5393 // when leaving scope, tally frames properly.
5394 ~DeferredOperations() {
5395 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5396 // because that is when the underrun occurs.
5397 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005398 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005399 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005400 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005401 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005402 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005403 }
5404 }
Andy Hungea840382020-05-05 21:50:17 -07005405 // send the max underrun frames for this mixer period
5406 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005407 }
5408
5409 // tallyUnderrunFrames() is called to update the track counters
5410 // with the number of underrun frames for a particular mixer period.
5411 // We defer tallying until we know the final mixer status.
Andy Hung3ff4b552023-06-26 19:20:57 -07005412 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005413 mUnderrunFrames.emplace_back(track, underrunFrames);
5414 }
5415
5416 private:
5417 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005418 ThreadMetrics * const mThreadMetrics;
Andy Hung3ff4b552023-06-26 19:20:57 -07005419 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005420 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005421 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005422
jiabin245cdd92018-12-07 17:55:15 -08005423 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005424 for (size_t i=0 ; i<count ; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005425 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005426
5427 // this const just means the local variable doesn't change
Andy Hung3ff4b552023-06-26 19:20:57 -07005428 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005429
5430 // process fast tracks
5431 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005432 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5433 "%s(%d): FastTrack(%d) present without FastMixer",
5434 __func__, id(), track->id());
5435
jiabin245cdd92018-12-07 17:55:15 -08005436 if (track->getHapticPlaybackEnabled()) {
5437 noFastHapticTrack = false;
5438 }
Eric Laurent81784c32012-11-19 14:55:58 -08005439
5440 // It's theoretically possible (though unlikely) for a fast track to be created
5441 // and then removed within the same normal mix cycle. This is not a problem, as
5442 // the track never becomes active so it's fast mixer slot is never touched.
5443 // The converse, of removing an (active) track and then creating a new track
5444 // at the identical fast mixer slot within the same normal mix cycle,
5445 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung3ff4b552023-06-26 19:20:57 -07005446 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005447 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005448 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5449 FastTrack *fastTrack = &state->mFastTracks[j];
5450
5451 // Determine whether the track is currently in underrun condition,
5452 // and whether it had a recent underrun.
5453 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5454 FastTrackUnderruns underruns = ftDump->mUnderruns;
5455 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung3ff4b552023-06-26 19:20:57 -07005456 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005457 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung3ff4b552023-06-26 19:20:57 -07005458 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005459 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung3ff4b552023-06-26 19:20:57 -07005460 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005461 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung3ff4b552023-06-26 19:20:57 -07005462 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005463 // don't count underruns that occur while stopping or pausing
5464 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005465 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005466 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5467 recentUnderruns > 0) {
5468 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005469 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005470 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005471 // Immediately account for FastTrack underruns.
Andy Hung3ff4b552023-06-26 19:20:57 -07005472 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005473
5474 // This is similar to the state machine for normal tracks,
5475 // with a few modifications for fast tracks.
5476 bool isActive = true;
Andy Hung3ff4b552023-06-26 19:20:57 -07005477 switch (track->state()) {
5478 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005479 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005480 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005481 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005482 }
5483 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005484 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005485 // ramp down is not yet implemented
5486 track->setPaused();
5487 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005488 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005489 // ramp up is not yet implemented
Andy Hung3ff4b552023-06-26 19:20:57 -07005490 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005491 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005492 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005493 if (recentFull > 0 || recentPartial > 0) {
5494 // track has provided at least some frames recently: reset retry count
Andy Hung3ff4b552023-06-26 19:20:57 -07005495 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005496 }
5497 if (recentUnderruns == 0) {
5498 // no recent underruns: stay active
5499 break;
5500 }
5501 // there has recently been an underrun of some kind
5502 if (track->sharedBuffer() == 0) {
5503 // were any of the recent underruns "empty" (no frames available)?
5504 if (recentEmpty == 0) {
5505 // no, then ignore the partial underruns as they are allowed indefinitely
5506 break;
5507 }
5508 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung3ff4b552023-06-26 19:20:57 -07005509 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005510 break;
5511 }
5512 // indicate to client process that the track was disabled because of underrun;
5513 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005514 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005515 // remove from active list, but state remains ACTIVE [confusing but true]
5516 isActive = false;
5517 break;
5518 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005519 FALLTHROUGH_INTENDED;
Andy Hung3ff4b552023-06-26 19:20:57 -07005520 case IAfTrackBase::STOPPING_2:
5521 case IAfTrackBase::PAUSED:
5522 case IAfTrackBase::STOPPED:
5523 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005524 // Check for presentation complete if track is inactive
5525 // We have consumed all the buffers of this track.
5526 // This would be incomplete if we auto-paused on underrun
5527 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005528 uint32_t latency = 0;
5529 status_t result = mOutput->stream->getLatency(&latency);
5530 ALOGE_IF(result != OK,
5531 "Error when retrieving output stream latency: %d", result);
5532 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005533 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005534 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5535 // track stays in active list until presentation is complete
5536 break;
5537 }
5538 }
5539 if (track->isStopping_2()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005540 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005541 }
5542 if (track->isStopped()) {
5543 // Can't reset directly, as fast mixer is still polling this track
5544 // track->reset();
5545 // So instead mark this track as needing to be reset after push with ack
5546 resetMask |= 1 << i;
5547 }
5548 isActive = false;
5549 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005550 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005551 default:
Andy Hung3ff4b552023-06-26 19:20:57 -07005552 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005553 }
5554
5555 if (isActive) {
5556 // was it previously inactive?
5557 if (!(state->mTrackMask & (1 << j))) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005558 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5559 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005560 fastTrack->mBufferProvider = eabp;
5561 fastTrack->mVolumeProvider = vp;
Andy Hung3ff4b552023-06-26 19:20:57 -07005562 fastTrack->mChannelMask = track->channelMask();
5563 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005564 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005565 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005566 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005567 fastTrack->mGeneration++;
5568 state->mTrackMask |= 1 << j;
5569 didModify = true;
5570 // no acknowledgement required for newly active tracks
5571 }
Andy Hung3ff4b552023-06-26 19:20:57 -07005572 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005573 float volume;
5574 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5575 volume = 0.f;
5576 } else {
5577 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5578 }
5579
5580 handleVoipVolume_l(&volume);
5581
Eric Laurent81784c32012-11-19 14:55:58 -08005582 // cache the combined master volume and stream type volume for fast mixer; this
5583 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005584 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005585 proxy->framesReleased()).first;
5586 volume *= vh;
Andy Hung3ff4b552023-06-26 19:20:57 -07005587 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005588 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005589 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5590 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005591
Andy Hung2cbc2722023-07-17 17:05:00 -07005592 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005593 /*muteState=*/{masterVolume == 0.f,
5594 mStreamTypes[track->streamType()].volume == 0.f,
5595 mStreamTypes[track->streamType()].mute,
5596 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005597 vlf == 0.f && vrf == 0.f,
5598 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005599
5600 vlf *= volume;
5601 vrf *= volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005602
jiabin76d94692022-12-15 21:51:21 +00005603 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005604 ++fastTracks;
5605 } else {
5606 // was it previously active?
5607 if (state->mTrackMask & (1 << j)) {
5608 fastTrack->mBufferProvider = NULL;
5609 fastTrack->mGeneration++;
5610 state->mTrackMask &= ~(1 << j);
5611 didModify = true;
5612 // If any fast tracks were removed, we must wait for acknowledgement
5613 // because we're about to decrement the last sp<> on those tracks.
5614 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5615 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005616 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5617 // AudioTrack may start (which may not be with a start() but with a write()
5618 // after underrun) and immediately paused or released. In that case the
5619 // FastTrack state hasn't had time to update.
5620 // TODO Remove the ALOGW when this theory is confirmed.
5621 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005622 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung3ff4b552023-06-26 19:20:57 -07005623 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005624 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005625 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005626 }
5627 tracksToRemove->add(track);
5628 // Avoids a misleading display in dumpsys
Andy Hung3ff4b552023-06-26 19:20:57 -07005629 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005630 }
jiabin245cdd92018-12-07 17:55:15 -08005631 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5632 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5633 didModify = true;
5634 }
Eric Laurent81784c32012-11-19 14:55:58 -08005635 continue;
5636 }
5637
5638 { // local variable scope to avoid goto warning
5639
5640 audio_track_cblk_t* cblk = track->cblk();
5641
5642 // The first time a track is added we wait
5643 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005644 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005645
5646 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005647 // use the trackId as the AudioMixer name.
5648 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005649 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005650 trackId,
Andy Hung3ff4b552023-06-26 19:20:57 -07005651 track->channelMask(),
5652 track->format(),
5653 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005654 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005655 ALOGW("%s(): AudioMixer cannot create track(%d)"
5656 " mask %#x, format %#x, sessionId %d",
5657 __func__, trackId,
Andy Hung3ff4b552023-06-26 19:20:57 -07005658 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005659 tracksToRemove->add(track);
5660 track->invalidate(); // consider it dead.
5661 continue;
5662 }
5663 }
5664
Eric Laurent81784c32012-11-19 14:55:58 -08005665 // make sure that we have enough frames to mix one full buffer.
5666 // enforce this condition only once to enable draining the buffer in case the client
5667 // app does not call stop() and relies on underrun to stop:
5668 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5669 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005670 size_t desiredFrames;
Andy Hung3ff4b552023-06-26 19:20:57 -07005671 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5672 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005673
5674 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005675 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005676 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5677 // add frames already consumed but not yet released by the resampler
5678 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005679 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005680
Eric Laurent81784c32012-11-19 14:55:58 -08005681 uint32_t minFrames = 1;
5682 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5683 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005684 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005685 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005686
5687 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005688 if (ATRACE_ENABLED()) {
5689 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005690 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005691 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005692 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005693 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005694 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005695 !track->isPaused() && !track->isTerminated())
5696 {
Andy Hungc0691382018-09-12 18:01:57 -07005697 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005698
5699 mixedTracks++;
5700
Andy Hung69aed5f2014-02-25 17:24:40 -08005701 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5702 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005703 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005704 if (track->mainBuffer() != mSinkBuffer &&
5705 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005706 if (mEffectBufferEnabled) {
5707 mEffectBufferValid = true; // Later can set directly.
5708 }
Eric Laurent81784c32012-11-19 14:55:58 -08005709 chain = getEffectChain_l(track->sessionId());
5710 // Delegate volume control to effect in track effect chain if needed
5711 if (chain != 0) {
5712 tracksWithEffect++;
5713 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005714 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005715 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005716 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005717 }
5718 }
5719
5720
5721 int param = AudioMixer::VOLUME;
Andy Hung3ff4b552023-06-26 19:20:57 -07005722 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005723 // no ramp for the first volume setting
Andy Hung3ff4b552023-06-26 19:20:57 -07005724 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5725 if (track->state() == IAfTrackBase::RESUMING) {
5726 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005727 // If a new track is paused immediately after start, do not ramp on resume.
5728 if (cblk->mServer != 0) {
5729 param = AudioMixer::RAMP_VOLUME;
5730 }
Eric Laurent81784c32012-11-19 14:55:58 -08005731 }
Andy Hungc0691382018-09-12 18:01:57 -07005732 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005733 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005734 // FIXME should not make a decision based on mServer
5735 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005736 // If the track is stopped before the first frame was mixed,
5737 // do not apply ramp
5738 param = AudioMixer::RAMP_VOLUME;
5739 }
5740
5741 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005742 uint32_t vl, vr; // in U8.24 integer format
5743 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005744 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005745 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005746 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung3ff4b552023-06-26 19:20:57 -07005747 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005748 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung3ff4b552023-06-26 19:20:57 -07005749 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005750
Eric Laurenteab90452019-06-24 15:17:46 -07005751 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5752 v = 0;
5753 }
5754
5755 handleVoipVolume_l(&v);
5756
5757 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005758 vl = vr = 0;
5759 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005760 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005761 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005762 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005763 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5764 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005765 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005766 if (vlf > GAIN_FLOAT_UNITY) {
5767 ALOGV("Track left volume out of range: %.3g", vlf);
5768 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005769 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005770 if (vrf > GAIN_FLOAT_UNITY) {
5771 ALOGV("Track right volume out of range: %.3g", vrf);
5772 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005773 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005774
Andy Hung2cbc2722023-07-17 17:05:00 -07005775 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005776 /*muteState=*/{masterVolume == 0.f,
5777 mStreamTypes[track->streamType()].volume == 0.f,
5778 mStreamTypes[track->streamType()].mute,
5779 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005780 vlf == 0.f && vrf == 0.f,
5781 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005782
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005783 // now apply the master volume and stream type volume and shaper volume
5784 vlf *= v * vh;
5785 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005786 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005787 // then derive vl and vr as U8.24 versions for the effect chain
5788 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5789 vl = (uint32_t) (scaleto8_24 * vlf);
5790 vr = (uint32_t) (scaleto8_24 * vrf);
5791 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005792 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005793 // send level comes from shared memory and so may be corrupt
5794 if (sendLevel > MAX_GAIN_INT) {
5795 ALOGV("Track send level out of range: %04X", sendLevel);
5796 sendLevel = MAX_GAIN_INT;
5797 }
Andy Hung6be49402014-05-30 10:42:03 -07005798 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5799 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005800 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005801
jiabin76d94692022-12-15 21:51:21 +00005802 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005803
Eric Laurent81784c32012-11-19 14:55:58 -08005804 // Delegate volume control to effect in track effect chain if needed
5805 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5806 // Do not ramp volume if volume is controlled by effect
5807 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005808 // Update remaining floating point volume levels
5809 vlf = (float)vl / (1 << 24);
5810 vrf = (float)vr / (1 << 24);
Andy Hung3ff4b552023-06-26 19:20:57 -07005811 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005812 } else {
5813 // force no volume ramp when volume controller was just disabled or removed
5814 // from effect chain to avoid volume spike
Andy Hung3ff4b552023-06-26 19:20:57 -07005815 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005816 param = AudioMixer::VOLUME;
5817 }
Andy Hung3ff4b552023-06-26 19:20:57 -07005818 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005819 }
5820
Eric Laurent81784c32012-11-19 14:55:58 -08005821 // XXX: these things DON'T need to be done each time
Andy Hung3ff4b552023-06-26 19:20:57 -07005822 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005823 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005824
Andy Hungc0691382018-09-12 18:01:57 -07005825 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5826 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5827 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005828 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005829 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005830 AudioMixer::TRACK,
5831 AudioMixer::FORMAT, (void *)track->format());
5832 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005833 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005834 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005835 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005836
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005837 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005838 mAudioMixer->setParameter(
5839 trackId,
5840 AudioMixer::TRACK,
5841 AudioMixer::MIXER_CHANNEL_MASK,
5842 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5843 } else {
5844 mAudioMixer->setParameter(
5845 trackId,
5846 AudioMixer::TRACK,
5847 AudioMixer::MIXER_CHANNEL_MASK,
5848 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5849 }
5850
Glenn Kastene3aa6592012-12-04 12:22:46 -08005851 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005852 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005853 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005854 if (reqSampleRate == 0) {
5855 reqSampleRate = mSampleRate;
5856 } else if (reqSampleRate > maxSampleRate) {
5857 reqSampleRate = maxSampleRate;
5858 }
Eric Laurent81784c32012-11-19 14:55:58 -08005859 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005860 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005861 AudioMixer::RESAMPLE,
5862 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005863 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005864
Andy Hung8edb8dc2015-03-26 19:13:55 -07005865 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005866 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005867 AudioMixer::TIMESTRETCH,
5868 AudioMixer::PLAYBACK_RATE,
Andy Hung71ba4b32022-10-06 12:09:49 -07005869 // cast away constness for this generic API.
5870 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005871
Andy Hung69aed5f2014-02-25 17:24:40 -08005872 /*
5873 * Select the appropriate output buffer for the track.
5874 *
Andy Hung98ef9782014-03-04 14:46:50 -08005875 * Tracks with effects go into their own effects chain buffer
5876 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005877 *
5878 * Other tracks can use mMixerBuffer for higher precision
5879 * channel accumulation. If this buffer is enabled
5880 * (mMixerBufferEnabled true), then selected tracks will accumulate
5881 * into it.
5882 *
5883 */
5884 if (mMixerBufferEnabled
5885 && (track->mainBuffer() == mSinkBuffer
5886 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005887 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005888 mAudioMixer->setParameter(
5889 trackId,
5890 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005891 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005892 mAudioMixer->setParameter(
5893 trackId,
5894 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005895 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005896 } else {
5897 mAudioMixer->setParameter(
5898 trackId,
5899 AudioMixer::TRACK,
5900 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5901 mAudioMixer->setParameter(
5902 trackId,
5903 AudioMixer::TRACK,
5904 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5905 // TODO: override track->mainBuffer()?
5906 mMixerBufferValid = true;
5907 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005908 } else {
5909 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005910 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005911 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07005912 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005913 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005914 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005915 AudioMixer::TRACK,
5916 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5917 }
Eric Laurent81784c32012-11-19 14:55:58 -08005918 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005919 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005920 AudioMixer::TRACK,
5921 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005922 mAudioMixer->setParameter(
5923 trackId,
5924 AudioMixer::TRACK,
5925 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005926 mAudioMixer->setParameter(
5927 trackId,
5928 AudioMixer::TRACK,
5929 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung3ff4b552023-06-26 19:20:57 -07005930 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005931 mAudioMixer->setParameter(
5932 trackId,
5933 AudioMixer::TRACK,
Andy Hung3ff4b552023-06-26 19:20:57 -07005934 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08005935
5936 // reset retry count
Andy Hung3ff4b552023-06-26 19:20:57 -07005937 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005938
5939 // If one track is ready, set the mixer ready if:
5940 // - the mixer was not ready during previous round OR
5941 // - no other track is not ready
5942 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5943 mixerStatus != MIXER_TRACKS_ENABLED) {
5944 mixerStatus = MIXER_TRACKS_READY;
5945 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005946
5947 // Enable the next few lines to instrument a test for underrun log handling.
5948 // TODO: Remove when we have a better way of testing the underrun log.
5949#if 0
5950 static int i;
5951 if ((++i & 0xf) == 0) {
5952 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5953 }
5954#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005955 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005956 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005957 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005958 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5959 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005960 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005961 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005962 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005963
Eric Laurent81784c32012-11-19 14:55:58 -08005964 // clear effect chain input buffer if an active track underruns to avoid sending
5965 // previous audio buffer again to effects
5966 chain = getEffectChain_l(track->sessionId());
5967 if (chain != 0) {
5968 chain->clearInputBuffer();
5969 }
5970
Andy Hungc0691382018-09-12 18:01:57 -07005971 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005972 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5973 track->isStopped() || track->isPaused()) {
5974 // We have consumed all the buffers of this track.
5975 // Remove it from the list of active tracks.
5976 // TODO: use actual buffer filling status instead of latency when available from
5977 // audio HAL
5978 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005979 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005980 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5981 if (track->isStopped()) {
5982 track->reset();
5983 }
5984 tracksToRemove->add(track);
5985 }
5986 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005987 // No buffers for this track. Give it a few chances to
5988 // fill a buffer, then remove it from active list.
Andy Hung3ff4b552023-06-26 19:20:57 -07005989 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005990 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5991 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005992 tracksToRemove->add(track);
5993 // indicate to client process that the track was disabled because of underrun;
5994 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005995 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005996 // If one track is not ready, mark the mixer also not ready if:
5997 // - the mixer was ready during previous round OR
5998 // - no other track is ready
5999 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6000 mixerStatus != MIXER_TRACKS_READY) {
6001 mixerStatus = MIXER_TRACKS_ENABLED;
6002 }
6003 }
Andy Hungc0691382018-09-12 18:01:57 -07006004 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006005 }
6006
6007 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006008
6009 }
6010
jiabin245cdd92018-12-07 17:55:15 -08006011 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6012 // When there is no fast track playing haptic and FastMixer exists,
6013 // enabling the first FastTrack, which provides mixed data from normal
6014 // tracks, to play haptic data.
6015 FastTrack *fastTrack = &state->mFastTracks[0];
6016 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6017 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6018 didModify = true;
6019 }
6020 }
6021
Eric Laurent81784c32012-11-19 14:55:58 -08006022 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006023 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006024 if (didModify) {
6025 state->mFastTracksGen++;
6026 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6027 if (kUseFastMixer == FastMixer_Dynamic &&
6028 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6029 state->mCommand = FastMixerState::COLD_IDLE;
6030 state->mColdFutexAddr = &mFastMixerFutex;
6031 state->mColdGen++;
6032 mFastMixerFutex = 0;
6033 if (kUseFastMixer == FastMixer_Dynamic) {
6034 mNormalSink = mOutputSink;
6035 }
6036 // If we go into cold idle, need to wait for acknowledgement
6037 // so that fast mixer stops doing I/O.
6038 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6039 pauseAudioWatchdog = true;
6040 }
Eric Laurent81784c32012-11-19 14:55:58 -08006041 }
6042 if (sq != NULL) {
6043 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006044 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6045 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6046 // when bringing the output sink into standby.)
6047 //
6048 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6049 //
6050 // This occurs with BT suspend when we idle the FastMixer with
6051 // active tracks, which may be added or removed.
6052 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006053 }
6054#ifdef AUDIO_WATCHDOG
6055 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6056 mAudioWatchdog->pause();
6057 }
6058#endif
6059
6060 // Now perform the deferred reset on fast tracks that have stopped
6061 while (resetMask != 0) {
6062 size_t i = __builtin_ctz(resetMask);
6063 ALOG_ASSERT(i < count);
6064 resetMask &= ~(1 << i);
Andy Hung3ff4b552023-06-26 19:20:57 -07006065 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006066 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6067 track->reset();
6068 }
6069
Andy Hung80d03d22018-04-10 10:32:11 -07006070 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6071 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6072 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6073 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6074 // See also the implementation of destroyTrack_l().
6075 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006076 const int trackId = track->id();
6077 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6078 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006079 }
6080 }
6081
Eric Laurent81784c32012-11-19 14:55:58 -08006082 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006083 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006084
Eric Laurentb3f315a2021-07-13 15:09:05 +02006085 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6086 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006087 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006088 }
6089
6090 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006091 // as long as there are effects we should clear the effects buffer, to avoid
6092 // passing a non-clean buffer to the effect chain
6093 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006094 if (mType == SPATIALIZER) {
6095 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6096 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006097 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006098 // sink or mix buffer must be cleared if all tracks are connected to an
6099 // effect chain as in this case the mixer will not write to the sink or mix buffer
6100 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006101 // always clear sink buffer for spatializer output as the output of the spatializer
6102 // effect will be accumulated into it
6103 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6104 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006105 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006106 if (mMixerBufferValid) {
6107 memset(mMixerBuffer, 0, mMixerBufferSize);
6108 // TODO: In testing, mSinkBuffer below need not be cleared because
6109 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6110 // after mixing.
6111 //
6112 // To enforce this guarantee:
6113 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6114 // (mixedTracks == 0 && fastTracks > 0))
6115 // must imply MIXER_TRACKS_READY.
6116 // Later, we may clear buffers regardless, and skip much of this logic.
6117 }
Andy Hung98ef9782014-03-04 14:46:50 -08006118 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006119 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006120 }
6121
6122 // if any fast tracks, then status is ready
6123 mMixerStatusIgnoringFastTracks = mixerStatus;
6124 if (fastTracks > 0) {
6125 mixerStatus = MIXER_TRACKS_READY;
6126 }
6127 return mixerStatus;
6128}
6129
Eric Laurentad7dd962016-09-22 12:38:37 -07006130// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006131uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006132{
6133 uint32_t trackCount = 0;
6134 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006135 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006136 trackCount++;
6137 }
6138 }
6139 return trackCount;
6140}
6141
Andy Hung71742ab2023-07-07 13:47:37 -07006142bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006143{
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006144 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6145 // could falsely detect that the frame position has stalled due to underrun because we haven't
6146 // given the Audio HAL enough time to update.
6147 const nsecs_t nowNs = systemTime();
6148 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6149 return mLatchedValue;
6150 }
6151 mPreviousNs = nowNs;
6152 mLatchedValue = false;
6153 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006154 uint64_t position = 0;
6155 struct timespec unused;
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006156 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006157 if (ret == NO_ERROR) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006158 if (position != mPreviousPosition) {
6159 mPreviousPosition = position;
6160 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006161 }
6162 }
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006163 return mLatchedValue;
6164}
6165
Andy Hung71742ab2023-07-07 13:47:37 -07006166void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006167{
6168 mLatchedValue = true;
6169 mPreviousPosition = 0;
6170 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006171}
6172
Andy Hung1bc088a2018-02-09 15:57:31 -08006173// isTrackAllowed_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006174bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006175 audio_channel_mask_t channelMask, audio_format_t format,
6176 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006177{
Andy Hung1bc088a2018-02-09 15:57:31 -08006178 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6179 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006180 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006181 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006182 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006183 ALOGW("%s: invalid format: %#x", __func__, format);
6184 return false;
6185 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006186 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006187 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6188 return false;
6189 }
6190 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006191}
6192
Eric Laurent10351942014-05-08 18:49:52 -07006193// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006194bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006195 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006196{
Eric Laurent81784c32012-11-19 14:55:58 -08006197 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006198 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006199
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006200 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006201
Eric Laurent10351942014-05-08 18:49:52 -07006202 AudioParameter param = AudioParameter(keyValuePair);
6203 int value;
6204 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6205 reconfig = true;
6206 }
6207 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung71742ab2023-07-07 13:47:37 -07006208 if (!AudioFlinger::isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006209 status = BAD_VALUE;
6210 } else {
6211 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006212 reconfig = true;
6213 }
Eric Laurent10351942014-05-08 18:49:52 -07006214 }
6215 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung71742ab2023-07-07 13:47:37 -07006216 if (!AudioFlinger::isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006217 status = BAD_VALUE;
6218 } else {
6219 // no need to save value, since it's constant
6220 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006221 }
Eric Laurent10351942014-05-08 18:49:52 -07006222 }
6223 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6224 // do not accept frame count changes if tracks are open as the track buffer
6225 // size depends on frame count and correct behavior would not be guaranteed
6226 // if frame count is changed after track creation
6227 if (!mTracks.isEmpty()) {
6228 status = INVALID_OPERATION;
6229 } else {
6230 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006231 }
Eric Laurent10351942014-05-08 18:49:52 -07006232 }
6233 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006234 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006235 }
Eric Laurent81784c32012-11-19 14:55:58 -08006236
Eric Laurent10351942014-05-08 18:49:52 -07006237 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006238 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006239 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungb72a5502023-03-27 15:53:06 -07006240 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6241 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006242 mOutput->standby();
Andy Hungb72a5502023-03-27 15:53:06 -07006243 mThreadMetrics.logEndInterval();
6244 mThreadSnapshot.onEnd();
Andy Hungdda7aed2023-03-27 15:53:06 -07006245 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006246 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006247 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006248 }
Eric Laurent10351942014-05-08 18:49:52 -07006249 if (status == NO_ERROR && reconfig) {
6250 readOutputParameters_l();
6251 delete mAudioMixer;
6252 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006253 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006254 const int trackId = track->id();
Andy Hung71ba4b32022-10-06 12:09:49 -07006255 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006256 trackId,
Andy Hung3ff4b552023-06-26 19:20:57 -07006257 track->channelMask(),
6258 track->format(),
6259 track->sessionId());
Andy Hung71ba4b32022-10-06 12:09:49 -07006260 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006261 "%s(): AudioMixer cannot create track(%d)"
6262 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006263 __func__,
Andy Hung3ff4b552023-06-26 19:20:57 -07006264 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006265 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006266 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006267 }
Eric Laurent81784c32012-11-19 14:55:58 -08006268 }
6269
Dean Wheatley68918102021-03-19 22:09:19 +11006270 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006271}
6272
6273
Andy Hung71742ab2023-07-07 13:47:37 -07006274void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006275{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006276 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006277 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006278 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006279 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006280 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6281 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6282 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006283 if (hasFastMixer()) {
6284 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6285
6286 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6287 // while we are dumping it. It may be inconsistent, but it won't mutate!
6288 // This is a large object so we place it on the heap.
6289 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006290 const std::unique_ptr<FastMixerDumpState> copy =
6291 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006292 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006293
6294#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006295 // Similar for state queue
6296 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6297 observerCopy.dump(fd);
6298 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6299 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006300#endif
6301
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006302#ifdef AUDIO_WATCHDOG
6303 if (mAudioWatchdog != 0) {
6304 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6305 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6306 wdCopy.dump(fd);
6307 }
6308#endif
6309
6310 } else {
6311 dprintf(fd, " No FastMixer\n");
6312 }
Eric Laurent90cea102023-05-15 15:08:27 +02006313
6314 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6315 mBluetoothLatencyModesEnabled ? "" : "not ");
6316 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6317 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6318 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006319}
6320
Andy Hung71742ab2023-07-07 13:47:37 -07006321uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006322{
6323 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6324}
6325
Andy Hung71742ab2023-07-07 13:47:37 -07006326uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006327{
6328 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6329}
6330
Andy Hung71742ab2023-07-07 13:47:37 -07006331void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006332{
6333 PlaybackThread::cacheParameters_l();
6334
6335 // FIXME: Relaxed timing because of a certain device that can't meet latency
6336 // Should be reduced to 2x after the vendor fixes the driver issue
6337 // increase threshold again due to low power audio mode. The way this warning
6338 // threshold is calculated and its usefulness should be reconsidered anyway.
6339 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6340}
6341
Andy Hung71742ab2023-07-07 13:47:37 -07006342void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung2cbc2722023-07-17 17:05:00 -07006343 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006344}
6345
Andy Hung71742ab2023-07-07 13:47:37 -07006346void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006347 // Only handle latency mode if:
6348 // - mBluetoothLatencyModesEnabled is true
6349 // - the HAL supports latency modes
6350 // - the selected device is Bluetooth LE or A2DP
6351 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6352 return;
6353 }
6354 if (mOutDeviceTypeAddrs.size() != 1
6355 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6356 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6357 return;
6358 }
6359
6360 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6361 if (mSupportedLatencyModes.size() == 1) {
6362 // If the HAL only support one latency mode currently, confirm the choice
6363 latencyMode = mSupportedLatencyModes[0];
6364 } else if (mSupportedLatencyModes.size() > 1) {
6365 // Request low latency if:
6366 // - At least one active track is either:
6367 // - a fast track with gaming usage or
6368 // - a track with acessibility usage
6369 for (const auto& track : mActiveTracks) {
6370 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6371 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6372 latencyMode = AUDIO_LATENCY_MODE_LOW;
6373 break;
6374 }
6375 }
6376 }
6377
6378 if (latencyMode != mSetLatencyMode) {
6379 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6380 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6381 __func__, mId, toString(latencyMode).c_str(), status);
6382 if (status == NO_ERROR) {
6383 mSetLatencyMode = latencyMode;
6384 }
6385 }
6386}
6387
Andy Hung71742ab2023-07-07 13:47:37 -07006388void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006389
6390 if (mOutput == nullptr || mOutput->stream == nullptr) {
6391 return;
6392 }
6393 std::vector<audio_latency_mode_t> latencyModes;
6394 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6395 if (status != NO_ERROR) {
6396 latencyModes.clear();
6397 }
6398 if (latencyModes != mSupportedLatencyModes) {
6399 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6400 __func__, mId, status, toString(latencyModes).c_str());
6401 mSupportedLatencyModes.swap(latencyModes);
6402 sendHalLatencyModesChangedEvent_l();
6403 }
6404}
6405
Andy Hung71742ab2023-07-07 13:47:37 -07006406status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006407 std::vector<audio_latency_mode_t>* modes) {
6408 if (modes == nullptr) {
6409 return BAD_VALUE;
6410 }
6411 Mutex::Autolock _l(mLock);
6412 *modes = mSupportedLatencyModes;
6413 return NO_ERROR;
6414}
6415
Andy Hung71742ab2023-07-07 13:47:37 -07006416void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006417 std::vector<audio_latency_mode_t> modes) {
6418 Mutex::Autolock _l(mLock);
6419 if (modes != mSupportedLatencyModes) {
6420 ALOGD("%s: thread(%d) supported latency modes: %s",
6421 __func__, mId, toString(modes).c_str());
6422 mSupportedLatencyModes.swap(modes);
6423 sendHalLatencyModesChangedEvent_l();
6424 }
6425}
6426
Andy Hung71742ab2023-07-07 13:47:37 -07006427status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006428 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6429 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6430 return INVALID_OPERATION;
6431 }
6432 mBluetoothLatencyModesEnabled.store(enabled);
6433 return NO_ERROR;
6434}
6435
Eric Laurent81784c32012-11-19 14:55:58 -08006436// ----------------------------------------------------------------------------
6437
Andy Hung71742ab2023-07-07 13:47:37 -07006438/* static */
6439sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07006440 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07006441 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6442 const audio_offload_info_t& offloadInfo) {
6443 return sp<DirectOutputThread>::make(
Andy Hung2cbc2722023-07-17 17:05:00 -07006444 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung71742ab2023-07-07 13:47:37 -07006445}
6446
Andy Hung2cbc2722023-07-17 17:05:00 -07006447DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fenn56576722022-10-05 13:42:36 -07006448 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6449 const audio_offload_info_t& offloadInfo)
Andy Hung2cbc2722023-07-17 17:05:00 -07006450 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fenn56576722022-10-05 13:42:36 -07006451 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006452{
Andy Hung2cbc2722023-07-17 17:05:00 -07006453 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006454}
6455
Andy Hung71742ab2023-07-07 13:47:37 -07006456DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006457{
6458}
6459
Andy Hung71742ab2023-07-07 13:47:37 -07006460void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006461{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006462 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006463 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6464 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6465}
6466
Andy Hung71742ab2023-07-07 13:47:37 -07006467void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006468{
6469 Mutex::Autolock _l(mLock);
6470 if (mMasterBalance != balance) {
6471 mMasterBalance.store(balance);
6472 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6473 broadcast_l();
6474 }
6475}
6476
Andy Hung71742ab2023-07-07 13:47:37 -07006477void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006478{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006479 float left, right;
6480
Andy Hung333ab962019-05-28 20:23:35 -07006481 // Ensure volumeshaper state always advances even when muted.
Andy Hung3ff4b552023-06-26 19:20:57 -07006482 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hungee86cee2022-12-13 19:19:53 -08006483
Andy Hungee86cee2022-12-13 19:19:53 -08006484 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6485 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6486
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006487 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6488 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hungee86cee2022-12-13 19:19:53 -08006489
6490 const int64_t volumeShaperFrames =
6491 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6492 const auto [shaperVolume, shaperActive] =
6493 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006494 mVolumeShaperActive = shaperActive;
6495
Vlad Popae2f5aef2022-07-25 16:00:20 +02006496 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6497 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6498 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6499
6500 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6501
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006502 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006503 left = right = 0;
6504 } else {
6505 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006506 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006507
Glenn Kastenc56f3422014-03-21 17:53:17 -07006508 if (left > GAIN_FLOAT_UNITY) {
6509 left = GAIN_FLOAT_UNITY;
6510 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006511 if (right > GAIN_FLOAT_UNITY) {
6512 right = GAIN_FLOAT_UNITY;
6513 }
zhangjincheng73e73872023-01-16 17:17:38 +08006514 left *= v;
6515 right *= v;
Andy Hung2cbc2722023-07-17 17:05:00 -07006516 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng73e73872023-01-16 17:17:38 +08006517 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6518 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6519 right *= mMasterBalanceRight;
6520 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006521 }
6522
Andy Hung2cbc2722023-07-17 17:05:00 -07006523 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006524 /*muteState=*/{mMasterMute,
6525 mStreamTypes[track->streamType()].volume == 0.f,
6526 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006527 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006528 clientVolumeMute,
6529 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006530
Eric Laurentbfb1b832013-01-07 09:53:42 -08006531 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006532 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006533 if (left != mLeftVolFloat || right != mRightVolFloat) {
6534 mLeftVolFloat = left;
6535 mRightVolFloat = right;
6536
Eric Laurentbfb1b832013-01-07 09:53:42 -08006537 // Delegate volume control to effect in track effect chain if needed
6538 // only one effect chain can be present on DirectOutputThread, so if
6539 // there is one, the track is connected to it
6540 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006541 // if effect chain exists, volume is handled by it.
6542 // Convert volumes from float to 8.24
6543 uint32_t vl = (uint32_t)(left * (1 << 24));
6544 uint32_t vr = (uint32_t)(right * (1 << 24));
6545 // Direct/Offload effect chains set output volume in setVolume_l().
6546 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6547 } else {
6548 // otherwise we directly set the volume.
6549 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006550 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006551 }
6552 }
6553}
6554
Andy Hung71742ab2023-07-07 13:47:37 -07006555void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006556{
Andy Hung3ff4b552023-06-26 19:20:57 -07006557 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6558 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006559
Eric Laurent0f0631e2015-07-06 18:01:25 -07006560 if (previousTrack != 0 && latestTrack != 0) {
6561 if (mType == DIRECT) {
6562 if (previousTrack.get() != latestTrack.get()) {
6563 mFlushPending = true;
6564 }
6565 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006566 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6567 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006568 mFlushPending = true;
6569 }
6570 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006571 } else if (previousTrack == 0) {
6572 // there could be an old track added back during track transition for direct
6573 // output, so always issues flush to flush data of the previous track if it
6574 // was already destroyed with HAL paused, then flush can resume the playback
6575 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006576 }
6577 PlaybackThread::onAddNewTrack_l();
6578}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006579
Andy Hung71742ab2023-07-07 13:47:37 -07006580PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07006581 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006582)
6583{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006584 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006585 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006586 bool doHwPause = false;
6587 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006588
6589 // find out which tracks need to be processed
Andy Hung3ff4b552023-06-26 19:20:57 -07006590 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006591 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006592 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006593 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006594 continue;
6595 }
6596
Andy Hung3ff4b552023-06-26 19:20:57 -07006597 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006598#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006599 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006600#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006601 // Only consider last track started for volume and mixer state control.
6602 // In theory an older track could underrun and restart after the new one starts
6603 // but as we only care about the transition phase between two tracks on a
6604 // direct output, it is not a problem to ignore the underrun case.
Andy Hung3ff4b552023-06-26 19:20:57 -07006605 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006606 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006607
Kuowei Li23666472021-01-20 10:23:25 +08006608 if (track->isPausePending()) {
6609 track->pauseAck();
6610 // It is possible a track might have been flushed or stopped.
6611 // Other operations such as flush pending might occur on the next prepare.
6612 if (track->isPausing()) {
6613 track->setPaused();
6614 }
6615 // Always perform pause, as an immediate flush will change
6616 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006617 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006618 doHwPause = true;
6619 mHwPaused = true;
6620 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006621 } else if (track->isFlushPending()) {
6622 track->flushAck();
6623 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006624 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006625 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006626 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006627 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006628 if (last) {
6629 mLeftVolFloat = mRightVolFloat = -1.0;
6630 if (mHwPaused) {
6631 doHwResume = true;
6632 mHwPaused = false;
6633 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006634 }
6635 }
6636
Eric Laurent81784c32012-11-19 14:55:58 -08006637 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006638 // for all its buffers to be filled before processing it.
6639 // Allow draining the buffer in case the client
6640 // app does not call stop() and relies on underrun to stop:
Andy Hung3ff4b552023-06-26 19:20:57 -07006641 // hence the test on (track->retryCount() > 1).
6642 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006643 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6644 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006645 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006646
6647 // target retry count that we will use is based on the time we wait for retries.
6648 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6649 // the retry threshold is when we accept any size for PCM data. This is slightly
6650 // smaller than the retry count so we can push small bits of data without a glitch.
6651 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006652 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006653 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung3ff4b552023-06-26 19:20:57 -07006654 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006655 minFrames = mNormalFrameCount;
6656 } else {
6657 minFrames = 1;
6658 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006659
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006660 const size_t framesReady = track->framesReady();
6661 const int trackId = track->id();
6662 if (ATRACE_ENABLED()) {
6663 std::string traceName("nRdy");
6664 traceName += std::to_string(trackId);
6665 ATRACE_INT(traceName.c_str(), framesReady);
6666 }
6667 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006668 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006669 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006670 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006671
Andy Hung3ff4b552023-06-26 19:20:57 -07006672 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6673 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006674 if (last) {
6675 // make sure processVolume_l() will apply new volume even if 0
6676 mLeftVolFloat = mRightVolFloat = -1.0;
6677 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006678 if (!mHwSupportsPause) {
6679 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006680 }
6681 }
6682
6683 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006684 processVolume_l(track, last);
6685 if (last) {
Andy Hung3ff4b552023-06-26 19:20:57 -07006686 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006687 if (previousTrack != 0) {
6688 if (track != previousTrack.get()) {
6689 // Flush any data still being written from last track
6690 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006691 // Invalidate previous track to force a seek when resuming.
6692 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006693 }
6694 }
6695 mPreviousTrack = track;
6696
Eric Laurentd595b7c2013-04-03 17:27:56 -07006697 // reset retry count
Andy Hung3ff4b552023-06-26 19:20:57 -07006698 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006699 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006700 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006701 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006702 doHwResume = true;
6703 mHwPaused = false;
6704 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006705 }
Eric Laurent81784c32012-11-19 14:55:58 -08006706 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006707 // clear effect chain input buffer if the last active track started underruns
6708 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006709 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006710 mEffectChains[0]->clearInputBuffer();
6711 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006712 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07006713 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006714 if (last && mHwPaused) {
6715 doHwResume = true;
6716 mHwPaused = false;
6717 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006718 }
6719 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6720 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006721 // We have consumed all the buffers of this track.
6722 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006723 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006724 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006725 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006726 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006727 if (presComplete) {
6728 mOutput->presentationComplete();
6729 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006730 if (track->isStopping_2()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07006731 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006732 }
Eric Laurent81784c32012-11-19 14:55:58 -08006733 if (track->isStopped()) {
6734 track->reset();
6735 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006736 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006737 }
6738 } else {
6739 // No buffers for this track. Give it a few chances to
6740 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006741 // Only consider last track started for mixer state control
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006742 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07006743 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung3ff4b552023-06-26 19:20:57 -07006744 && --(track->retryCount()) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006745 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung3ff4b552023-06-26 19:20:57 -07006746 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006747 } else {
6748 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6749 tracksToRemove->add(track);
6750 // indicate to client process that the track was disabled because of
6751 // underrun; it will then automatically call start() when data is available
6752 track->disable();
6753 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6754 // unlike mixerthread, HAL can be paused for direct output
6755 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6756 "minFrames = %u, mFormat = %#x",
6757 framesReady, minFrames, mFormat);
6758 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6759 doHwPause = true;
6760 mHwPaused = true;
6761 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006762 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006763 } else if (last) {
6764 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006765 }
6766 }
6767 }
6768 }
6769
Eric Laurentd1f69b02014-12-15 14:33:13 -08006770 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006771 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006772 for (size_t i = 0; i < mTracks.size(); i++) {
6773 if (mTracks[i]->isFlushPending()) {
6774 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006775 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006776 }
6777 }
6778 }
6779
6780 // make sure the pause/flush/resume sequence is executed in the right order.
6781 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6782 // before flush and then resume HW. This can happen in case of pause/flush/resume
6783 // if resume is received before pause is executed.
6784 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006785 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006786 status_t result = mOutput->stream->pause();
6787 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006788 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006789 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006790 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006791 flushHw_l();
6792 }
6793 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006794 status_t result = mOutput->stream->resume();
6795 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006796 }
Eric Laurent81784c32012-11-19 14:55:58 -08006797 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006798 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006799
6800 return mixerStatus;
6801}
6802
Andy Hung71742ab2023-07-07 13:47:37 -07006803void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006804{
Eric Laurent81784c32012-11-19 14:55:58 -08006805 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006806 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006807 // output audio to hardware
6808 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006809 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006810 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006811 status_t status = mActiveTrack->getNextBuffer(&buffer);
6812 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006813 // no need to pad with 0 for compressed audio
6814 if (audio_has_proportional_frames(mFormat)) {
6815 memset(curBuf, 0, frameCount * mFrameSize);
6816 }
Eric Laurent81784c32012-11-19 14:55:58 -08006817 break;
6818 }
6819 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6820 frameCount -= buffer.frameCount;
6821 curBuf += buffer.frameCount * mFrameSize;
6822 mActiveTrack->releaseBuffer(&buffer);
6823 }
Andy Hung2098f272014-02-27 14:00:06 -08006824 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006825 mSleepTimeUs = 0;
6826 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006827 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006828}
6829
Andy Hung71742ab2023-07-07 13:47:37 -07006830void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006831{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006832 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006833 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006834 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006835 return;
6836 }
Andy Hung85ba3332021-04-27 17:40:26 -07006837 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6838 mSleepTimeUs = mActiveSleepTimeUs;
6839 } else {
6840 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006841 }
Andy Hung85ba3332021-04-27 17:40:26 -07006842 // Note: In S or later, we do not write zeroes for
6843 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006844}
6845
Andy Hung71742ab2023-07-07 13:47:37 -07006846void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006847{
6848 {
6849 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006850 for (size_t i = 0; i < mTracks.size(); i++) {
6851 if (mTracks[i]->isFlushPending()) {
6852 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006853 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006854 }
6855 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006856 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006857 flushHw_l();
6858 }
6859 }
6860 PlaybackThread::threadLoop_exit();
6861}
6862
6863// must be called with thread mutex locked
Andy Hung71742ab2023-07-07 13:47:37 -07006864bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006865{
6866 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006867 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006868
6869 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6870 // after a timeout and we will enter standby then.
6871 if (mTracks.size() > 0) {
6872 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006873 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung3ff4b552023-06-26 19:20:57 -07006874 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006875 }
6876
Eric Laurent5cff4032015-05-26 13:49:58 -07006877 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006878}
6879
Eric Laurent10351942014-05-08 18:49:52 -07006880// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006881bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006882 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006883{
6884 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006885 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006886
Eric Laurent10351942014-05-08 18:49:52 -07006887 AudioParameter param = AudioParameter(keyValuePair);
6888 int value;
6889 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006890 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006891 }
Eric Laurent10351942014-05-08 18:49:52 -07006892 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6893 // do not accept frame count changes if tracks are open as the track buffer
6894 // size depends on frame count and correct behavior would not be garantied
6895 // if frame count is changed after track creation
6896 if (!mTracks.isEmpty()) {
6897 status = INVALID_OPERATION;
6898 } else {
6899 reconfig = true;
6900 }
6901 }
6902 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006903 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006904 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006905 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006906 if (!mStandby) {
6907 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006908 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02006909 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07006910 }
Eric Laurent10351942014-05-08 18:49:52 -07006911 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006912 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006913 }
6914 if (status == NO_ERROR && reconfig) {
6915 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006916 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006917 }
6918 }
6919
Dean Wheatley68918102021-03-19 22:09:19 +11006920 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006921}
6922
Andy Hung71742ab2023-07-07 13:47:37 -07006923uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006924{
6925 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006926 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006927 time = PlaybackThread::activeSleepTimeUs();
6928 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006929 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006930 }
6931 return time;
6932}
6933
Andy Hung71742ab2023-07-07 13:47:37 -07006934uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006935{
6936 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006937 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006938 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6939 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006940 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006941 }
6942 return time;
6943}
6944
Andy Hung71742ab2023-07-07 13:47:37 -07006945uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006946{
6947 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006948 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006949 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6950 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006951 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006952 }
6953 return time;
6954}
6955
Andy Hung71742ab2023-07-07 13:47:37 -07006956void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006957{
6958 PlaybackThread::cacheParameters_l();
6959
6960 // use shorter standby delay as on normal output to release
6961 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006962 // no delay on outputs with HW A/V sync
6963 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006964 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006965 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006966 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006967 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006968 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006969 }
Eric Laurent81784c32012-11-19 14:55:58 -08006970}
6971
Andy Hung71742ab2023-07-07 13:47:37 -07006972void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07006973{
ziyangch8f194f12021-12-01 13:48:04 -08006974 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08006975 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006976 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006977 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006978 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006979 mTimestamp.clear();
Andy Hungee86cee2022-12-13 19:19:53 -08006980 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07006981}
6982
Andy Hung71742ab2023-07-07 13:47:37 -07006983int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08006984 // If a VolumeShaper is active, we must wake up periodically to update volume.
6985 const int64_t NS_PER_MS = 1000000;
6986 return mVolumeShaperActive ?
6987 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6988}
6989
Eric Laurent81784c32012-11-19 14:55:58 -08006990// ----------------------------------------------------------------------------
6991
Andy Hung71742ab2023-07-07 13:47:37 -07006992AsyncCallbackThread::AsyncCallbackThread(
6993 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006994 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006995 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006996 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006997 mDrainSequence(0),
6998 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006999{
7000}
7001
Andy Hung71742ab2023-07-07 13:47:37 -07007002void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007003{
7004 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7005}
7006
Andy Hung71742ab2023-07-07 13:47:37 -07007007bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007008{
7009 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007010 uint32_t writeAckSequence;
7011 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007012 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007013
7014 {
7015 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007016 while (!((mWriteAckSequence & 1) ||
7017 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007018 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007019 exitPending())) {
7020 mWaitWorkCV.wait(mLock);
7021 }
7022
Eric Laurentbfb1b832013-01-07 09:53:42 -08007023 if (exitPending()) {
7024 break;
7025 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007026 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7027 mWriteAckSequence, mDrainSequence);
7028 writeAckSequence = mWriteAckSequence;
7029 mWriteAckSequence &= ~1;
7030 drainSequence = mDrainSequence;
7031 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007032 asyncError = mAsyncError;
7033 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007034 }
7035 {
Andy Hung71742ab2023-07-07 13:47:37 -07007036 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007037 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007038 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007039 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007040 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007041 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007042 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007043 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007044 if (asyncError) {
7045 playbackThread->onAsyncError();
7046 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007047 }
7048 }
7049 }
7050 return false;
7051}
7052
Andy Hung71742ab2023-07-07 13:47:37 -07007053void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007054{
7055 ALOGV("AsyncCallbackThread::exit");
7056 Mutex::Autolock _l(mLock);
7057 requestExit();
7058 mWaitWorkCV.broadcast();
7059}
7060
Andy Hung71742ab2023-07-07 13:47:37 -07007061void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007062{
7063 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007064 // bit 0 is cleared
7065 mWriteAckSequence = sequence << 1;
7066}
7067
Andy Hung71742ab2023-07-07 13:47:37 -07007068void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007069{
7070 Mutex::Autolock _l(mLock);
7071 // ignore unexpected callbacks
7072 if (mWriteAckSequence & 2) {
7073 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007074 mWaitWorkCV.signal();
7075 }
7076}
7077
Andy Hung71742ab2023-07-07 13:47:37 -07007078void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007079{
7080 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007081 // bit 0 is cleared
7082 mDrainSequence = sequence << 1;
7083}
7084
Andy Hung71742ab2023-07-07 13:47:37 -07007085void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007086{
7087 Mutex::Autolock _l(mLock);
7088 // ignore unexpected callbacks
7089 if (mDrainSequence & 2) {
7090 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007091 mWaitWorkCV.signal();
7092 }
7093}
7094
Andy Hung71742ab2023-07-07 13:47:37 -07007095void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007096{
7097 Mutex::Autolock _l(mLock);
7098 mAsyncError = true;
7099 mWaitWorkCV.signal();
7100}
7101
Eric Laurentbfb1b832013-01-07 09:53:42 -08007102
7103// ----------------------------------------------------------------------------
Andy Hung71742ab2023-07-07 13:47:37 -07007104
7105/* static */
7106sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07007107 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07007108 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7109 const audio_offload_info_t& offloadInfo) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007110 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung71742ab2023-07-07 13:47:37 -07007111}
7112
Andy Hung2cbc2722023-07-17 17:05:00 -07007113OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fenn56576722022-10-05 13:42:36 -07007114 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7115 const audio_offload_info_t& offloadInfo)
Andy Hung2cbc2722023-07-17 17:05:00 -07007116 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007117 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007118{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007119 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007120 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007121 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007122}
7123
Andy Hung71742ab2023-07-07 13:47:37 -07007124void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007125{
7126 if (mFlushPending || mHwPaused) {
7127 // If a flush is pending or track was paused, just discard buffered data
7128 flushHw_l();
7129 } else {
7130 mMixerStatus = MIXER_DRAIN_ALL;
7131 threadLoop_drain();
7132 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007133 if (mUseAsyncWrite) {
7134 ALOG_ASSERT(mCallbackThread != 0);
7135 mCallbackThread->exit();
7136 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007137 PlaybackThread::threadLoop_exit();
7138}
7139
Andy Hung71742ab2023-07-07 13:47:37 -07007140PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07007141 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007142)
7143{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007144 size_t count = mActiveTracks.size();
7145
7146 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007147 bool doHwPause = false;
7148 bool doHwResume = false;
7149
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007150 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007151
Eric Laurentbfb1b832013-01-07 09:53:42 -08007152 // find out which tracks need to be processed
Andy Hung3ff4b552023-06-26 19:20:57 -07007153 for (const sp<IAfTrack>& t : mActiveTracks) {
7154 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007155#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007156 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007157#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007158 // Only consider last track started for volume and mixer state control.
7159 // In theory an older track could underrun and restart after the new one starts
7160 // but as we only care about the transition phase between two tracks on a
7161 // direct output, it is not a problem to ignore the underrun case.
Andy Hung3ff4b552023-06-26 19:20:57 -07007162 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007163 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007164
Haynes Mathew George7844f672014-01-15 12:32:55 -08007165 if (track->isInvalid()) {
7166 ALOGW("An invalidated track shouldn't be in active list");
7167 tracksToRemove->add(track);
7168 continue;
7169 }
7170
Andy Hung3ff4b552023-06-26 19:20:57 -07007171 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007172 ALOGW("An idle track shouldn't be in active list");
7173 continue;
7174 }
7175
Kuowei Li23666472021-01-20 10:23:25 +08007176 if (track->isPausePending()) {
7177 track->pauseAck();
7178 // It is possible a track might have been flushed or stopped.
7179 // Other operations such as flush pending might occur on the next prepare.
7180 if (track->isPausing()) {
7181 track->setPaused();
7182 }
7183 // Always perform pause if last, as an immediate flush will change
7184 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007185 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007186 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007187 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007188 mHwPaused = true;
7189 }
7190 // If we were part way through writing the mixbuffer to
7191 // the HAL we must save this until we resume
7192 // BUG - this will be wrong if a different track is made active,
7193 // in that case we want to discard the pending data in the
7194 // mixbuffer and tell the client to present it again when the
7195 // track is resumed
7196 mPausedWriteLength = mCurrentWriteLength;
7197 mPausedBytesRemaining = mBytesRemaining;
7198 mBytesRemaining = 0; // stop writing
7199 }
7200 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007201 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007202 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007203 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007204 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07007205 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007206 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007207 track->flushAck();
7208 if (last) {
7209 mFlushPending = true;
7210 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007211 } else if (track->isResumePending()){
7212 track->resumeAck();
7213 if (last) {
7214 if (mPausedBytesRemaining) {
7215 // Need to continue write that was interrupted
7216 mCurrentWriteLength = mPausedWriteLength;
7217 mBytesRemaining = mPausedBytesRemaining;
7218 mPausedBytesRemaining = 0;
7219 }
7220 if (mHwPaused) {
7221 doHwResume = true;
7222 mHwPaused = false;
7223 // threadLoop_mix() will handle the case that we need to
7224 // resume an interrupted write
7225 }
7226 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007227 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007228
Eric Laurent3df841a2016-07-15 15:15:40 -07007229 mLeftVolFloat = mRightVolFloat = -1.0;
7230
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007231 // Do not handle new data in this iteration even if track->framesReady()
7232 mixerStatus = MIXER_TRACKS_ENABLED;
7233 }
7234 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007235 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007236 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung3ff4b552023-06-26 19:20:57 -07007237 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7238 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007239 if (last) {
7240 // make sure processVolume_l() will apply new volume even if 0
7241 mLeftVolFloat = mRightVolFloat = -1.0;
7242 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007243 }
7244
7245 if (last) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007246 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007247 if (previousTrack != 0) {
7248 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007249 // Flush any data still being written from last track
7250 mBytesRemaining = 0;
7251 if (mPausedBytesRemaining) {
7252 // Last track was paused so we also need to flush saved
7253 // mixbuffer state and invalidate track so that it will
7254 // re-submit that unwritten data when it is next resumed
7255 mPausedBytesRemaining = 0;
7256 // Invalidate is a bit drastic - would be more efficient
7257 // to have a flag to tell client that some of the
7258 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007259 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007260 }
7261 // flush data already sent to the DSP if changing audio session as audio
7262 // comes from a different source. Also invalidate previous track to force a
7263 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007264 if (previousTrack->sessionId() != track->sessionId()) {
7265 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007266 }
7267 }
7268 }
7269 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007270 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007271 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007272 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007273 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07007274 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007275 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007276 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007277 mixerStatus = MIXER_TRACKS_READY;
7278 }
7279 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007280 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007281 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007282 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007283 // Hardware buffer can hold a large amount of audio so we must
7284 // wait for all current track's data to drain before we say
7285 // that the track is stopped.
7286 if (mBytesRemaining == 0) {
7287 // Only start draining when all data in mixbuffer
7288 // has been written
7289 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung3ff4b552023-06-26 19:20:57 -07007290 track->setState(IAfTrackBase::STOPPING_2);
7291 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007292 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7293 if (last && !mStandby) {
7294 // do not modify drain sequence if we are already draining. This happens
7295 // when resuming from pause after drain.
7296 if ((mDrainSequence & 1) == 0) {
7297 mSleepTimeUs = 0;
7298 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7299 mixerStatus = MIXER_DRAIN_TRACK;
7300 mDrainSequence += 2;
7301 }
7302 if (mHwPaused) {
7303 // It is possible to move from PAUSED to STOPPING_1 without
7304 // a resume so we must ensure hardware is running
7305 doHwResume = true;
7306 mHwPaused = false;
7307 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007308 }
7309 }
Eric Laurente93cc032016-05-05 10:15:10 -07007310 } else if (last) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007311 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007312 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007313 }
7314 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007315 // Drain has completed or we are in standby, signal presentation complete
7316 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007317 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007318 mOutput->presentationComplete();
7319 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007320 track->reset();
7321 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007322 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007323 if (!mUseAsyncWrite) {
7324 // If we don't get explicit drain notification we must
7325 // register discontinuity regardless of whether this is
7326 // the previous (!last) or the upcoming (last) track
7327 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007328 mTimestampVerifier.discontinuity(
7329 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007330 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007331 }
7332 } else {
7333 // No buffers for this track. Give it a few chances to
7334 // fill a buffer, then remove it from active list.
Brian Lindahl9e661ad2022-07-27 18:01:07 +02007335 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07007336 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung3ff4b552023-06-26 19:20:57 -07007337 && --(track->retryCount()) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02007338 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung3ff4b552023-06-26 19:20:57 -07007339 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007340 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007341 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7342 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007343 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007344 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007345 // it will then automatically call start() when data is available
7346 track->disable();
7347 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007348 } else if (last){
7349 mixerStatus = MIXER_TRACKS_ENABLED;
7350 }
7351 }
7352 }
7353 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007354 if (track->isReady()) { // check ready to prevent premature start.
7355 processVolume_l(track, last);
7356 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007357 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007358
Eric Laurentea0fade2013-10-04 16:23:48 -07007359 // make sure the pause/flush/resume sequence is executed in the right order.
7360 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7361 // before flush and then resume HW. This can happen in case of pause/flush/resume
7362 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007363 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007364 status_t result = mOutput->stream->pause();
7365 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007366 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007367 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007368 if (mFlushPending) {
7369 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007370 }
Eric Laurentfd477972013-10-25 18:10:40 -07007371 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007372 status_t result = mOutput->stream->resume();
7373 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007374 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007375
Eric Laurentbfb1b832013-01-07 09:53:42 -08007376 // remove all the tracks that need to be...
7377 removeTracks_l(*tracksToRemove);
7378
7379 return mixerStatus;
7380}
7381
Eric Laurentbfb1b832013-01-07 09:53:42 -08007382// must be called with thread mutex locked
Andy Hung71742ab2023-07-07 13:47:37 -07007383bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007384{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007385 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7386 mWriteAckSequence, mDrainSequence);
7387 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007388 return true;
7389 }
7390 return false;
7391}
7392
Andy Hung71742ab2023-07-07 13:47:37 -07007393bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007394{
7395 Mutex::Autolock _l(mLock);
7396 return waitingAsyncCallback_l();
7397}
7398
Andy Hung71742ab2023-07-07 13:47:37 -07007399void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007400{
Eric Laurente659ef42014-09-29 13:06:46 -07007401 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007402 // Flush anything still waiting in the mixbuffer
7403 mCurrentWriteLength = 0;
7404 mBytesRemaining = 0;
7405 mPausedWriteLength = 0;
7406 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007407 // reset bytes written count to reflect that DSP buffers are empty after flush.
7408 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007409
Eric Laurentbfb1b832013-01-07 09:53:42 -08007410 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007411 // discard any pending drain or write ack by incrementing sequence
7412 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7413 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007414 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007415 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7416 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007417 }
7418}
7419
Andy Hung71742ab2023-07-07 13:47:37 -07007420void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007421{
7422 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007423 if (PlaybackThread::invalidateTracks_l(streamType)) {
7424 mFlushPending = true;
7425 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007426}
7427
Andy Hung71742ab2023-07-07 13:47:37 -07007428void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08007429 Mutex::Autolock _l(mLock);
7430 if (PlaybackThread::invalidateTracks_l(portIds)) {
7431 mFlushPending = true;
7432 }
7433}
7434
Eric Laurentbfb1b832013-01-07 09:53:42 -08007435// ----------------------------------------------------------------------------
7436
Andy Hung71742ab2023-07-07 13:47:37 -07007437/* static */
7438sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung2cbc2722023-07-17 17:05:00 -07007439 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07007440 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007441 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -07007442}
7443
Andy Hung2cbc2722023-07-17 17:05:00 -07007444DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung44f27182023-07-06 20:56:16 -07007445 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -07007446 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007447 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007448 mWaitTimeMs(UINT_MAX)
7449{
7450 addOutputTrack(mainThread);
7451}
7452
Andy Hung71742ab2023-07-07 13:47:37 -07007453DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007454{
7455 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7456 mOutputTracks[i]->destroy();
7457 }
7458}
7459
Andy Hung71742ab2023-07-07 13:47:37 -07007460void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007461{
7462 // mix buffers...
Andy Hung71ba4b32022-10-06 12:09:49 -07007463 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007464 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007465 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007466 if (mMixerBufferValid) {
7467 memset(mMixerBuffer, 0, mMixerBufferSize);
7468 } else {
7469 memset(mSinkBuffer, 0, mSinkBufferSize);
7470 }
Eric Laurent81784c32012-11-19 14:55:58 -08007471 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007472 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007473 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007474 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007475 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007476}
7477
Andy Hung71742ab2023-07-07 13:47:37 -07007478void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007479{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007480 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007481 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007482 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007483 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007484 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007485 }
7486 } else if (mBytesWritten != 0) {
7487 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7488 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007489 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007490 } else {
7491 // flush remaining overflow buffers in output tracks
7492 writeFrames = 0;
7493 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007494 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007495 }
7496}
7497
Andy Hung71742ab2023-07-07 13:47:37 -07007498ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007499{
7500 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007501 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7502
7503 // Consider the first OutputTrack for timestamp and frame counting.
7504
7505 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7506 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7507 // we always claim success.
7508 if (i == 0) {
7509 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7510 ALOGD_IF(correction != 0 && writeFrames != 0,
7511 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7512 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7513 mFramesWritten -= correction;
7514 }
7515
7516 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007517 }
Andy Hungcf10d742020-04-28 15:38:24 -07007518 if (mStandby) {
7519 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007520 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007521 mStandby = false;
7522 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007523 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007524}
7525
Andy Hung71742ab2023-07-07 13:47:37 -07007526void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007527{
7528 // DuplicatingThread implements standby by stopping all tracks
7529 for (size_t i = 0; i < outputTracks.size(); i++) {
7530 outputTracks[i]->stop();
7531 }
7532}
7533
Andy Hung71742ab2023-07-07 13:47:37 -07007534void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007535{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007536 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007537
7538 std::stringstream ss;
7539 const size_t numTracks = mOutputTracks.size();
7540 ss << " " << numTracks << " OutputTracks";
7541 if (numTracks > 0) {
7542 ss << ":";
7543 for (const auto &track : mOutputTracks) {
Andy Hung44f27182023-07-06 20:56:16 -07007544 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007545 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007546 if (thread.get() != nullptr) {
7547 ss << thread.get() << ", " << thread->id();
7548 } else {
7549 ss << "null";
7550 }
7551 ss << ")";
7552 }
7553 }
7554 ss << "\n";
7555 std::string result = ss.str();
7556 write(fd, result.c_str(), result.size());
7557}
7558
Andy Hung71742ab2023-07-07 13:47:37 -07007559void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007560{
7561 outputTracks = mOutputTracks;
7562}
7563
Andy Hung71742ab2023-07-07 13:47:37 -07007564void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007565{
7566 outputTracks.clear();
7567}
7568
Andy Hung71742ab2023-07-07 13:47:37 -07007569void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007570{
7571 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007572 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7573 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7574 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7575 const size_t frameCount =
7576 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7577 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7578 // from different OutputTracks and their associated MixerThreads (e.g. one may
7579 // nearly empty and the other may be dropping data).
7580
Svet Ganov33761132021-05-13 22:51:08 +00007581 // TODO b/182392769: use attribution source util, move to server edge
7582 AttributionSourceState attributionSource = AttributionSourceState();
7583 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007584 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007585 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007586 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007587 attributionSource.token = sp<BBinder>::make();
Andy Hung3ff4b552023-06-26 19:20:57 -07007588 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007589 this,
7590 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007591 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007592 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007593 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007594 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007595 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7596 if (status != NO_ERROR) {
7597 ALOGE("addOutputTrack() initCheck failed %d", status);
7598 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007599 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007600 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7601 mOutputTracks.add(outputTrack);
7602 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7603 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007604}
7605
Andy Hung71742ab2023-07-07 13:47:37 -07007606void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007607{
7608 Mutex::Autolock _l(mLock);
7609 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7610 if (mOutputTracks[i]->thread() == thread) {
7611 mOutputTracks[i]->destroy();
7612 mOutputTracks.removeAt(i);
7613 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007614 if (thread->getOutput() == mOutput) {
7615 mOutput = NULL;
7616 }
Eric Laurent81784c32012-11-19 14:55:58 -08007617 return;
7618 }
7619 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007620 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007621}
7622
7623// caller must hold mLock
Andy Hung71742ab2023-07-07 13:47:37 -07007624void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007625{
7626 mWaitTimeMs = UINT_MAX;
7627 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung44f27182023-07-06 20:56:16 -07007628 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007629 if (strong != 0) {
7630 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7631 if (waitTimeMs < mWaitTimeMs) {
7632 mWaitTimeMs = waitTimeMs;
7633 }
7634 }
7635 }
7636}
7637
Andy Hung71742ab2023-07-07 13:47:37 -07007638bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007639{
7640 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung44f27182023-07-06 20:56:16 -07007641 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007642 if (thread == 0) {
7643 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7644 outputTracks[i].get());
7645 return false;
7646 }
Andy Hung44f27182023-07-06 20:56:16 -07007647 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007648 // see note at standby() declaration
Andy Hung4989d312023-06-29 21:19:25 -07007649 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007650 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7651 thread.get());
7652 return false;
7653 }
7654 }
7655 return true;
7656}
7657
Andy Hung71742ab2023-07-07 13:47:37 -07007658void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007659 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007660{
Kevin Rocard12381092018-04-11 09:19:59 -07007661 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7662 outputTrack->setMetadatas(metadata.tracks);
7663 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007664}
7665
Andy Hung71742ab2023-07-07 13:47:37 -07007666uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007667{
7668 return (mWaitTimeMs * 1000) / 2;
7669}
7670
Andy Hung71742ab2023-07-07 13:47:37 -07007671void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007672{
7673 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7674 updateWaitTime_l();
7675
7676 MixerThread::cacheParameters_l();
7677}
7678
Eric Laurentb3f315a2021-07-13 15:09:05 +02007679// ----------------------------------------------------------------------------
7680
Andy Hung71742ab2023-07-07 13:47:37 -07007681/* static */
7682sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07007683 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07007684 AudioStreamOut* output,
7685 audio_io_handle_t id,
7686 bool systemReady,
7687 audio_config_base_t* mixerConfig) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007688 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hung71742ab2023-07-07 13:47:37 -07007689}
7690
Andy Hung2cbc2722023-07-17 17:05:00 -07007691SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007692 AudioStreamOut* output,
7693 audio_io_handle_t id,
7694 bool systemReady,
7695 audio_config_base_t *mixerConfig)
Andy Hung2cbc2722023-07-17 17:05:00 -07007696 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007697{
7698}
7699
Andy Hung71742ab2023-07-07 13:47:37 -07007700void SpatializerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01007701 MixerThread::onFirstRef();
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007702
Andy Hung41ccf7f2022-12-14 14:25:49 -08007703 const pid_t tid = getTid();
7704 if (tid == -1) {
7705 // Unusual: PlaybackThread::onFirstRef() should set the threadLoop running.
7706 ALOGW("%s: Cannot update Spatializer mixer thread priority, not running", __func__);
7707 } else {
7708 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
7709 if (priorityBoost > 0) {
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007710 stream()->setHalThreadPriority(priorityBoost);
7711 }
7712 }
Eric Laurent6f9534f2022-05-03 18:15:04 +02007713}
7714
Andy Hung71742ab2023-07-07 13:47:37 -07007715void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent6f9534f2022-05-03 18:15:04 +02007716 // if mSupportedLatencyModes is empty, the HAL stream does not support
7717 // latency mode control and we can exit.
7718 if (mSupportedLatencyModes.empty()) {
7719 return;
7720 }
7721 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7722 if (mSupportedLatencyModes.size() == 1) {
7723 // If the HAL only support one latency mode currently, confirm the choice
7724 latencyMode = mSupportedLatencyModes[0];
7725 } else if (mSupportedLatencyModes.size() > 1) {
7726 // Request low latency if:
7727 // - The low latency mode is requested by the spatializer controller
7728 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7729 // AND
7730 // - At least one active track is spatialized
7731 bool hasSpatializedActiveTrack = false;
7732 for (const auto& track : mActiveTracks) {
7733 if (track->isSpatialized()) {
7734 hasSpatializedActiveTrack = true;
7735 break;
7736 }
7737 }
7738 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7739 latencyMode = AUDIO_LATENCY_MODE_LOW;
7740 }
7741 }
7742
7743 if (latencyMode != mSetLatencyMode) {
7744 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007745 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7746 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent6f9534f2022-05-03 18:15:04 +02007747 if (status == NO_ERROR) {
7748 mSetLatencyMode = latencyMode;
7749 }
7750 }
7751}
7752
Andy Hung71742ab2023-07-07 13:47:37 -07007753status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent6f9534f2022-05-03 18:15:04 +02007754 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7755 return BAD_VALUE;
7756 }
7757 Mutex::Autolock _l(mLock);
7758 mRequestedLatencyMode = mode;
7759 return NO_ERROR;
7760}
7761
Andy Hung71742ab2023-07-07 13:47:37 -07007762void SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007763{
7764 bool hasVirtualizer = false;
7765 bool hasDownMixer = false;
Andy Hungbd72c542023-06-20 18:56:17 -07007766 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007767 {
7768 Mutex::Autolock _l(mLock);
Andy Hungbd72c542023-06-20 18:56:17 -07007769 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007770 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007771 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007772 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7773 }
7774
7775 finalDownMixer = mFinalDownMixer;
7776 mFinalDownMixer.clear();
7777 }
7778
7779 if (hasVirtualizer) {
7780 if (finalDownMixer != nullptr) {
7781 int32_t ret;
Andy Hungbd72c542023-06-20 18:56:17 -07007782 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007783 }
7784 finalDownMixer.clear();
7785 } else if (!hasDownMixer) {
7786 std::vector<effect_descriptor_t> descriptors;
Andy Hung2cbc2722023-07-17 17:05:00 -07007787 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007788 EFFECT_UIID_DOWNMIX, &descriptors);
7789 if (status != NO_ERROR) {
7790 return;
7791 }
7792 ALOG_ASSERT(!descriptors.empty(),
7793 "%s getDescriptors() returned no error but empty list", __func__);
7794
7795 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7796 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007797 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007798
7799 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7800 ALOGW("%s error creating downmixer %d", __func__, status);
7801 finalDownMixer.clear();
7802 } else {
7803 int32_t ret;
Andy Hungbd72c542023-06-20 18:56:17 -07007804 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007805 }
7806 }
7807
7808 {
7809 Mutex::Autolock _l(mLock);
7810 mFinalDownMixer = finalDownMixer;
7811 }
7812}
7813
Eric Laurent81784c32012-11-19 14:55:58 -08007814// ----------------------------------------------------------------------------
7815// Record
7816// ----------------------------------------------------------------------------
7817
Andy Hung2cbc2722023-07-17 17:05:00 -07007818sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung44f27182023-07-06 20:56:16 -07007819 AudioStreamIn* input,
7820 audio_io_handle_t id,
7821 bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007822 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung44f27182023-07-06 20:56:16 -07007823}
7824
Andy Hung2cbc2722023-07-17 17:05:00 -07007825RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007826 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007827 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007828 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007829 ) :
Andy Hung2cbc2722023-07-17 17:05:00 -07007830 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007831 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007832 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007833 mActiveTracks(&this->mLocalLog),
7834 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007835 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007836 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007837 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7838 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007839 // mFastCapture below
7840 , mFastCaptureFutex(0)
7841 // mInputSource
7842 // mPipeSink
7843 // mPipeSource
7844 , mPipeFramesP2(0)
7845 // mPipeMemory
7846 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007847 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007848 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007849{
Glenn Kastend7dca052015-03-05 16:05:54 -08007850 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung2cbc2722023-07-17 17:05:00 -07007851 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007852
George Burgess IVa8f90c12020-05-14 11:27:19 -07007853 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007854 mIsMsdDevice = strcmp(
7855 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7856 }
7857
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007858 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007859
Andy Hungc8fddf32018-08-08 18:32:37 -07007860 // TODO: We may also match on address as well as device type for
7861 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007862 // TODO: This property should be ensure that only contains one single device type.
7863 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7864 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007865 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7866 : AUDIO_DEVICE_NONE));
7867
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007868 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007869 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007870 size_t numCounterOffers = 0;
7871 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007872#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007873 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007874#else
7875 (void)
7876#endif
7877 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007878 ALOG_ASSERT(index == 0);
7879
7880 // initialize fast capture depending on configuration
7881 bool initFastCapture;
7882 switch (kUseFastCapture) {
7883 case FastCapture_Never:
7884 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007885 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007886 break;
7887 case FastCapture_Always:
7888 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007889 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007890 break;
7891 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007892 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
7893 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7894 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d "
7895 "mIsMsdDevice = %d", this, (long long)mFrameCount, mSampleRate,
7896 kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007897 break;
7898 // case FastCapture_Dynamic:
7899 }
7900
7901 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007902 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007903 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007904 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7905 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007906 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007907 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007908 const sp<MemoryDealer> roHeap(readOnlyHeap());
7909 sp<IMemory> pipeMemory;
7910 if ((roHeap == 0) ||
7911 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007912 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007913 ALOGE("not enough memory for pipe buffer size=%zu; "
7914 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7915 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7916 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007917 goto failed;
7918 }
7919 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7920 memset(pipeBuffer, 0, pipeSize);
7921 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07007922 const NBAIO_Format offersFast[1] = {format};
7923 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007924 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung71ba4b32022-10-06 12:09:49 -07007925 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007926 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007927 mPipeSink = pipe;
7928 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung71ba4b32022-10-06 12:09:49 -07007929 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007930 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung71ba4b32022-10-06 12:09:49 -07007931 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007932 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007933 mPipeSource = pipeReader;
7934 mPipeFramesP2 = pipeFramesP2;
7935 mPipeMemory = pipeMemory;
7936
7937 // create fast capture
7938 mFastCapture = new FastCapture();
7939 FastCaptureStateQueue *sq = mFastCapture->sq();
7940#ifdef STATE_QUEUE_DUMP
7941 // FIXME
7942#endif
7943 FastCaptureState *state = sq->begin();
7944 state->mCblk = NULL;
7945 state->mInputSource = mInputSource.get();
7946 state->mInputSourceGen++;
7947 state->mPipeSink = pipe;
7948 state->mPipeSinkGen++;
7949 state->mFrameCount = mFrameCount;
7950 state->mCommand = FastCaptureState::COLD_IDLE;
7951 // already done in constructor initialization list
7952 //mFastCaptureFutex = 0;
7953 state->mColdFutexAddr = &mFastCaptureFutex;
7954 state->mColdGen++;
7955 state->mDumpState = &mFastCaptureDumpState;
7956#ifdef TEE_SINK
7957 // FIXME
7958#endif
Andy Hung2cbc2722023-07-17 17:05:00 -07007959 mFastCaptureNBLogWriter =
7960 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007961 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7962 sq->end();
7963 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7964
7965 // start the fast capture
7966 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7967 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007968 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007969 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007970#ifdef AUDIO_WATCHDOG
7971 // FIXME
7972#endif
7973
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007974 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007975 }
Andy Hung8946a282018-04-19 20:04:56 -07007976#ifdef TEE_SINK
7977 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7978 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7979#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007980failed: ;
7981
7982 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007983}
7984
Andy Hung71742ab2023-07-07 13:47:37 -07007985RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007986{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007987 if (mFastCapture != 0) {
7988 FastCaptureStateQueue *sq = mFastCapture->sq();
7989 FastCaptureState *state = sq->begin();
7990 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7991 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7992 if (old == -1) {
7993 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7994 }
7995 }
7996 state->mCommand = FastCaptureState::EXIT;
7997 sq->end();
7998 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7999 mFastCapture->join();
8000 mFastCapture.clear();
8001 }
Andy Hung2cbc2722023-07-17 17:05:00 -07008002 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8003 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008004 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008005}
8006
Andy Hung71742ab2023-07-07 13:47:37 -07008007void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008008{
Glenn Kastend7dca052015-03-05 16:05:54 -08008009 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008010}
8011
Andy Hung71742ab2023-07-07 13:47:37 -07008012void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008013{
8014 ALOGV(" preExit()");
8015 Mutex::Autolock _l(mLock);
8016 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008017 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008018 track->invalidate();
8019 }
8020 mActiveTracks.clear();
8021 mStartStopCond.broadcast();
8022}
8023
Andy Hung71742ab2023-07-07 13:47:37 -07008024bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008025{
Eric Laurent81784c32012-11-19 14:55:58 -08008026 nsecs_t lastWarning = 0;
8027
8028 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008029
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008030reacquire_wakelock:
Andy Hung3ff4b552023-06-26 19:20:57 -07008031 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008032 {
8033 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07008034 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008035 }
8036
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008037 // used to request a deferred sleep, to be executed later while mutex is unlocked
8038 uint32_t sleepUs = 0;
8039
Andy Hung446f4df2019-02-21 12:26:41 -08008040 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8041
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008042 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008043 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hungbd72c542023-06-20 18:56:17 -07008044 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008045
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008046 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung3ff4b552023-06-26 19:20:57 -07008047 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008048
Glenn Kasten735f45f2014-08-18 15:51:59 -07008049 // reference to the (first and only) active fast track
Andy Hung3ff4b552023-06-26 19:20:57 -07008050 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008051
Glenn Kasten735f45f2014-08-18 15:51:59 -07008052 // reference to a fast track which is about to be removed
Andy Hung3ff4b552023-06-26 19:20:57 -07008053 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008054
Eric Laurent33403f02020-05-29 18:35:06 -07008055 bool silenceFastCapture = false;
8056
Eric Laurent81784c32012-11-19 14:55:58 -08008057 { // scope for mLock
8058 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08008059
Eric Laurent021cf962014-05-13 10:18:14 -07008060 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008061
Eric Laurent000a4192014-01-29 15:17:32 -08008062 // check exitPending here because checkForNewParameters_l() and
8063 // checkForNewParameters_l() can temporarily release mLock
8064 if (exitPending()) {
8065 break;
8066 }
8067
Eric Laurent5c25d562016-07-13 17:17:45 -07008068 // sleep with mutex unlocked
8069 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008070 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07008071 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
8072 ATRACE_END();
8073 sleepUs = 0;
8074 continue;
8075 }
8076
Glenn Kasten2b806402013-11-20 16:37:38 -08008077 // if no active track(s), then standby and release wakelock
8078 size_t size = mActiveTracks.size();
8079 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008080 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008081 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008082 releaseWakeLock_l();
8083 ALOGV("RecordThread: loop stopping");
8084 // go to sleep
8085 mWaitWorkCV.wait(mLock);
8086 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008087 goto reacquire_wakelock;
8088 }
8089
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008090 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008091 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008092 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008093
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008094 activeTrack = mActiveTracks[i];
8095 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008096 if (activeTrack->isFastTrack()) {
8097 ALOG_ASSERT(fastTrackToRemove == 0);
8098 fastTrackToRemove = activeTrack;
8099 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008100 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008101 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008102 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008103 continue;
8104 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008105
Andy Hung3ff4b552023-06-26 19:20:57 -07008106 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008107 switch (activeTrackState) {
8108
Andy Hung3ff4b552023-06-26 19:20:57 -07008109 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008110 mActiveTracks.remove(activeTrack);
Andy Hung3ff4b552023-06-26 19:20:57 -07008111 activeTrack->setState(IAfTrackBase::PAUSED);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008112 doBroadcast = true;
8113 size--;
8114 continue;
8115
Andy Hung3ff4b552023-06-26 19:20:57 -07008116 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008117 sleepUs = 10000;
8118 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008119 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008120 continue;
8121
Andy Hung3ff4b552023-06-26 19:20:57 -07008122 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008123 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008124 if (mStandby) {
8125 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008126 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008127 mStandby = false;
8128 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008129 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008130 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008131 break;
8132
Andy Hung3ff4b552023-06-26 19:20:57 -07008133 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008134 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008135 break;
8136
Andy Hung3ff4b552023-06-26 19:20:57 -07008137 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8138 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8139 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008140 default:
Andy Hungce685402018-10-05 17:23:27 -07008141 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8142 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008143 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008144
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008145 if (activeTrack->isFastTrack()) {
8146 ALOG_ASSERT(!mFastTrackAvail);
8147 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008148 // if the active fast track is silenced either:
8149 // 1) silence the whole capture from fast capture buffer if this is
8150 // the only active track
8151 // 2) invalidate this track: this will cause the client to reconnect and possibly
8152 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008153 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008154 if (activeTrack->isSilenced()) {
8155 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008156 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008157 } else {
8158 silenceFastCapture = true;
8159 }
8160 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008161 // Invalidate fast tracks if access to audio history is required as this is not
8162 // possible with fast tracks. Once the fast track has been invalidated, no new
8163 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8164 if (mMaxSharedAudioHistoryMs != 0) {
8165 invalidate = true;
8166 }
8167 if (invalidate) {
8168 activeTrack->invalidate();
8169 ALOG_ASSERT(fastTrackToRemove == 0);
8170 fastTrackToRemove = activeTrack;
8171 removeTrack_l(activeTrack);
8172 mActiveTracks.remove(activeTrack);
8173 size--;
8174 continue;
8175 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008176 fastTrack = activeTrack;
8177 }
Eric Laurent33403f02020-05-29 18:35:06 -07008178
8179 activeTracks.add(activeTrack);
8180 i++;
8181
Glenn Kasten9e982352013-08-14 14:39:50 -07008182 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008183
Andy Hungdae27702016-10-31 14:01:16 -07008184 mActiveTracks.updatePowerState(this);
8185
Kevin Rocard069c2712018-03-29 19:09:14 -07008186 updateMetadata_l();
8187
Eric Laurent5c25d562016-07-13 17:17:45 -07008188 if (allStopped) {
8189 standbyIfNotAlreadyInStandby();
8190 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008191 if (doBroadcast) {
8192 mStartStopCond.broadcast();
8193 }
8194
8195 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008196 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008197 if (sleepUs == 0) {
8198 sleepUs = kRecordThreadSleepUs;
8199 }
8200 continue;
8201 }
8202 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008203
Eric Laurent81784c32012-11-19 14:55:58 -08008204 lockEffectChains_l(effectChains);
8205 }
8206
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008207 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008208
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008209 size_t size = effectChains.size();
8210 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008211 // thread mutex is not locked, but effect chain is locked
8212 effectChains[i]->process_l();
8213 }
8214
Glenn Kasten735f45f2014-08-18 15:51:59 -07008215 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008216 if (mFastCapture != 0) {
8217 FastCaptureStateQueue *sq = mFastCapture->sq();
8218 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008219 bool didModify = false;
8220 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008221 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8222 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8223 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8224 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8225 if (old == -1) {
8226 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8227 }
8228 }
8229 state->mCommand = FastCaptureState::READ_WRITE;
8230#if 0 // FIXME
Andy Hung2cbc2722023-07-17 17:05:00 -07008231 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008232 FastThreadDumpState::kSamplingNforLowRamDevice :
8233 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008234#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008235 didModify = true;
8236 }
8237 audio_track_cblk_t *cblkOld = state->mCblk;
8238 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8239 if (cblkNew != cblkOld) {
8240 state->mCblk = cblkNew;
8241 // block until acked if removing a fast track
8242 if (cblkOld != NULL) {
8243 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8244 }
8245 didModify = true;
8246 }
jiabin01c8f562018-07-19 17:47:28 -07008247 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8248 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8249 if (state->mFastPatchRecordBufferProvider != abp) {
8250 state->mFastPatchRecordBufferProvider = abp;
8251 state->mFastPatchRecordFormat = fastTrack == 0 ?
8252 AUDIO_FORMAT_INVALID : fastTrack->format();
8253 didModify = true;
8254 }
Eric Laurent33403f02020-05-29 18:35:06 -07008255 if (state->mSilenceCapture != silenceFastCapture) {
8256 state->mSilenceCapture = silenceFastCapture;
8257 didModify = true;
8258 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008259 sq->end(didModify);
8260 if (didModify) {
8261 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008262#if 0
8263 if (kUseFastCapture == FastCapture_Dynamic) {
8264 mNormalSource = mPipeSource;
8265 }
8266#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008267 }
8268 }
8269
Glenn Kasten735f45f2014-08-18 15:51:59 -07008270 // now run the fast track destructor with thread mutex unlocked
8271 fastTrackToRemove.clear();
8272
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008273 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8274 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8275 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8276 // If destination is non-contiguous, first read past the nominal end of buffer, then
8277 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008278
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008279 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung71ba4b32022-10-06 12:09:49 -07008280 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008281 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008282
8283 // If an NBAIO source is present, use it to read the normal capture's data
8284 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008285 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008286
8287 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8288 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8289 // we immediately retry the read() to get data and prevent another overflow.
8290 for (int retries = 0; retries <= 2; ++retries) {
8291 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8292 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8293 framesToRead);
8294 if (framesRead != OVERRUN) break;
8295 }
8296
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008297 const ssize_t availableToRead = mPipeSource->availableToRead();
8298 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008299 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008300 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008301 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8302 "more frames to read than fifo size, %zd > %zu",
8303 availableToRead, mPipeFramesP2);
8304 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8305 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8306 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8307 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008308 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8309 }
8310 if (framesRead < 0) {
8311 status_t status = (status_t) framesRead;
8312 switch (status) {
8313 case OVERRUN:
8314 ALOGW("overrun on read from pipe");
8315 framesRead = 0;
8316 break;
8317 case NEGOTIATE:
8318 ALOGE("re-negotiation is needed");
8319 framesRead = -1; // Will cause an attempt to recover.
8320 break;
8321 default:
8322 ALOGE("unknown error %d on read from pipe", status);
8323 break;
8324 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008325 }
8326 // otherwise use the HAL / AudioStreamIn directly
8327 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008328 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008329 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008330 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008331 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008332 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008333 if (result < 0) {
8334 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008335 } else {
8336 framesRead = bytesRead / mFrameSize;
8337 }
8338 }
8339
Andy Hung446f4df2019-02-21 12:26:41 -08008340 const int64_t lastIoEndNs = systemTime(); // end IO timing
8341
Andy Hung3f0c9022016-01-15 17:49:46 -08008342 // Update server timestamp with server stats
8343 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008344 if (framesRead >= 0) {
8345 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8346 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8347 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008348
8349 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008350 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008351 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008352 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008353 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8354 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8355 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008356 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008357 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8358
8359 mTimestampVerifier.add(position, time, mSampleRate);
8360
8361 // Correct timestamps
8362 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008363 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008364 id(), (long long)time, (long long)position);
8365 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8366 position = correctedTimestamp.mFrames;
8367 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008368 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008369 id(), (long long)time, (long long)position);
8370 }
8371
Andy Hung3f0c9022016-01-15 17:49:46 -08008372 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8373 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8374 // Note: In general record buffers should tend to be empty in
8375 // a properly running pipeline.
8376 //
8377 // Also, it is not advantageous to call get_presentation_position during the read
8378 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008379 } else {
8380 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008381 }
8382 }
Andy Hunge6c37112019-02-26 17:38:10 -08008383
8384 // From the timestamp, input read latency is negative output write latency.
8385 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung3ff4b552023-06-26 19:20:57 -07008386 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008387 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8388 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8389 mLatencyMs.add(latencyMs);
8390 }
8391
Andy Hung3f0c9022016-01-15 17:49:46 -08008392 // Use this to track timestamp information
8393 // ALOGD("%s", mTimestamp.toString().c_str());
8394
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008395 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008396 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008397 // Force input into standby so that it tries to recover at next read attempt
8398 inputStandBy();
8399 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008400 }
8401 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008402 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008403 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008404 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008405 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008406
Andy Hung8946a282018-04-19 20:04:56 -07008407#ifdef TEE_SINK
8408 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8409#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008410 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008411 {
8412 size_t part1 = mRsmpInFramesP2 - rear;
8413 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008414 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008415 (framesRead - part1) * mFrameSize);
8416 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008417 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008418 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008419
8420 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008421
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008422 // loop over each active track
8423 for (size_t i = 0; i < size; i++) {
8424 activeTrack = activeTracks[i];
8425
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008426 // skip fast tracks, as those are handled directly by FastCapture
8427 if (activeTrack->isFastTrack()) {
8428 continue;
8429 }
8430
Andy Hung73c02e42015-03-29 01:13:58 -07008431 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008432 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8433
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008434 enum {
8435 OVERRUN_UNKNOWN,
8436 OVERRUN_TRUE,
8437 OVERRUN_FALSE
8438 } overrun = OVERRUN_UNKNOWN;
8439
8440 // loop over getNextBuffer to handle circular sink
8441 for (;;) {
8442
Andy Hung3ff4b552023-06-26 19:20:57 -07008443 activeTrack->sinkBuffer().frameCount = ~0;
8444 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8445 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008446 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8447
Andy Hung73c02e42015-03-29 01:13:58 -07008448 // check available frames and handle overrun conditions
8449 // if the record track isn't draining fast enough.
8450 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008451 size_t framesIn;
Andy Hung3ff4b552023-06-26 19:20:57 -07008452 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008453 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008454 overrun = OVERRUN_TRUE;
8455 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008456 if (framesOut == 0 || framesIn == 0) {
8457 break;
8458 }
8459
Andy Hung6770c6f2015-04-07 13:43:36 -07008460 // Don't allow framesOut to be larger than what is possible with resampling
8461 // from framesIn.
8462 // This isn't strictly necessary but helps limit buffer resizing in
8463 // RecordBufferConverter. TODO: remove when no longer needed.
8464 framesOut = min(framesOut,
8465 destinationFramesPossible(
Andy Hung3ff4b552023-06-26 19:20:57 -07008466 framesIn, mSampleRate, activeTrack->sampleRate()));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008467
8468 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008469 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008470 // straight from RecordThread buffer to RecordTrack buffer.
8471 AudioBufferProvider::Buffer buffer;
8472 buffer.frameCount = framesOut;
Andy Hung71ba4b32022-10-06 12:09:49 -07008473 const status_t getNextBufferStatus =
Andy Hung3ff4b552023-06-26 19:20:57 -07008474 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07008475 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008476 ALOGV_IF(buffer.frameCount != framesOut,
8477 "%s() read less than expected (%zu vs %zu)",
8478 __func__, buffer.frameCount, framesOut);
8479 framesOut = buffer.frameCount;
Andy Hung3ff4b552023-06-26 19:20:57 -07008480 memcpy(activeTrack->sinkBuffer().raw,
8481 buffer.raw, buffer.frameCount * mFrameSize);
8482 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008483 } else {
8484 framesOut = 0;
8485 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung71ba4b32022-10-06 12:09:49 -07008486 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008487 }
8488 } else {
8489 // process frames from the RecordThread buffer provider to the RecordTrack
8490 // buffer
Andy Hung3ff4b552023-06-26 19:20:57 -07008491 framesOut = activeTrack->recordBufferConverter()->convert(
8492 activeTrack->sinkBuffer().raw,
8493 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008494 framesOut);
8495 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008496
8497 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8498 overrun = OVERRUN_FALSE;
8499 }
8500
Andy Hung93bb5732023-05-04 21:16:34 -07008501 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8502 const ssize_t framesToDrop =
Andy Hung3ff4b552023-06-26 19:20:57 -07008503 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008504 if (framesToDrop == 0) {
8505 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008506 if (framesOut > 0) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008507 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008508 // Sanitize before releasing if the track has no access to the source data
8509 // An idle UID receives silence from non virtual devices until active
8510 if (activeTrack->isSilenced()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008511 memset(activeTrack->sinkBuffer().raw,
8512 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008513 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008514 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008515 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008516 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008517 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008518 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008519 }
8520 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008521
8522 switch (overrun) {
8523 case OVERRUN_TRUE:
8524 // client isn't retrieving buffers fast enough
8525 if (!activeTrack->setOverflow()) {
8526 nsecs_t now = systemTime();
8527 // FIXME should lastWarning per track?
8528 if ((now - lastWarning) > kWarningThrottleNs) {
8529 ALOGW("RecordThread: buffer overflow");
8530 lastWarning = now;
8531 }
8532 }
8533 break;
8534 case OVERRUN_FALSE:
8535 activeTrack->clearOverflow();
8536 break;
8537 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008538 break;
8539 }
8540
Andy Hung3f0c9022016-01-15 17:49:46 -08008541 // update frame information and push timestamp out
8542 activeTrack->updateTrackFrameInfo(
Andy Hung3ff4b552023-06-26 19:20:57 -07008543 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008544 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8545 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008546 }
8547
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008548unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008549 // enable changes in effect chain
8550 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008551 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008552 if (audio_has_proportional_frames(mFormat)
8553 && loopCount == lastLoopCountRead + 1) {
8554 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8555 const double jitterMs =
8556 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8557 {framesRead, readPeriodNs},
8558 {0, 0} /* lastTimestamp */, mSampleRate);
8559 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8560
8561 Mutex::Autolock _l(mLock);
8562 mIoJitterMs.add(jitterMs);
8563 mProcessTimeMs.add(processMs);
8564 }
8565 // update timing info.
8566 mLastIoBeginNs = lastIoBeginNs;
8567 mLastIoEndNs = lastIoEndNs;
8568 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008569 }
8570
Glenn Kasten93e471f2013-08-19 08:40:07 -07008571 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008572
8573 {
8574 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008575 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008576 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008577 track->invalidate();
8578 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008579 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008580 mStartStopCond.broadcast();
8581 }
8582
8583 releaseWakeLock();
8584
8585 ALOGV("RecordThread %p exiting", this);
8586 return false;
8587}
8588
Andy Hung71742ab2023-07-07 13:47:37 -07008589void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008590{
8591 if (!mStandby) {
8592 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008593 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008594 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008595 mStandby = true;
8596 }
8597}
8598
Andy Hung71742ab2023-07-07 13:47:37 -07008599void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008600{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008601 // Idle the fast capture if it's currently running
8602 if (mFastCapture != 0) {
8603 FastCaptureStateQueue *sq = mFastCapture->sq();
8604 FastCaptureState *state = sq->begin();
8605 if (!(state->mCommand & FastCaptureState::IDLE)) {
8606 state->mCommand = FastCaptureState::COLD_IDLE;
8607 state->mColdFutexAddr = &mFastCaptureFutex;
8608 state->mColdGen++;
8609 mFastCaptureFutex = 0;
8610 sq->end();
8611 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8612 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8613#if 0
8614 if (kUseFastCapture == FastCapture_Dynamic) {
8615 // FIXME
8616 }
8617#endif
8618#ifdef AUDIO_WATCHDOG
8619 // FIXME
8620#endif
8621 } else {
8622 sq->end(false /*didModify*/);
8623 }
8624 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008625 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008626 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008627
8628 // If going into standby, flush the pipe source.
8629 if (mPipeSource.get() != nullptr) {
8630 const ssize_t flushed = mPipeSource->flush();
8631 if (flushed > 0) {
8632 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8633 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8634 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8635 }
8636 }
Eric Laurent81784c32012-11-19 14:55:58 -08008637}
8638
Glenn Kasten05997e22014-03-13 15:08:33 -07008639// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07008640sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hungd65869f2023-06-27 17:05:02 -07008641 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008642 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008643 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008644 audio_format_t format,
8645 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008646 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008647 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008648 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008649 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008650 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008651 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008652 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008653 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008654 audio_port_handle_t portId,
8655 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008656{
Glenn Kasten74935e42013-12-19 08:56:45 -08008657 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008658 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung3ff4b552023-06-26 19:20:57 -07008659 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008660 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008661 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008662 audio_input_flags_t requestedFlags = *flags;
8663 uint32_t sampleRate;
8664
8665 lStatus = initCheck();
8666 if (lStatus != NO_ERROR) {
8667 ALOGE("createRecordTrack_l() audio driver not initialized");
8668 goto Exit;
8669 }
8670
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008671 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8672 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8673 lStatus = BAD_VALUE;
8674 goto Exit;
8675 }
8676
Eric Laurentec376dc2021-04-08 20:41:22 +02008677 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008678 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008679 lStatus = PERMISSION_DENIED;
8680 goto Exit;
8681 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008682 if (maxSharedAudioHistoryMs < 0
8683 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8684 lStatus = BAD_VALUE;
8685 goto Exit;
8686 }
8687 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008688 if (*pSampleRate == 0) {
8689 *pSampleRate = mSampleRate;
8690 }
8691 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008692
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008693 // special case for FAST flag considered OK if fast capture is present and access to
8694 // audio history is not required
8695 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008696 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8697 }
8698
Eric Laurentf14db3c2017-12-08 14:20:36 -08008699 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008700 if ((*flags & inputFlags) != *flags) {
8701 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8702 " input flags (%08x)",
8703 *flags, inputFlags);
8704 *flags = (audio_input_flags_t)(*flags & inputFlags);
8705 }
Eric Laurent81784c32012-11-19 14:55:58 -08008706
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008707 // client expresses a preference for FAST and no access to audio history,
8708 // but we get the final say
8709 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008710 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008711 // we formerly checked for a callback handler (non-0 tid),
8712 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008713 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008714 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008715 // Frame count is not specified (0), or is less than or equal the pipe depth.
8716 // It is OK to provide a higher capacity than requested.
8717 // We will force it to mPipeFramesP2 below.
8718 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008719 // PCM data
8720 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008721 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008722 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008723 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008724 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008725 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008726 hasFastCapture() &&
8727 // there are sufficient fast track slots available
8728 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008729 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008730 // check compatibility with audio effects.
8731 Mutex::Autolock _l(mLock);
8732 // Do not accept FAST flag if the session has software effects
Andy Hungbd72c542023-06-20 18:56:17 -07008733 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008734 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008735 audio_input_flags_t old = *flags;
8736 chain->checkInputFlagCompatibility(flags);
8737 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008738 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8739 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008740 }
8741 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008742 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008743 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8744 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008745 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008746 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8747 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008748 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008749 this, frameCount, mFrameCount, mPipeFramesP2,
8750 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008751 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008752 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008753 }
8754 }
8755
Eric Laurentf14db3c2017-12-08 14:20:36 -08008756 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8757 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8758 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8759 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8760 lStatus = BAD_TYPE;
8761 goto Exit;
8762 }
8763
Glenn Kasten74105912014-07-03 12:28:53 -07008764 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008765 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008766 // fast track: frame count is exactly the pipe depth
8767 frameCount = mPipeFramesP2;
8768 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008769 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008770 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008771 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8772 // or 20 ms if there is a fast capture
8773 // TODO This could be a roundupRatio inline, and const
8774 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8775 * sampleRate + mSampleRate - 1) / mSampleRate;
8776 // minimum number of notification periods is at least kMinNotifications,
8777 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8778 static const size_t kMinNotifications = 3;
8779 static const uint32_t kMinMs = 30;
8780 // TODO This could be a roundupRatio inline
8781 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8782 // TODO This could be a roundupRatio inline
8783 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8784 maxNotificationFrames;
8785 const size_t minFrameCount = maxNotificationFrames *
8786 max(kMinNotifications, minNotificationsByMs);
8787 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008788 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8789 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008790 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008791 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008792 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008793 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008794
8795 { // scope for mLock
8796 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008797 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008798 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008799 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008800 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008801 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008802 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008803 }
Eric Laurent81784c32012-11-19 14:55:58 -08008804
Andy Hung3ff4b552023-06-26 19:20:57 -07008805 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008806 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008807 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung3ff4b552023-06-26 19:20:57 -07008808 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008809 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008810
Glenn Kasten03003332013-08-06 15:40:54 -07008811 lStatus = track->initCheck();
8812 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008813 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008814 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008815 goto Exit;
8816 }
8817 mTracks.add(track);
8818
Eric Laurent05067782016-06-01 18:27:28 -07008819 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008820 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8821 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8822 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008823 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008824 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008825
8826 if (maxSharedAudioHistoryMs != 0) {
8827 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8828 }
Eric Laurent81784c32012-11-19 14:55:58 -08008829 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008830
Eric Laurent81784c32012-11-19 14:55:58 -08008831 lStatus = NO_ERROR;
8832
8833Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008834 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008835 return track;
8836}
8837
Andy Hung71742ab2023-07-07 13:47:37 -07008838status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08008839 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008840 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008841{
8842 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8843 sp<ThreadBase> strongMe = this;
8844 status_t status = NO_ERROR;
8845
8846 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008847 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008848 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008849 recordTrack->synchronizedRecordState().startRecording(
Andy Hung2cbc2722023-07-17 17:05:00 -07008850 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07008851 event, triggerSession,
8852 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08008853 }
8854
8855 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008856 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008857 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008858 if (recordTrack->isInvalid()) {
8859 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008860 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8861 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008862 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008863 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008864 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008865 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8866 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008867 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung3ff4b552023-06-26 19:20:57 -07008868 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008869 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07008870 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008871 }
8872 return status;
8873 }
8874
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008875 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8876 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8877 // or using a separate command thread
Andy Hung3ff4b552023-06-26 19:20:57 -07008878 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08008879 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008880 if (recordTrack->isExternalTrack()) {
8881 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008882 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008883 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008884 if (recordTrack->isInvalid()) {
8885 recordTrack->clearSyncStartEvent();
Andy Hung3ff4b552023-06-26 19:20:57 -07008886 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
8887 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07008888 // STARTING_2 forces destroy to call stopInput.
8889 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008890 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8891 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008892 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008893 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07008894 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung3ff4b552023-06-26 19:20:57 -07008895 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07008896 // Someone else has changed state, let them take over,
8897 // leave mState in the new state.
8898 recordTrack->clearSyncStartEvent();
8899 return INVALID_OPERATION;
8900 }
8901 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008902 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008903 ALOGW("%s(%d): startInput failed, status %d",
8904 __func__, recordTrack->id(), status);
8905 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8906 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008907 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008908 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008909 return status;
8910 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008911 sendIoConfigEvent_l(
8912 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008913 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008914
8915 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8916
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008917 // Catch up with current buffer indices if thread is already running.
8918 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8919 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8920 // see previously buffered data before it called start(), but with greater risk of overrun.
8921
Andy Hung3ff4b552023-06-26 19:20:57 -07008922 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008923 if (!recordTrack->isDirect()) {
8924 // clear any converter state as new data will be discontinuous
Andy Hung3ff4b552023-06-26 19:20:57 -07008925 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008926 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008927 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08008928 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008929 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008930 return status;
8931 }
Eric Laurent81784c32012-11-19 14:55:58 -08008932}
8933
Andy Hung71742ab2023-07-07 13:47:37 -07008934void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08008935{
Andy Hung71742ab2023-07-07 13:47:37 -07008936 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08008937
8938 if (strongEvent != 0) {
Andy Hung02a6c4e2023-06-23 19:27:19 -07008939 sp<IAfTrackBase> ptr =
8940 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
8941 if (ptr != nullptr) {
Andy Hung56126702023-07-14 11:00:08 -07008942 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hung02a6c4e2023-06-23 19:27:19 -07008943 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08008944 }
Eric Laurent81784c32012-11-19 14:55:58 -08008945 }
8946}
8947
Andy Hung71742ab2023-07-07 13:47:37 -07008948bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008949 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008950 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008951 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung3ff4b552023-06-26 19:20:57 -07008952 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008953 return false;
8954 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008955 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung3ff4b552023-06-26 19:20:57 -07008956 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07008957
Andy Hungabfab202019-03-07 19:45:54 -08008958 // NOTE: Waiting here is important to keep stop synchronous.
8959 // This is needed for proper patchRecord peer release.
Andy Hung3ff4b552023-06-26 19:20:57 -07008960 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungce685402018-10-05 17:23:27 -07008961 mWaitWorkCV.broadcast(); // signal thread to stop
8962 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008963 }
Andy Hungce685402018-10-05 17:23:27 -07008964
Andy Hung3ff4b552023-06-26 19:20:57 -07008965 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008966 ALOGV("Record stopped OK");
8967 return true;
8968 }
Andy Hungce685402018-10-05 17:23:27 -07008969
8970 // don't handle anything - we've been invalidated or restarted and in a different state
8971 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung3ff4b552023-06-26 19:20:57 -07008972 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008973 return false;
8974}
8975
Andy Hung71742ab2023-07-07 13:47:37 -07008976bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08008977{
8978 return false;
8979}
8980
Andy Hung71742ab2023-07-07 13:47:37 -07008981status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08008982{
8983#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8984 if (!isValidSyncEvent(event)) {
8985 return BAD_VALUE;
8986 }
8987
Glenn Kastend848eb42016-03-08 13:42:11 -08008988 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008989 status_t ret = NAME_NOT_FOUND;
8990
8991 Mutex::Autolock _l(mLock);
8992
8993 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008994 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08008995 if (eventSession == track->sessionId()) {
8996 (void) track->setSyncEvent(event);
8997 ret = NO_ERROR;
8998 }
8999 }
9000 return ret;
9001#else
9002 return BAD_VALUE;
9003#endif
9004}
9005
Andy Hung71742ab2023-07-07 13:47:37 -07009006status_t RecordThread::getActiveMicrophones(
Andy Hung44f27182023-07-06 20:56:16 -07009007 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009008{
9009 ALOGV("RecordThread::getActiveMicrophones");
9010 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009011 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009012 return NO_INIT;
9013 }
jiabin9ff780e2018-03-19 18:19:52 -07009014 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9015 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009016}
9017
Andy Hung71742ab2023-07-07 13:47:37 -07009018status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009019 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009020{
Paul McLean12340082019-03-19 09:35:05 -06009021 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009022 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009023 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009024 return NO_INIT;
9025 }
Paul McLean12340082019-03-19 09:35:05 -06009026 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009027}
9028
Andy Hung71742ab2023-07-07 13:47:37 -07009029status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009030{
Paul McLean12340082019-03-19 09:35:05 -06009031 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009032 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009033 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009034 return NO_INIT;
9035 }
Paul McLean12340082019-03-19 09:35:05 -06009036 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009037}
9038
Andy Hung71742ab2023-07-07 13:47:37 -07009039status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009040 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9041 int64_t sharedAudioStartMs) {
9042 AutoMutex _l(mLock);
9043 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9044}
9045
Andy Hung71742ab2023-07-07 13:47:37 -07009046status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009047 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9048 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009049
Eric Laurentec376dc2021-04-08 20:41:22 +02009050 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9051 return BAD_VALUE;
9052 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009053
9054 if (sharedAudioStartMs < 0
9055 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009056 return BAD_VALUE;
9057 }
9058
Eric Laurent2407ce32021-04-26 14:56:03 +02009059 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9060 // As we cannot detect more than one wraparound, only accept values up current write position
9061 // after one wraparound
9062 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9063 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009064 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009065 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9066 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009067 // Bring the start frame position within the input buffer to match the documented
9068 // "best effort" behavior of the API.
9069 if (sharedOffset < 0) {
9070 sharedAudioStartFrames = mRsmpInRear;
Andy Hung71ba4b32022-10-06 12:09:49 -07009071 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009072 sharedAudioStartFrames =
9073 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009074 }
9075
Eric Laurentec376dc2021-04-08 20:41:22 +02009076 mSharedAudioPackageName = sharedAudioPackageName;
9077 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009078 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009079 } else {
9080 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009081 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009082 }
9083 return NO_ERROR;
9084}
9085
Andy Hung71742ab2023-07-07 13:47:37 -07009086void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009087 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9088 mSharedAudioStartFrames = -1;
9089 mSharedAudioPackageName = "";
9090}
9091
Andy Hung71742ab2023-07-07 13:47:37 -07009092ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009093{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009094 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009095 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009096 }
9097 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009098 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung3ff4b552023-06-26 19:20:57 -07009099 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009100 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009101 }
9102 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009103 MetadataUpdate change;
9104 change.recordMetadataUpdate = metadata.tracks;
9105 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009106}
9107
Eric Laurent81784c32012-11-19 14:55:58 -08009108// destroyTrack_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07009109void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009110{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009111 track->terminate();
Andy Hung3ff4b552023-06-26 19:20:57 -07009112 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009113
Eric Laurent81784c32012-11-19 14:55:58 -08009114 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009115 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009116 removeTrack_l(track);
9117 }
9118}
9119
Andy Hung71742ab2023-07-07 13:47:37 -07009120void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009121{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009122 String8 result;
9123 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00009124 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009125
Eric Laurent81784c32012-11-19 14:55:58 -08009126 mTracks.remove(track);
9127 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009128 if (track->isFastTrack()) {
9129 ALOG_ASSERT(!mFastTrackAvail);
9130 mFastTrackAvail = true;
9131 }
Eric Laurent81784c32012-11-19 14:55:58 -08009132}
9133
Andy Hung71742ab2023-07-07 13:47:37 -07009134void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009135{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009136 AudioStreamIn *input = mInput;
9137 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9138 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009139 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009140 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009141 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009142 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009143 }
Andy Hungbfa64962017-06-12 14:43:19 -07009144
9145 if (input != nullptr) {
9146 dprintf(fd, " Hal stream dump:\n");
9147 (void)input->stream->dump(fd);
9148 }
9149
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009150 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009151 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009152
Glenn Kasten2f90c512015-12-02 11:40:09 -08009153 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9154 // while we are dumping it. It may be inconsistent, but it won't mutate!
9155 // This is a large object so we place it on the heap.
9156 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009157 const std::unique_ptr<FastCaptureDumpState> copy =
9158 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009159 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009160}
9161
Andy Hung71742ab2023-07-07 13:47:37 -07009162void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009163{
Eric Laurent81784c32012-11-19 14:55:58 -08009164 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009165 size_t numtracks = mTracks.size();
9166 size_t numactive = mActiveTracks.size();
9167 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009168 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009169 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009170 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009171 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009172 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009173 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009174 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009175 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009176 if (track != 0) {
9177 bool active = mActiveTracks.indexOf(track) >= 0;
9178 if (active) {
9179 numactiveseen++;
9180 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009181 result.append(prefix);
9182 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009183 }
Eric Laurent81784c32012-11-19 14:55:58 -08009184 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009185 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009186 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009187 }
9188
Marco Nelissenb2208842014-02-07 14:00:50 -08009189 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009190 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009191 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009192 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009193 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009194 for (size_t i = 0; i < numactive; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009195 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009196 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009197 result.append(prefix);
9198 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009199 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009200 }
Eric Laurent81784c32012-11-19 14:55:58 -08009201
9202 }
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00009203 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009204}
9205
Andy Hung71742ab2023-07-07 13:47:37 -07009206void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009207{
9208 Mutex::Autolock _l(mLock);
9209 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009210 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009211 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009212 track->setSilenced(silenced);
9213 }
9214 }
9215}
Andy Hung73c02e42015-03-29 01:13:58 -07009216
Andy Hung3ff4b552023-06-26 19:20:57 -07009217void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009218{
Andy Hung44f27182023-07-06 20:56:16 -07009219 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung71742ab2023-07-07 13:47:37 -07009220 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009221 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009222 const int32_t rear = recordThread->mRsmpInRear;
9223 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009224 if (mRecordTrack->startFrames() >= 0) {
9225 int32_t startFrames = mRecordTrack->startFrames();
9226 // Accept a recent wraparound of mRsmpInRear
9227 if (startFrames <= rear) {
9228 deltaFrames = rear - startFrames;
9229 } else {
9230 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009231 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009232 // start frame cannot be further in the past than start of resampling buffer
9233 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9234 deltaFrames = recordThread->mRsmpInFrames;
9235 }
9236 }
9237 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009238}
9239
Andy Hung3ff4b552023-06-26 19:20:57 -07009240void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009241 size_t *framesAvailable, bool *hasOverrun)
9242{
Andy Hung44f27182023-07-06 20:56:16 -07009243 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung71742ab2023-07-07 13:47:37 -07009244 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009245 const int32_t rear = recordThread->mRsmpInRear;
9246 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009247 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009248
9249 size_t framesIn;
9250 bool overrun = false;
9251 if (filled < 0) {
9252 // should not happen, but treat like a massive overrun and re-sync
9253 framesIn = 0;
9254 mRsmpInFront = rear;
9255 overrun = true;
9256 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9257 framesIn = (size_t) filled;
9258 } else {
9259 // client is not keeping up with server, but give it latest data
9260 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009261 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9262 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009263 overrun = true;
9264 }
9265 if (framesAvailable != NULL) {
9266 *framesAvailable = framesIn;
9267 }
9268 if (hasOverrun != NULL) {
9269 *hasOverrun = overrun;
9270 }
9271}
9272
Eric Laurent81784c32012-11-19 14:55:58 -08009273// AudioBufferProvider interface
Andy Hung3ff4b552023-06-26 19:20:57 -07009274status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009275 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009276{
Andy Hung44f27182023-07-06 20:56:16 -07009277 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009278 if (threadBase == 0) {
9279 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009280 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009281 return NOT_ENOUGH_DATA;
9282 }
Andy Hung71742ab2023-07-07 13:47:37 -07009283 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009284 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009285 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009286 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009287 // FIXME should not be P2 (don't want to increase latency)
9288 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009289 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009290 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009291
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009292 front &= recordThread->mRsmpInFramesP2 - 1;
9293 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009294 if (part1 > (size_t) filled) {
9295 part1 = filled;
9296 }
9297 size_t ask = buffer->frameCount;
9298 ALOG_ASSERT(ask > 0);
9299 if (part1 > ask) {
9300 part1 = ask;
9301 }
9302 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009303 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009304 buffer->raw = NULL;
9305 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009306 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009307 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009308 }
9309
Andy Hung57446612015-04-19 23:56:46 -07009310 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009311 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009312 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009313 return NO_ERROR;
9314}
9315
9316// AudioBufferProvider interface
Andy Hung3ff4b552023-06-26 19:20:57 -07009317void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009318 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009319{
Hongwei Wang95e37682019-04-12 11:13:36 -07009320 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009321 if (stepCount == 0) {
9322 return;
9323 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009324 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009325 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009326 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009327 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009328 buffer->frameCount = 0;
9329}
9330
Andy Hung71742ab2023-07-07 13:47:37 -07009331void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009332{
9333 Mutex::Autolock _l(mLock);
9334 checkBtNrec_l();
9335}
9336
Andy Hung71742ab2023-07-07 13:47:37 -07009337void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009338{
9339 // disable AEC and NS if the device is a BT SCO headset supporting those
9340 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009341 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Andy Hung2cbc2722023-07-17 17:05:00 -07009342 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009343 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9344 for (size_t i = 0; i < mEffectChains.size(); i++) {
9345 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9346 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9347 }
9348 }
9349}
9350
Andy Hung97a893e2015-03-29 01:03:07 -07009351
Andy Hung71742ab2023-07-07 13:47:37 -07009352bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009353 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009354{
9355 bool reconfig = false;
9356
Eric Laurent10351942014-05-08 18:49:52 -07009357 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009358
Eric Laurent10351942014-05-08 18:49:52 -07009359 audio_format_t reqFormat = mFormat;
9360 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009361 // 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 +08009362 [[maybe_unused]] audio_channel_mask_t channelMask =
9363 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009364
9365 AudioParameter param = AudioParameter(keyValuePair);
9366 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009367
9368 // scope for AutoPark extends to end of method
9369 AutoPark<FastCapture> park(mFastCapture);
9370
Eric Laurent10351942014-05-08 18:49:52 -07009371 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9372 // channel count change can be requested. Do we mandate the first client defines the
9373 // HAL sampling rate and channel count or do we allow changes on the fly?
9374 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9375 samplingRate = value;
9376 reconfig = true;
9377 }
9378 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009379 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009380 status = BAD_VALUE;
9381 } else {
9382 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009383 reconfig = true;
9384 }
Eric Laurent10351942014-05-08 18:49:52 -07009385 }
9386 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9387 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009388 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009389 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009390 status = BAD_VALUE;
9391 } else {
9392 channelMask = mask;
9393 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009394 }
Eric Laurent10351942014-05-08 18:49:52 -07009395 }
9396 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9397 // do not accept frame count changes if tracks are open as the track buffer
9398 // size depends on frame count and correct behavior would not be guaranteed
9399 // if frame count is changed after track creation
9400 if (mActiveTracks.size() > 0) {
9401 status = INVALID_OPERATION;
9402 } else {
9403 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009404 }
Eric Laurent10351942014-05-08 18:49:52 -07009405 }
9406 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009407 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009408 }
9409 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9410 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009411 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009412 }
Glenn Kastene198c362013-08-13 09:13:36 -07009413
Eric Laurent10351942014-05-08 18:49:52 -07009414 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009415 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009416 if (status == INVALID_OPERATION) {
9417 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009418 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009419 }
9420 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009421 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009422 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9423 if (mInput->stream->getAudioProperties(&config) == OK &&
9424 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9425 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009426 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009427 status = NO_ERROR;
9428 }
Eric Laurent81784c32012-11-19 14:55:58 -08009429 }
Eric Laurent10351942014-05-08 18:49:52 -07009430 if (status == NO_ERROR) {
9431 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009432 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009433 }
9434 }
Eric Laurent81784c32012-11-19 14:55:58 -08009435 }
Eric Laurent10351942014-05-08 18:49:52 -07009436
Eric Laurent81784c32012-11-19 14:55:58 -08009437 return reconfig;
9438}
9439
Andy Hung71742ab2023-07-07 13:47:37 -07009440String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009441{
Eric Laurent81784c32012-11-19 14:55:58 -08009442 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009443 if (initCheck() == NO_ERROR) {
9444 String8 out_s8;
9445 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9446 return out_s8;
9447 }
Eric Laurent81784c32012-11-19 14:55:58 -08009448 }
Andy Hung71ba4b32022-10-06 12:09:49 -07009449 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009450}
9451
Andy Hung71742ab2023-07-07 13:47:37 -07009452void RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009453 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009454 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009455 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009456 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009457 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009458 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009459 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9460 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009461 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009462 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009463 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009464 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009465 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009466 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009467 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009468 break;
9469 }
Andy Hung2cbc2722023-07-17 17:05:00 -07009470 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009471}
9472
Andy Hung71742ab2023-07-07 13:47:37 -07009473void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009474{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009475 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9476 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009477 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009478 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9479 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009480 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9481 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009482 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009483 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009484 ALOGI("HAL format %#x is not linear pcm", mFormat);
9485 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009486 result = mInput->stream->getFrameSize(&mFrameSize);
9487 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009488 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9489 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009490 result = mInput->stream->getBufferSize(&mBufferSize);
9491 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009492 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009493 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9494 "mBufferSize=%zu, mFrameCount=%zu",
9495 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009496
Eric Laurentec376dc2021-04-08 20:41:22 +02009497 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9498 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009499 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009500
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009501 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9502 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009503
9504 audio_input_flags_t flags = mInput->flags;
9505 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9506 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9507 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9508 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9509 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9510 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9511 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9512 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9513 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009514}
9515
Andy Hung71742ab2023-07-07 13:47:37 -07009516uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009517{
9518 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009519 uint32_t result;
9520 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9521 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009522 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009523 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009524}
9525
Andy Hung71742ab2023-07-07 13:47:37 -07009526KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009527{
Glenn Kastend848eb42016-03-08 13:42:11 -08009528 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009529 Mutex::Autolock _l(mLock);
9530 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009531 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009532 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009533 if (ids.indexOfKey(sessionId) < 0) {
9534 ids.add(sessionId, true);
9535 }
9536 }
9537 return ids;
9538}
9539
Andy Hung71742ab2023-07-07 13:47:37 -07009540AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009541{
9542 Mutex::Autolock _l(mLock);
9543 AudioStreamIn *input = mInput;
9544 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009545 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009546 return input;
9547}
9548
9549// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hung71742ab2023-07-07 13:47:37 -07009550sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009551{
9552 if (mInput == NULL) {
9553 return NULL;
9554 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009555 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009556}
9557
Andy Hung71742ab2023-07-07 13:47:37 -07009558status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009559{
Eric Laurent81784c32012-11-19 14:55:58 -08009560 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009561 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009562 chain->setInBuffer(NULL);
9563 chain->setOutBuffer(NULL);
9564
9565 checkSuspendOnAddEffectChain_l(chain);
9566
Eric Laurent1b928682014-10-02 19:41:47 -07009567 // make sure enabled pre processing effects state is communicated to the HAL as we
9568 // just moved them to a new input stream.
9569 chain->syncHalEffectsState();
9570
Eric Laurent81784c32012-11-19 14:55:58 -08009571 mEffectChains.add(chain);
9572
9573 return NO_ERROR;
9574}
9575
Andy Hung71742ab2023-07-07 13:47:37 -07009576size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009577{
9578 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009579
9580 for (size_t i = 0; i < mEffectChains.size(); i++) {
9581 if (chain == mEffectChains[i]) {
9582 mEffectChains.removeAt(i);
9583 break;
9584 }
Eric Laurent81784c32012-11-19 14:55:58 -08009585 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009586 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009587}
9588
Andy Hung71742ab2023-07-07 13:47:37 -07009589status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009590 audio_patch_handle_t *handle)
9591{
9592 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009593
9594 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009595 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009596 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009597 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009598 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009599 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009600 }
9601
Eric Laurentd8365c52017-07-16 15:27:05 -07009602 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009603
9604 // store new source and send to effects
9605 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9606 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009607 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009608 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009609 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009610 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009611
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009612 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009613 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9614 status = hwDevice->createAudioPatch(patch->num_sources,
9615 patch->sources,
9616 patch->num_sinks,
9617 patch->sinks,
9618 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009619 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009620 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9621 patch->sinks[0].ext.mix.usecase.source,
9622 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009623 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009624 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009625
jiabinc52b1ff2019-10-31 17:20:42 -07009626 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009627 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009628 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009629 }
Eric Laurent296fb132015-05-01 11:38:42 -07009630
Andy Hungc2b11cb2020-04-22 09:04:01 -07009631 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009632 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009633 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009634 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009635 // also dispatch to active AudioRecords
9636 for (const auto &track : mActiveTracks) {
9637 track->logEndInterval();
9638 track->logBeginInterval(pathSourcesAsString);
9639 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009640 // Force meteadata update after a route change
9641 mActiveTracks.setHasChanged();
9642
Eric Laurent1c333e22014-05-20 10:48:17 -07009643 return status;
9644}
9645
Andy Hung71742ab2023-07-07 13:47:37 -07009646status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009647{
9648 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009649
jiabinc52b1ff2019-10-31 17:20:42 -07009650 mPatch = audio_patch{};
9651 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009652
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009653 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009654 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9655 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009656 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009657 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009658 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009659 // Force meteadata update after a route change
9660 mActiveTracks.setHasChanged();
9661
Eric Laurent1c333e22014-05-20 10:48:17 -07009662 return status;
9663}
9664
Andy Hung71742ab2023-07-07 13:47:37 -07009665void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009666{
wendy lin56aa82b2020-12-02 15:19:55 +08009667 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009668 mOutDevices = outDevices;
9669 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9670 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009671 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009672 }
9673}
9674
Andy Hung71742ab2023-07-07 13:47:37 -07009675int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009676{
9677 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009678 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009679 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009680 int32_t oldestFront = mRsmpInRear;
9681 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009682 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009683 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009684 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009685 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009686 if (filled > maxFilled) {
9687 oldestFront = front;
9688 maxFilled = filled;
9689 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009690 }
Andy Hung71ba4b32022-10-06 12:09:49 -07009691 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009692 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9693 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009694 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009695}
9696
Andy Hung71742ab2023-07-07 13:47:37 -07009697void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009698{
9699 if (offset == 0) {
9700 return;
9701 }
9702 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009703 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009704 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung3ff4b552023-06-26 19:20:57 -07009705 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009706 }
9707}
9708
Andy Hung71742ab2023-07-07 13:47:37 -07009709void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009710{
9711 // This is the formula for calculating the temporary buffer size.
9712 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9713 // 1 full output buffer, regardless of the alignment of the available input.
9714 // The value is somewhat arbitrary, and could probably be even larger.
9715 // A larger value should allow more old data to be read after a track calls start(),
9716 // without increasing latency.
9717 //
9718 // Note this is independent of the maximum downsampling ratio permitted for capture.
9719 size_t minRsmpInFrames = mFrameCount * 7;
9720
9721 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9722 // capture history available to another client using the same session ID:
9723 // dimension the resampler input buffer accordingly.
9724
9725 // Get oldest client read position: getOldestFront_l() must be called before altering
9726 // mRsmpInRear, or mRsmpInFrames
9727 int32_t previousFront = getOldestFront_l();
9728 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9729 int32_t previousRear = mRsmpInRear;
9730 mRsmpInRear = 0;
9731
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009732 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hung71742ab2023-07-07 13:47:37 -07009733 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009734 "resizeInputBuffer_l() called with invalid max shared history %d",
9735 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009736 if (maxSharedAudioHistoryMs != 0) {
9737 // resizeInputBuffer_l should never be called with a non zero shared history if the
9738 // buffer was not already allocated
9739 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9740 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9741 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9742 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009743 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009744 return;
9745 }
9746 mRsmpInFrames = rsmpInFrames;
9747 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009748 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009749 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9750 // initialized
9751 if (mRsmpInFrames < minRsmpInFrames) {
9752 mRsmpInFrames = minRsmpInFrames;
9753 }
9754 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9755
9756 // TODO optimize audio capture buffer sizes ...
9757 // Here we calculate the size of the sliding buffer used as a source
9758 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9759 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9760 // be better to have it derived from the pipe depth in the long term.
9761 // The current value is higher than necessary. However it should not add to latency.
9762
9763 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9764 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9765
9766 void *rsmpInBuffer;
9767 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9768 // if posix_memalign fails, will segv here.
9769 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9770
9771 // Copy audio history if any from old buffer before freeing it
9772 if (previousRear != 0) {
9773 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9774 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9775
9776 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9777 previousFront &= previousRsmpInFramesP2 - 1;
9778 size_t part1 = previousRsmpInFramesP2 - previousFront;
9779 if (part1 > (size_t) unread) {
9780 part1 = unread;
9781 }
9782 if (part1 != 0) {
9783 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9784 part1 * mFrameSize);
9785 mRsmpInRear = part1;
9786 part1 = unread - part1;
9787 if (part1 != 0) {
9788 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9789 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9790 mRsmpInRear += part1;
9791 }
9792 }
9793 // Update front for all clients according to new rear
9794 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9795 } else {
9796 mRsmpInRear = 0;
9797 }
9798 free(mRsmpInBuffer);
9799 mRsmpInBuffer = rsmpInBuffer;
9800}
9801
Andy Hung71742ab2023-07-07 13:47:37 -07009802void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009803{
9804 Mutex::Autolock _l(mLock);
9805 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009806 if (record->getSource()) {
9807 mSource = record->getSource();
9808 }
Eric Laurent83b88082014-06-20 18:31:16 -07009809}
9810
Andy Hung71742ab2023-07-07 13:47:37 -07009811void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009812{
9813 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009814 if (mSource == record->getSource()) {
9815 mSource = mInput;
9816 }
Eric Laurent83b88082014-06-20 18:31:16 -07009817 destroyTrack_l(record);
9818}
9819
Andy Hung71742ab2023-07-07 13:47:37 -07009820void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07009821{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009822 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009823 config->role = AUDIO_PORT_ROLE_SINK;
9824 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9825 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009826 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9827 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9828 config->flags.input = mInput->flags;
9829 }
Eric Laurent83b88082014-06-20 18:31:16 -07009830}
Eric Laurent1c333e22014-05-20 10:48:17 -07009831
Eric Laurent6acd1d42017-01-04 14:23:29 -08009832// ----------------------------------------------------------------------------
9833// Mmap
9834// ----------------------------------------------------------------------------
9835
Andy Hung667dec42023-07-07 15:58:48 -07009836// Mmap stream control interface implementation. Each MmapThreadHandle controls one
9837// MmapPlaybackThread or MmapCaptureThread instance.
9838class MmapThreadHandle : public MmapStreamInterface {
9839public:
9840 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
9841 ~MmapThreadHandle() override;
9842
9843 // MmapStreamInterface virtuals
9844 status_t createMmapBuffer(int32_t minSizeFrames,
9845 struct audio_mmap_buffer_info* info) final;
9846 status_t getMmapPosition(struct audio_mmap_position* position) final;
9847 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
9848 status_t start(const AudioClient& client,
9849 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
9850 status_t stop(audio_port_handle_t handle) final;
9851 status_t standby() final;
9852 status_t reportData(const void* buffer, size_t frameCount) final;
9853private:
9854 const sp<IAfMmapThread> mThread;
9855};
9856
9857/* static */
9858sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
9859 const sp<IAfMmapThread>& mmapThread) {
9860 return sp<MmapThreadHandle>::make(mmapThread);
9861}
9862
9863MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009864 : mThread(thread)
9865{
Phil Burk9fabbf82017-08-03 12:02:00 -07009866 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009867}
9868
Andy Hung667dec42023-07-07 15:58:48 -07009869// MmapStreamInterface could be directly implemented by MmapThread excepting this
9870// special handling on adapter dtor.
9871MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009872{
Phil Burk9fabbf82017-08-03 12:02:00 -07009873 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009874}
9875
Andy Hung667dec42023-07-07 15:58:48 -07009876status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009877 struct audio_mmap_buffer_info *info)
9878{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009879 return mThread->createMmapBuffer(minSizeFrames, info);
9880}
9881
Andy Hung667dec42023-07-07 15:58:48 -07009882status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009883{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009884 return mThread->getMmapPosition(position);
9885}
9886
Andy Hung667dec42023-07-07 15:58:48 -07009887status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -07009888 int64_t *timeNanos) {
9889 return mThread->getExternalPosition(position, timeNanos);
9890}
9891
Andy Hung667dec42023-07-07 15:58:48 -07009892status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009893 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009894{
jiabind1f1cb62020-03-24 11:57:57 -07009895 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009896}
9897
Andy Hung667dec42023-07-07 15:58:48 -07009898status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009899{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009900 return mThread->stop(handle);
9901}
9902
Andy Hung667dec42023-07-07 15:58:48 -07009903status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -08009904{
Eric Laurent18b57012017-02-13 16:23:52 -08009905 return mThread->standby();
9906}
9907
Andy Hung667dec42023-07-07 15:58:48 -07009908status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
9909{
jiabinfc791ee2023-02-15 19:43:40 +00009910 return mThread->reportData(buffer, frameCount);
9911}
9912
Eric Laurent6acd1d42017-01-04 14:23:29 -08009913
Andy Hung71742ab2023-07-07 13:47:37 -07009914MmapThread::MmapThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07009915 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung71ba4b32022-10-06 12:09:49 -07009916 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung2cbc2722023-07-17 17:05:00 -07009917 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009918 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009919 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009920 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009921 mActiveTracks(&this->mLocalLog),
9922 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9923 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009924{
Eric Laurent18b57012017-02-13 16:23:52 -08009925 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009926 readHalParameters_l();
9927}
9928
Andy Hung71742ab2023-07-07 13:47:37 -07009929void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009930{
9931 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9932}
9933
Andy Hung71742ab2023-07-07 13:47:37 -07009934void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009935{
Andy Hung3ff4b552023-06-26 19:20:57 -07009936 ActiveTracks<IAfMmapTrack> activeTracks;
Eric Laurent331679c2018-04-16 17:03:16 -07009937 {
9938 Mutex::Autolock _l(mLock);
Andy Hung3ff4b552023-06-26 19:20:57 -07009939 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -07009940 activeTracks.add(t);
9941 }
9942 }
Andy Hung3ff4b552023-06-26 19:20:57 -07009943 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009944 stop(t->portId());
9945 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009946 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009947 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009948 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009949 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009950 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009951 }
9952}
9953
9954
Andy Hung71742ab2023-07-07 13:47:37 -07009955void MmapThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009956 audio_stream_type_t streamType __unused,
9957 audio_session_t sessionId,
9958 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009959 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009960 audio_port_handle_t portId)
9961{
9962 mAttr = *attr;
9963 mSessionId = sessionId;
9964 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009965 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009966 mPortId = portId;
9967}
9968
Andy Hung71742ab2023-07-07 13:47:37 -07009969status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009970 struct audio_mmap_buffer_info *info)
9971{
9972 if (mHalStream == 0) {
9973 return NO_INIT;
9974 }
Eric Laurent18b57012017-02-13 16:23:52 -08009975 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009976 return mHalStream->createMmapBuffer(minSizeFrames, info);
9977}
9978
Andy Hung71742ab2023-07-07 13:47:37 -07009979status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -08009980{
9981 if (mHalStream == 0) {
9982 return NO_INIT;
9983 }
9984 return mHalStream->getMmapPosition(position);
9985}
9986
Andy Hung71742ab2023-07-07 13:47:37 -07009987status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -07009988{
Eric Laurentdda206a2022-07-08 17:28:35 +02009989 // The HAL must receive track metadata before starting the stream
9990 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -07009991 status_t ret = mHalStream->start();
9992 if (ret != NO_ERROR) {
9993 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9994 return ret;
9995 }
Andy Hungcf10d742020-04-28 15:38:24 -07009996 if (mStandby) {
9997 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009998 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07009999 mStandby = false;
10000 }
Eric Laurent331679c2018-04-16 17:03:16 -070010001 return NO_ERROR;
10002}
10003
Andy Hung71742ab2023-07-07 13:47:37 -070010004status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010005 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010006 audio_port_handle_t *handle)
10007{
Eric Laurenta54f1282017-07-01 19:39:32 -070010008 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010009 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010010 if (mHalStream == 0) {
10011 return NO_INIT;
10012 }
10013
10014 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010015
Eric Laurentdda206a2022-07-08 17:28:35 +020010016 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010017 if (*handle == mPortId) {
Eric Laurentdda206a2022-07-08 17:28:35 +020010018 acquireWakeLock();
10019 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010020 }
10021
10022 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10023
10024 audio_io_handle_t io = mId;
Andy Hungc5106312023-07-19 16:56:19 -070010025 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010026 client.attributionSource);
10027
Eric Laurenta54f1282017-07-01 19:39:32 -070010028 if (isOutput()) {
10029 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10030 config.sample_rate = mSampleRate;
10031 config.channel_mask = mChannelMask;
10032 config.format = mFormat;
10033 audio_stream_type_t stream = streamType();
10034 audio_output_flags_t flags =
10035 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010036 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010037 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010038 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010039 bool isBitPerfect;
Eric Laurenta54f1282017-07-01 19:39:32 -070010040 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
10041 mSessionId,
10042 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010043 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010044 &config,
10045 flags,
10046 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010047 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010048 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010049 &isSpatialized,
10050 &isBitPerfect);
Kevin Rocard153f92d2018-12-18 18:33:28 -080010051 ALOGD_IF(!secondaryOutputs.empty(),
10052 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010053 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010054 audio_config_base_t config;
10055 config.sample_rate = mSampleRate;
10056 config.channel_mask = mChannelMask;
10057 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010058 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -070010059 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010060 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -070010061 mSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010062 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010063 &config,
10064 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10065 &deviceId,
10066 &portId);
10067 }
10068 // APM should not chose a different input or output stream for the same set of attributes
10069 // and audo configuration
10070 if (ret != NO_ERROR || io != mId) {
10071 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10072 __FUNCTION__, ret, io, mId);
10073 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010074 }
10075
10076 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010077 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010078 } else {
jiabincfc10a42022-06-15 19:26:01 +000010079 {
10080 // Add the track record before starting input so that the silent status for the
10081 // client can be cached.
10082 Mutex::Autolock _l(mLock);
10083 setClientSilencedState_l(portId, false /*silenced*/);
10084 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010085 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010086 }
10087
Eric Laurent331679c2018-04-16 17:03:16 -070010088 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010089 // abort if start is rejected by audio policy manager
10090 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010091 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010092 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -070010093 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010094 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010095 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010096 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010097 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010098 }
Eric Laurent331679c2018-04-16 17:03:16 -070010099 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010100 } else {
10101 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010102 }
jiabincfc10a42022-06-15 19:26:01 +000010103 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010104 return PERMISSION_DENIED;
10105 }
10106
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010107 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung3ff4b552023-06-26 19:20:57 -070010108 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10109 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010110 mChannelMask, mSessionId, isOutput(),
10111 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010112 IPCThreadState::self()->getCallingPid(), portId);
jiabincfc10a42022-06-15 19:26:01 +000010113 if (!isOutput()) {
10114 track->setSilenced_l(isClientSilenced_l(portId));
10115 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010116
Eric Laurent4eb58f12018-12-07 16:41:02 -080010117 if (isOutput()) {
10118 // force volume update when a new track is added
10119 mHalVolFloat = -1.0f;
10120 } else if (!track->isSilenced_l()) {
Andy Hung3ff4b552023-06-26 19:20:57 -070010121 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung71ba4b32022-10-06 12:09:49 -070010122 if (t->isSilenced_l()
10123 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010124 t->invalidate();
Andy Hung71ba4b32022-10-06 12:09:49 -070010125 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010126 }
10127 }
10128
Eric Laurent6acd1d42017-01-04 14:23:29 -080010129 mActiveTracks.add(track);
Andy Hungbd72c542023-06-20 18:56:17 -070010130 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010131 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +020010132 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010133 chain->incTrackCnt();
10134 chain->incActiveTrackCnt();
10135 }
10136
Andy Hungc2b11cb2020-04-22 09:04:01 -070010137 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010138 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010139
10140 if (mActiveTracks.size() == 1) {
10141 ret = exitStandby_l();
10142 }
10143
Eric Laurent6acd1d42017-01-04 14:23:29 -080010144 broadcast_l();
10145
Eric Laurentdda206a2022-07-08 17:28:35 +020010146 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010147
Eric Laurentdda206a2022-07-08 17:28:35 +020010148 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010149}
10150
Andy Hung71742ab2023-07-07 13:47:37 -070010151status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010152{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010153 ALOGV("%s handle %d", __FUNCTION__, handle);
10154
10155 if (mHalStream == 0) {
10156 return NO_INIT;
10157 }
10158
Eric Laurenta54f1282017-07-01 19:39:32 -070010159 if (handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +000010160 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -070010161 return NO_ERROR;
10162 }
10163
Eric Laurent331679c2018-04-16 17:03:16 -070010164 Mutex::Autolock _l(mLock);
10165
Andy Hung3ff4b552023-06-26 19:20:57 -070010166 sp<IAfMmapTrack> track;
10167 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010168 if (handle == t->portId()) {
10169 track = t;
10170 break;
10171 }
10172 }
10173 if (track == 0) {
10174 return BAD_VALUE;
10175 }
10176
10177 mActiveTracks.remove(track);
jiabincfc10a42022-06-15 19:26:01 +000010178 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010179
Eric Laurent331679c2018-04-16 17:03:16 -070010180 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010181 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010182 AudioSystem::stopOutput(track->portId());
10183 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010184 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010185 AudioSystem::stopInput(track->portId());
10186 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010187 }
Eric Laurent331679c2018-04-16 17:03:16 -070010188 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010189
Andy Hungbd72c542023-06-20 18:56:17 -070010190 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010191 if (chain != 0) {
10192 chain->decActiveTrackCnt();
10193 chain->decTrackCnt();
10194 }
10195
Eric Laurentdda206a2022-07-08 17:28:35 +020010196 if (mActiveTracks.isEmpty()) {
10197 mHalStream->stop();
10198 }
10199
Eric Laurent6acd1d42017-01-04 14:23:29 -080010200 broadcast_l();
10201
Eric Laurent6acd1d42017-01-04 14:23:29 -080010202 return NO_ERROR;
10203}
10204
Andy Hung71742ab2023-07-07 13:47:37 -070010205status_t MmapThread::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010206{
10207 ALOGV("%s", __FUNCTION__);
10208
10209 if (mHalStream == 0) {
10210 return NO_INIT;
10211 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010212 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010213 return INVALID_OPERATION;
10214 }
10215 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010216 if (!mStandby) {
10217 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010218 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010219 mStandby = true;
10220 }
Eric Laurent18b57012017-02-13 16:23:52 -080010221 releaseWakeLock();
10222 return NO_ERROR;
10223}
10224
Andy Hung71742ab2023-07-07 13:47:37 -070010225status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010226 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10227 return INVALID_OPERATION;
10228}
Eric Laurent6acd1d42017-01-04 14:23:29 -080010229
Andy Hung71742ab2023-07-07 13:47:37 -070010230void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010231{
10232 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10233 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10234 mFormat = mHALFormat;
10235 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10236 result = mHalStream->getFrameSize(&mFrameSize);
10237 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010238 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10239 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010240 result = mHalStream->getBufferSize(&mBufferSize);
10241 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10242 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010243
Andy Hungcf10d742020-04-28 15:38:24 -070010244 // TODO: make a readHalParameters call?
10245 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010246 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
10247 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
10248 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10249 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10250 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10251 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10252 /*
10253 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10254 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10255 (int32_t)mHapticChannelMask)
10256 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10257 (int32_t)mHapticChannelCount)
10258 */
10259 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
10260 formatToString(mHALFormat).c_str())
10261 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10262 (int32_t)mFrameCount) // sic - added HAL
10263 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010264}
10265
Andy Hung71742ab2023-07-07 13:47:37 -070010266bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010267{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010268 checkSilentMode_l();
10269
10270 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10271
10272 while (!exitPending())
10273 {
Andy Hungbd72c542023-06-20 18:56:17 -070010274 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010275
Andy Hung13850be2019-03-14 11:33:09 -070010276 { // under Thread lock
10277 Mutex::Autolock _l(mLock);
10278
Eric Laurent6acd1d42017-01-04 14:23:29 -080010279 if (mSignalPending) {
10280 // A signal was raised while we were unlocked
10281 mSignalPending = false;
10282 } else {
10283 if (mConfigEvents.isEmpty()) {
10284 // we're about to wait, flush the binder command buffer
10285 IPCThreadState::self()->flushCommands();
10286
10287 if (exitPending()) {
10288 break;
10289 }
10290
Eric Laurent6acd1d42017-01-04 14:23:29 -080010291 // wait until we have something to do...
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010292 ALOGV("%s going to sleep", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010293 mWaitWorkCV.wait(mLock);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010294 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010295
10296 checkSilentMode_l();
10297
10298 continue;
10299 }
10300 }
10301
10302 processConfigEvents_l();
10303
10304 processVolume_l();
10305
10306 checkInvalidTracks_l();
10307
10308 mActiveTracks.updatePowerState(this);
10309
Kevin Rocard069c2712018-03-29 19:09:14 -070010310 updateMetadata_l();
10311
Eric Laurent6acd1d42017-01-04 14:23:29 -080010312 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010313 } // release Thread lock
10314
Eric Laurent6acd1d42017-01-04 14:23:29 -080010315 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010316 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010317 }
Andy Hung13850be2019-03-14 11:33:09 -070010318
10319 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010320 unlockEffectChains(effectChains);
10321 // Effect chains will be actually deleted here if they were removed from
10322 // mEffectChains list during mixing or effects processing
10323 }
10324
10325 threadLoop_exit();
10326
10327 if (!mStandby) {
10328 threadLoop_standby();
10329 mStandby = true;
10330 }
10331
Eric Laurent6acd1d42017-01-04 14:23:29 -080010332 ALOGV("Thread %p type %d exiting", this, mType);
10333 return false;
10334}
10335
10336// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -070010337bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010338 status_t& status)
10339{
10340 AudioParameter param = AudioParameter(keyValuePair);
10341 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010342 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010343 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010344 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010345 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010346 if (sendToHal) {
10347 status = mHalStream->setParameters(keyValuePair);
10348 } else {
10349 status = NO_ERROR;
10350 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010351
10352 return false;
10353}
10354
Andy Hung71742ab2023-07-07 13:47:37 -070010355String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010356{
10357 Mutex::Autolock _l(mLock);
10358 String8 out_s8;
10359 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10360 return out_s8;
10361 }
Andy Hung71ba4b32022-10-06 12:09:49 -070010362 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010363}
10364
Andy Hung71742ab2023-07-07 13:47:37 -070010365void MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010366 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010367 sp<AudioIoDescriptor> desc;
10368 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010369 switch (event) {
10370 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010371 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010372 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010373 isInput = true;
10374 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010375 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010376 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010377 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010378 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10379 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010380 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010381 case AUDIO_INPUT_CLOSED:
10382 case AUDIO_OUTPUT_CLOSED:
10383 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010384 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010385 break;
10386 }
Andy Hung2cbc2722023-07-17 17:05:00 -070010387 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010388}
10389
Andy Hung71742ab2023-07-07 13:47:37 -070010390status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010391 audio_patch_handle_t *handle)
Andy Hung71ba4b32022-10-06 12:09:49 -070010392NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010393{
10394 status_t status = NO_ERROR;
10395
10396 // store new device and send to effects
10397 audio_devices_t type = AUDIO_DEVICE_NONE;
10398 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010399 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10400 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10401 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010402 if (isOutput()) {
10403 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010404 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10405 && !mAudioHwDev->supportsAudioPatches(),
10406 "Enumerated device type(%#x) must not be used "
10407 "as it does not support audio patches",
10408 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010409 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung71ba4b32022-10-06 12:09:49 -070010410 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10411 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010412 }
10413 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010414 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010415 } else {
10416 type = patch->sources[0].ext.device.type;
10417 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010418 numDevices = mPatch.num_sources;
10419 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010420 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010421 }
10422
10423 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010424 if (isOutput()) {
10425 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10426 } else {
10427 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10428 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010429 }
10430
jiabinc52b1ff2019-10-31 17:20:42 -070010431 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010432 // store new source and send to effects
10433 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10434 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10435 for (size_t i = 0; i < mEffectChains.size(); i++) {
10436 mEffectChains[i]->setAudioSource_l(mAudioSource);
10437 }
10438 }
10439 }
10440
10441 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010442 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10443 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010444 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010445 audio_port_config port;
10446 std::optional<audio_source_t> source;
10447 if (isOutput()) {
10448 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010449 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010450 port = patch->sources[0];
10451 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010452 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010453 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010454 *handle = AUDIO_PATCH_HANDLE_NONE;
10455 }
10456
jiabinc52b1ff2019-10-31 17:20:42 -070010457 if (numDevices == 0 || mDeviceId != deviceId) {
10458 if (isOutput()) {
10459 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10460 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010461 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010462 } else {
10463 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10464 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10465 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010466 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010467 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010468 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010469 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -070010470 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010471 }
jiabinc52b1ff2019-10-31 17:20:42 -070010472 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010473 mDeviceId = deviceId;
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 Hung71742ab2023-07-07 13:47:37 -070010481status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010482{
10483 status_t status = NO_ERROR;
10484
jiabinc52b1ff2019-10-31 17:20:42 -070010485 mPatch = audio_patch{};
10486 mOutDeviceTypeAddrs.clear();
10487 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010488
10489 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10490 supportsAudioPatches : false;
10491
10492 if (supportsAudioPatches) {
10493 status = mHalDevice->releaseAudioPatch(handle);
10494 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010495 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010496 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010497 // Force meteadata update after a route change
10498 mActiveTracks.setHasChanged();
10499
Eric Laurent6acd1d42017-01-04 14:23:29 -080010500 return status;
10501}
10502
Andy Hung71742ab2023-07-07 13:47:37 -070010503void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010504{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010505 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010506 if (isOutput()) {
10507 config->role = AUDIO_PORT_ROLE_SOURCE;
10508 config->ext.mix.hw_module = mAudioHwDev->handle();
10509 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10510 } else {
10511 config->role = AUDIO_PORT_ROLE_SINK;
10512 config->ext.mix.hw_module = mAudioHwDev->handle();
10513 config->ext.mix.usecase.source = mAudioSource;
10514 }
10515}
10516
Andy Hung71742ab2023-07-07 13:47:37 -070010517status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010518{
10519 audio_session_t session = chain->sessionId();
10520
10521 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10522 // Attach all tracks with same session ID to this chain.
10523 // indicate all active tracks in the chain
Andy Hung3ff4b552023-06-26 19:20:57 -070010524 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010525 if (session == track->sessionId()) {
10526 chain->incTrackCnt();
10527 chain->incActiveTrackCnt();
10528 }
10529 }
10530
10531 chain->setThread(this);
10532 chain->setInBuffer(nullptr);
10533 chain->setOutBuffer(nullptr);
10534 chain->syncHalEffectsState();
10535
10536 mEffectChains.add(chain);
10537 checkSuspendOnAddEffectChain_l(chain);
10538 return NO_ERROR;
10539}
10540
Andy Hung71742ab2023-07-07 13:47:37 -070010541size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010542{
10543 audio_session_t session = chain->sessionId();
10544
10545 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10546
10547 for (size_t i = 0; i < mEffectChains.size(); i++) {
10548 if (chain == mEffectChains[i]) {
10549 mEffectChains.removeAt(i);
10550 // detach all active tracks from the chain
10551 // detach all tracks with same session ID from this chain
Andy Hung3ff4b552023-06-26 19:20:57 -070010552 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010553 if (session == track->sessionId()) {
10554 chain->decActiveTrackCnt();
10555 chain->decTrackCnt();
10556 }
10557 }
10558 break;
10559 }
10560 }
10561 return mEffectChains.size();
10562}
10563
Andy Hung71742ab2023-07-07 13:47:37 -070010564void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010565{
10566 mHalStream->standby();
10567}
10568
Andy Hung71742ab2023-07-07 13:47:37 -070010569void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010570{
Phil Burk7dce7282017-09-27 13:51:41 -070010571 // Do not call callback->onTearDown() because it is redundant for thread exit
10572 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010573}
10574
Andy Hung71742ab2023-07-07 13:47:37 -070010575status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010576{
10577 return BAD_VALUE;
10578}
10579
Andy Hung71742ab2023-07-07 13:47:37 -070010580bool MmapThread::isValidSyncEvent(
10581 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010582{
10583 return false;
10584}
10585
Andy Hung71742ab2023-07-07 13:47:37 -070010586status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010587 const effect_descriptor_t *desc, audio_session_t sessionId)
10588{
10589 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010590 if (audio_is_global_session(sessionId)) {
10591 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010592 desc->name, mThreadName);
10593 return BAD_VALUE;
10594 }
10595
10596 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10597 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10598 desc->name);
10599 return BAD_VALUE;
10600 }
10601 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010602 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10603 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010604 return BAD_VALUE;
10605 }
10606
10607 // Only allow effects without processing load or latency
10608 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10609 return BAD_VALUE;
10610 }
10611
Andy Hungbd72c542023-06-20 18:56:17 -070010612 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010613 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10614 return BAD_VALUE;
10615 }
10616
Eric Laurent6acd1d42017-01-04 14:23:29 -080010617 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010618}
10619
Andy Hung71742ab2023-07-07 13:47:37 -070010620void MmapThread::checkInvalidTracks_l()
Andy Hung71ba4b32022-10-06 12:09:49 -070010621NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010622{
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010623 sp<MmapStreamCallback> callback;
Andy Hung3ff4b552023-06-26 19:20:57 -070010624 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010625 if (track->isInvalid()) {
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010626 callback = mCallback.promote();
10627 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10628 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
Eric Laurent331679c2018-04-16 17:03:16 -070010629 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010630 }
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010631 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010632 }
10633 }
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010634 if (callback != 0) {
10635 mLock.unlock();
10636 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10637 mLock.lock();
10638 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010639}
10640
Andy Hung71742ab2023-07-07 13:47:37 -070010641void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010642{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010643 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10644 mAttr.content_type, mAttr.usage, mAttr.source);
10645 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010646 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010647 dprintf(fd, " No active clients\n");
10648 }
10649}
10650
Andy Hung71742ab2023-07-07 13:47:37 -070010651void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010652{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010653 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010654 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010655 dprintf(fd, " %zu Tracks\n", numtracks);
10656 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010657 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010658 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010659 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010660 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -070010661 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010662 result.append(prefix);
10663 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010664 }
10665 } else {
10666 dprintf(fd, "\n");
10667 }
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010668 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010669}
10670
Andy Hung71742ab2023-07-07 13:47:37 -070010671/* static */
10672sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung2cbc2722023-07-17 17:05:00 -070010673 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung71742ab2023-07-07 13:47:37 -070010674 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -070010675 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -070010676}
10677
10678MmapPlaybackThread::MmapPlaybackThread(
Andy Hung2cbc2722023-07-17 17:05:00 -070010679 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010680 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -070010681 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010682 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010683 mStreamVolume(1.0),
10684 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010685 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010686{
10687 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10688 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung2cbc2722023-07-17 17:05:00 -070010689 mMasterVolume = afThreadCallback->masterVolume_l();
10690 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010691 if (mAudioHwDev) {
10692 if (mAudioHwDev->canSetMasterVolume()) {
10693 mMasterVolume = 1.0;
10694 }
10695
10696 if (mAudioHwDev->canSetMasterMute()) {
10697 mMasterMute = false;
10698 }
10699 }
10700}
10701
Andy Hung71742ab2023-07-07 13:47:37 -070010702void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010703 audio_stream_type_t streamType,
10704 audio_session_t sessionId,
10705 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010706 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010707 audio_port_handle_t portId)
10708{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010709 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010710 mStreamType = streamType;
10711}
10712
Andy Hung71742ab2023-07-07 13:47:37 -070010713AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010714{
10715 Mutex::Autolock _l(mLock);
10716 AudioStreamOut *output = mOutput;
10717 mOutput = NULL;
10718 return output;
10719}
10720
Andy Hung71742ab2023-07-07 13:47:37 -070010721void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010722{
10723 Mutex::Autolock _l(mLock);
10724 // Don't apply master volume in SW if our HAL can do it for us.
10725 if (mAudioHwDev &&
10726 mAudioHwDev->canSetMasterVolume()) {
10727 mMasterVolume = 1.0;
10728 } else {
10729 mMasterVolume = value;
10730 }
10731}
10732
Andy Hung71742ab2023-07-07 13:47:37 -070010733void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010734{
10735 Mutex::Autolock _l(mLock);
10736 // Don't apply master mute in SW if our HAL can do it for us.
10737 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10738 mMasterMute = false;
10739 } else {
10740 mMasterMute = muted;
10741 }
10742}
10743
Andy Hung71742ab2023-07-07 13:47:37 -070010744void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010745{
10746 Mutex::Autolock _l(mLock);
10747 if (stream == mStreamType) {
10748 mStreamVolume = value;
10749 broadcast_l();
10750 }
10751}
10752
Andy Hung71742ab2023-07-07 13:47:37 -070010753float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010754{
10755 Mutex::Autolock _l(mLock);
10756 if (stream == mStreamType) {
10757 return mStreamVolume;
10758 }
10759 return 0.0f;
10760}
10761
Andy Hung71742ab2023-07-07 13:47:37 -070010762void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010763{
10764 Mutex::Autolock _l(mLock);
10765 if (stream == mStreamType) {
10766 mStreamMute= muted;
10767 broadcast_l();
10768 }
10769}
10770
Andy Hung71742ab2023-07-07 13:47:37 -070010771void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010772{
10773 Mutex::Autolock _l(mLock);
10774 if (streamType == mStreamType) {
Andy Hung3ff4b552023-06-26 19:20:57 -070010775 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010776 track->invalidate();
10777 }
10778 broadcast_l();
10779 }
10780}
10781
Andy Hung71742ab2023-07-07 13:47:37 -070010782void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010783{
10784 Mutex::Autolock _l(mLock);
10785 bool trackMatch = false;
Andy Hung3ff4b552023-06-26 19:20:57 -070010786 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010787 if (portIds.find(track->portId()) != portIds.end()) {
10788 track->invalidate();
10789 trackMatch = true;
10790 portIds.erase(track->portId());
10791 }
10792 if (portIds.empty()) {
10793 break;
10794 }
10795 }
10796 if (trackMatch) {
10797 broadcast_l();
10798 }
10799}
10800
Andy Hung71742ab2023-07-07 13:47:37 -070010801void MmapPlaybackThread::processVolume_l()
Andy Hung71ba4b32022-10-06 12:09:49 -070010802NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080010803{
10804 float volume;
10805
10806 if (mMasterMute || mStreamMute) {
10807 volume = 0;
10808 } else {
10809 volume = mMasterVolume * mStreamVolume;
10810 }
10811
10812 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010813
10814 // Convert volumes from float to 8.24
10815 uint32_t vol = (uint32_t)(volume * (1 << 24));
10816
10817 // Delegate volume control to effect in track effect chain if needed
10818 // only one effect chain can be present on DirectOutputThread, so if
10819 // there is one, the track is connected to it
10820 if (!mEffectChains.isEmpty()) {
10821 mEffectChains[0]->setVolume_l(&vol, &vol);
10822 volume = (float)vol / (1 << 24);
10823 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010824 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010825 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10826 mHalVolFloat = volume; // HW volume control worked, so update value.
10827 mNoCallbackWarningCount = 0;
10828 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010829 sp<MmapStreamCallback> callback = mCallback.promote();
10830 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010831 mHalVolFloat = volume; // SW volume control worked, so update value.
10832 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010833 mLock.unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010834 callback->onVolumeChanged(volume);
Eric Laurent734046e2018-04-16 14:50:52 -070010835 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010836 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010837 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10838 ALOGW("Could not set MMAP stream volume: no volume callback!");
10839 mNoCallbackWarningCount++;
10840 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010841 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010842 }
Andy Hung3ff4b552023-06-26 19:20:57 -070010843 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010844 track->setMetadataHasChanged();
Andy Hung2cbc2722023-07-17 17:05:00 -070010845 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010846 /*muteState=*/{mMasterMute,
10847 mStreamVolume == 0.f,
10848 mStreamMute,
10849 // TODO(b/241533526): adjust logic to include mute from AppOps
10850 false /*muteFromPlaybackRestricted*/,
10851 false /*muteFromClientVolume*/,
10852 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010853 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010854 }
10855}
10856
Andy Hung71742ab2023-07-07 13:47:37 -070010857ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070010858{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010859 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010010860 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010861 }
10862 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung3ff4b552023-06-26 19:20:57 -070010863 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070010864 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010865 playback_track_metadata_v7_t trackMetadata;
10866 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010867 .usage = track->attributes().usage,
10868 .content_type = track->attributes().content_type,
10869 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010870 };
10871 trackMetadata.channel_mask = track->channelMask(),
10872 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10873 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010874 }
10875 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010010876
10877 MetadataUpdate change;
10878 change.playbackMetadataUpdate = metadata.tracks;
10879 return change;
10880};
Kevin Rocard069c2712018-03-29 19:09:14 -070010881
Andy Hung71742ab2023-07-07 13:47:37 -070010882void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010883{
10884 if (!mMasterMute) {
10885 char value[PROPERTY_VALUE_MAX];
10886 if (property_get("ro.audio.silent", value, "0") > 0) {
10887 char *endptr;
10888 unsigned long ul = strtoul(value, &endptr, 0);
10889 if (*endptr == '\0' && ul != 0) {
10890 ALOGD("Silence is golden");
10891 // The setprop command will not allow a property to be changed after
10892 // the first time it is set, so we don't have to worry about un-muting.
10893 setMasterMute_l(true);
10894 }
10895 }
10896 }
10897}
10898
Andy Hung71742ab2023-07-07 13:47:37 -070010899void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010900{
10901 MmapThread::toAudioPortConfig(config);
10902 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10903 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10904 config->flags.output = mOutput->flags;
10905 }
10906}
10907
Andy Hung71742ab2023-07-07 13:47:37 -070010908status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung4989d312023-06-29 21:19:25 -070010909 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070010910{
10911 if (mOutput == nullptr) {
10912 return NO_INIT;
10913 }
10914 struct timespec timestamp;
10915 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10916 if (status == NO_ERROR) {
10917 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10918 }
10919 return status;
10920}
10921
Andy Hung71742ab2023-07-07 13:47:37 -070010922status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010923 // Send to MelProcessor for sound dose measurement.
10924 auto processor = mMelProcessor.load();
10925 if (processor) {
10926 processor->process(buffer, frameCount * mFrameSize);
10927 }
10928
jiabinfc791ee2023-02-15 19:43:40 +000010929 return NO_ERROR;
10930}
10931
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010932// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -070010933void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010934 const sp<audio_utils::MelProcessor>& processor)
10935{
10936 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010937 mMelProcessor.store(processor);
10938 if (processor) {
10939 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010940 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010941
10942 // no need to update output format for MMapPlaybackThread since it is
10943 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010944}
10945
10946// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -070010947void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010948{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010949 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
10950 auto melProcessor = mMelProcessor.load();
10951 if (melProcessor != nullptr) {
10952 melProcessor->pause();
10953 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010954}
10955
Andy Hung71742ab2023-07-07 13:47:37 -070010956void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010957{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010958 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010959
Glenn Kastend3bb6452016-12-05 18:14:37 -080010960 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10961 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010962 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10963}
10964
Andy Hung71742ab2023-07-07 13:47:37 -070010965/* static */
10966sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung2cbc2722023-07-17 17:05:00 -070010967 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung71742ab2023-07-07 13:47:37 -070010968 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -070010969 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -070010970}
10971
10972MmapCaptureThread::MmapCaptureThread(
Andy Hung2cbc2722023-07-17 17:05:00 -070010973 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010974 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -070010975 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010976 mInput(input)
10977{
10978 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10979 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10980}
10981
Andy Hung71742ab2023-07-07 13:47:37 -070010982status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010983{
Phil Burkf054fc32018-12-06 09:45:59 -080010984 {
10985 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080010986 if (mInput != nullptr && mInput->stream != nullptr) {
10987 mInput->stream->setGain(1.0f);
10988 }
10989 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010990 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010991}
10992
Andy Hung71742ab2023-07-07 13:47:37 -070010993AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010994{
10995 Mutex::Autolock _l(mLock);
10996 AudioStreamIn *input = mInput;
10997 mInput = NULL;
10998 return input;
10999}
Kevin Rocard069c2712018-03-29 19:09:14 -070011000
Andy Hung71742ab2023-07-07 13:47:37 -070011001void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011002{
11003 bool changed = false;
11004 bool silenced = false;
11005
11006 sp<MmapStreamCallback> callback = mCallback.promote();
11007 if (callback == 0) {
11008 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11009 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11010 mNoCallbackWarningCount++;
11011 }
11012 }
11013
11014 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11015 // track is silenced and unmute otherwise
11016 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11017 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11018 changed = true;
11019 silenced = mActiveTracks[i]->isSilenced_l();
11020 }
11021 }
11022
11023 if (changed) {
11024 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11025 }
11026}
11027
Andy Hung71742ab2023-07-07 13:47:37 -070011028ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011029{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011030 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011031 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011032 }
11033 StreamInHalInterface::SinkMetadata metadata;
Andy Hung3ff4b552023-06-26 19:20:57 -070011034 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011035 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011036 record_track_metadata_v7_t trackMetadata;
11037 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011038 .source = track->attributes().source,
11039 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011040 };
11041 trackMetadata.channel_mask = track->channelMask(),
11042 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11043 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011044 }
11045 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011046 MetadataUpdate change;
11047 change.recordMetadataUpdate = metadata.tracks;
11048 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011049}
11050
Andy Hung71742ab2023-07-07 13:47:37 -070011051void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011052{
11053 Mutex::Autolock _l(mLock);
11054 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011055 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011056 mActiveTracks[i]->setSilenced_l(silenced);
11057 broadcast_l();
11058 }
11059 }
jiabincfc10a42022-06-15 19:26:01 +000011060 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011061}
11062
Andy Hung71742ab2023-07-07 13:47:37 -070011063void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011064{
11065 MmapThread::toAudioPortConfig(config);
11066 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11067 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11068 config->flags.input = mInput->flags;
11069 }
11070}
11071
Andy Hung71742ab2023-07-07 13:47:37 -070011072status_t MmapCaptureThread::getExternalPosition(
Andy Hung4989d312023-06-29 21:19:25 -070011073 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011074{
11075 if (mInput == nullptr) {
11076 return NO_INIT;
11077 }
11078 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11079}
11080
jiabinc658e452022-10-21 20:52:21 +000011081// ----------------------------------------------------------------------------
11082
Andy Hung71742ab2023-07-07 13:47:37 -070011083/* static */
11084sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung2cbc2722023-07-17 17:05:00 -070011085 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -070011086 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -070011087 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -070011088}
11089
Andy Hung2cbc2722023-07-17 17:05:00 -070011090BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011091 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -070011092 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011093
Andy Hung71742ab2023-07-07 13:47:37 -070011094PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -070011095 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011096 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11097 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011098 float volumeLeft = 1.0f;
11099 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011100 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11101 const int trackId = mActiveTracks[0]->id();
11102 mAudioMixer->setParameter(
11103 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11104 mAudioMixer->setParameter(
11105 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11106 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011107 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011108 mIsBitPerfect = true;
11109 } else {
11110 mIsBitPerfect = false;
11111 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11112 // active.
11113 for (const auto& track : mActiveTracks) {
11114 const int trackId = track->id();
11115 mAudioMixer->setParameter(
11116 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11117 }
11118 }
jiabin76d94692022-12-15 21:51:21 +000011119 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11120 mVolumeLeft = volumeLeft;
11121 mVolumeRight = volumeRight;
11122 setVolumeForOutput_l(volumeLeft, volumeRight);
11123 }
jiabinc658e452022-10-21 20:52:21 +000011124 return result;
11125}
11126
Andy Hung71742ab2023-07-07 13:47:37 -070011127void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011128 MixerThread::threadLoop_mix();
11129 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11130}
11131
Glenn Kasten63238ef2015-03-02 15:50:29 -080011132} // namespace android