blob: c8338b23432e3800dce2b93bf7b3ae7197655cc4 [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
Andy Hung18bef9b2023-07-20 21:31:38 -0700248static constexpr nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
249
250static nsecs_t getStandbyTimeInNanos() {
251 static nsecs_t standbyTimeInNanos = []() {
252 const int ms = property_get_int32("ro.audio.flinger_standbytime_ms",
253 kDefaultStandbyTimeInNsecs / NANOS_PER_MILLISECOND);
254 ALOGI("%s: Using %d ms as standby time", __func__, ms);
255 return milliseconds(ms);
256 }();
257 return standbyTimeInNanos;
258}
259
Eric Laurent81784c32012-11-19 14:55:58 -0800260// ----------------------------------------------------------------------------
261
Andy Hungb68f5eb2019-12-03 16:49:17 -0800262// TODO: move all toString helpers to audio.h
263// under #ifdef __cplusplus #endif
264static std::string patchSinksToString(const struct audio_patch *patch)
265{
266 std::stringstream ss;
267 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700268 if (i > 0) {
269 ss << "|";
270 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800271 ss << "(" << toString(patch->sinks[i].ext.device.type)
272 << ", " << patch->sinks[i].ext.device.address << ")";
273 }
274 return ss.str();
275}
276
277static std::string patchSourcesToString(const struct audio_patch *patch)
278{
279 std::stringstream ss;
280 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700281 if (i > 0) {
282 ss << "|";
283 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800284 ss << "(" << toString(patch->sources[i].ext.device.type)
285 << ", " << patch->sources[i].ext.device.address << ")";
286 }
287 return ss.str();
288}
289
Andy Hung4bd53e72022-11-17 17:21:45 -0800290static std::string toString(audio_latency_mode_t mode) {
291 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganova77d5552022-12-18 02:48:14 +0000292 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
293 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800294}
295
296// Could be made a template, but other toString overloads for std::vector are confused.
297static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
298 std::string s("{ ");
299 for (const auto& e : elements) {
300 s.append(toString(e));
301 s.append(" ");
302 }
303 s.append("}");
304 return s;
305}
306
Glenn Kasten03490092014-05-27 12:30:54 -0700307static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
308
309static void sFastTrackMultiplierInit()
310{
311 char value[PROPERTY_VALUE_MAX];
312 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
313 char *endptr;
314 unsigned long ul = strtoul(value, &endptr, 0);
315 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
316 sFastTrackMultiplier = (int) ul;
317 }
318 }
319}
320
321// ----------------------------------------------------------------------------
322
Eric Laurent81784c32012-11-19 14:55:58 -0800323#ifdef ADD_BATTERY_DATA
324// To collect the amplifier usage
325static void addBatteryData(uint32_t params) {
326 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
327 if (service == NULL) {
328 // it already logged
329 return;
330 }
331
332 service->addBatteryData(params);
333}
334#endif
335
Andy Hung3f0c9022016-01-15 17:49:46 -0800336// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
337struct {
338 // call when you acquire a partial wakelock
339 void acquire(const sp<IBinder> &wakeLockToken) {
340 pthread_mutex_lock(&mLock);
341 if (wakeLockToken.get() == nullptr) {
342 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
343 } else {
344 if (mCount == 0) {
345 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
346 }
347 ++mCount;
348 }
349 pthread_mutex_unlock(&mLock);
350 }
351
352 // call when you release a partial wakelock.
353 void release(const sp<IBinder> &wakeLockToken) {
354 if (wakeLockToken.get() == nullptr) {
355 return;
356 }
357 pthread_mutex_lock(&mLock);
358 if (--mCount < 0) {
359 ALOGE("negative wakelock count");
360 mCount = 0;
361 }
362 pthread_mutex_unlock(&mLock);
363 }
364
365 // retrieves the boottime timebase offset from monotonic.
366 int64_t getBoottimeOffset() {
367 pthread_mutex_lock(&mLock);
368 int64_t boottimeOffset = mBoottimeOffset;
369 pthread_mutex_unlock(&mLock);
370 return boottimeOffset;
371 }
372
373 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
374 // and the selected timebase.
375 // Currently only TIMEBASE_BOOTTIME is allowed.
376 //
377 // This only needs to be called upon acquiring the first partial wakelock
378 // after all other partial wakelocks are released.
379 //
380 // We do an empirical measurement of the offset rather than parsing
381 // /proc/timer_list since the latter is not a formal kernel ABI.
382 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
383 int clockbase;
384 switch (timebase) {
385 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
386 clockbase = SYSTEM_TIME_BOOTTIME;
387 break;
388 default:
389 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
390 break;
391 }
392 // try three times to get the clock offset, choose the one
393 // with the minimum gap in measurements.
394 const int tries = 3;
Andy Hung71ba4b32022-10-06 12:09:49 -0700395 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800396 for (int i = 0; i < tries; ++i) {
397 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
398 const nsecs_t tbase = systemTime(clockbase);
399 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
400 const nsecs_t gap = tmono2 - tmono;
401 if (i == 0 || gap < bestGap) {
402 bestGap = gap;
403 measured = tbase - ((tmono + tmono2) >> 1);
404 }
405 }
406
407 // to avoid micro-adjusting, we don't change the timebase
408 // unless it is significantly different.
409 //
410 // Assumption: It probably takes more than toleranceNs to
411 // suspend and resume the device.
412 static int64_t toleranceNs = 10000; // 10 us
413 if (llabs(*offset - measured) > toleranceNs) {
414 ALOGV("Adjusting timebase offset old: %lld new: %lld",
415 (long long)*offset, (long long)measured);
416 *offset = measured;
417 }
418 }
419
420 pthread_mutex_t mLock;
421 int32_t mCount;
422 int64_t mBoottimeOffset;
423} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800424
425// ----------------------------------------------------------------------------
426// CPU Stats
427// ----------------------------------------------------------------------------
428
429class CpuStats {
430public:
431 CpuStats();
432 void sample(const String8 &title);
433#ifdef DEBUG_CPU_USAGE
434private:
435 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700436 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800437
Andy Hung16698b82018-08-01 10:48:38 -0700438 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800439
440 int mCpuNum; // thread's current CPU number
441 int mCpukHz; // frequency of thread's current CPU in kHz
442#endif
443};
444
445CpuStats::CpuStats()
446#ifdef DEBUG_CPU_USAGE
447 : mCpuNum(-1), mCpukHz(-1)
448#endif
449{
450}
451
Glenn Kasten0f11b512014-01-31 16:18:54 -0800452void CpuStats::sample(const String8 &title
453#ifndef DEBUG_CPU_USAGE
454 __unused
455#endif
456 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800457#ifdef DEBUG_CPU_USAGE
458 // get current thread's delta CPU time in wall clock ns
459 double wcNs;
460 bool valid = mCpuUsage.sampleAndEnable(wcNs);
461
462 // record sample for wall clock statistics
463 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700464 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800465 }
466
467 // get the current CPU number
468 int cpuNum = sched_getcpu();
469
470 // get the current CPU frequency in kHz
471 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
472
473 // check if either CPU number or frequency changed
474 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
475 mCpuNum = cpuNum;
476 mCpukHz = cpukHz;
477 // ignore sample for purposes of cycles
478 valid = false;
479 }
480
481 // if no change in CPU number or frequency, then record sample for cycle statistics
482 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700483 const double cycles = wcNs * cpukHz * 0.000001;
484 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800485 }
486
Eric Tan5b13ff82018-07-27 11:20:17 -0700487 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800488 // mCpuUsage.elapsed() is expensive, so don't call it every loop
489 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700490 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800491 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700492 const double perLoop = elapsed / (double) n;
493 const double perLoop100 = perLoop * 0.01;
494 const double perLoop1k = perLoop * 0.001;
495 const double mean = mWcStats.getMean();
496 const double stddev = mWcStats.getStdDev();
497 const double minimum = mWcStats.getMin();
498 const double maximum = mWcStats.getMax();
499 const double meanCycles = mHzStats.getMean();
500 const double stddevCycles = mHzStats.getStdDev();
501 const double minCycles = mHzStats.getMin();
502 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800503 mCpuUsage.resetElapsed();
504 mWcStats.reset();
505 mHzStats.reset();
506 ALOGD("CPU usage for %s over past %.1f secs\n"
507 " (%u mixer loops at %.1f mean ms per loop):\n"
508 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
509 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
510 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000511 title.c_str(),
Eric Laurent81784c32012-11-19 14:55:58 -0800512 elapsed * .000000001, n, perLoop * .000001,
513 mean * .001,
514 stddev * .001,
515 minimum * .001,
516 maximum * .001,
517 mean / perLoop100,
518 stddev / perLoop100,
519 minimum / perLoop100,
520 maximum / perLoop100,
521 meanCycles / perLoop1k,
522 stddevCycles / perLoop1k,
523 minCycles / perLoop1k,
524 maxCycles / perLoop1k);
525
526 }
527 }
528#endif
529};
530
531// ----------------------------------------------------------------------------
532// ThreadBase
533// ----------------------------------------------------------------------------
534
Glenn Kasten97b7b752014-09-28 13:04:24 -0700535// static
Andy Hung71742ab2023-07-07 13:47:37 -0700536const char* ThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700537{
538 switch (type) {
539 case MIXER:
540 return "MIXER";
541 case DIRECT:
542 return "DIRECT";
543 case DUPLICATING:
544 return "DUPLICATING";
545 case RECORD:
546 return "RECORD";
547 case OFFLOAD:
548 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700549 case MMAP_PLAYBACK:
550 return "MMAP_PLAYBACK";
551 case MMAP_CAPTURE:
552 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200553 case SPATIALIZER:
554 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000555 case BIT_PERFECT:
556 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700557 default:
558 return "unknown";
559 }
560}
561
Andy Hung2cbc2722023-07-17 17:05:00 -0700562ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700563 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800564 : Thread(false /*canCallJava*/),
565 mType(type),
Andy Hung2cbc2722023-07-17 17:05:00 -0700566 mAfThreadCallback(afThreadCallback),
Andy Hungcf10d742020-04-28 15:38:24 -0700567 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
568 isOut),
569 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700570 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800571 // are set by PlaybackThread::readOutputParameters_l() or
572 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700573 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700574 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700575 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800576 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700577 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800578 mSystemReady(systemReady),
579 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800580{
Andy Hungcf10d742020-04-28 15:38:24 -0700581 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700582 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800583}
584
Andy Hung71742ab2023-07-07 13:47:37 -0700585ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800586{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700587 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700588 mConfigEvents.clear();
589
Eric Laurent81784c32012-11-19 14:55:58 -0800590 // do not lock the mutex in destructor
591 releaseWakeLock_l();
592 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800593 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800594 binder->unlinkToDeath(mDeathRecipient);
595 }
Andy Hungd0979812019-02-21 15:51:44 -0800596
597 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800598}
599
Andy Hung71742ab2023-07-07 13:47:37 -0700600status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700601{
602 status_t status = initCheck();
603 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800604 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700605 } else {
606 ALOGE("No working audio driver found.");
607 }
608 return status;
609}
610
Andy Hung71742ab2023-07-07 13:47:37 -0700611void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800612{
613 ALOGV("ThreadBase::exit");
614 // do any cleanup required for exit to succeed
615 preExit();
616 {
617 // This lock prevents the following race in thread (uniprocessor for illustration):
618 // if (!exitPending()) {
619 // // context switch from here to exit()
620 // // exit() calls requestExit(), what exitPending() observes
621 // // exit() calls signal(), which is dropped since no waiters
622 // // context switch back from exit() to here
623 // mWaitWorkCV.wait(...);
624 // // now thread is hung
625 // }
626 AutoMutex lock(mLock);
627 requestExit();
628 mWaitWorkCV.broadcast();
629 }
630 // When Thread::requestExitAndWait is made virtual and this method is renamed to
631 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
632 requestExitAndWait();
633}
634
Andy Hung71742ab2023-07-07 13:47:37 -0700635status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800636{
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000637 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800638 Mutex::Autolock _l(mLock);
639
Eric Laurent10351942014-05-08 18:49:52 -0700640 return sendSetParameterConfigEvent_l(keyValuePairs);
641}
642
643// sendConfigEvent_l() must be called with ThreadBase::mLock held
644// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hung71742ab2023-07-07 13:47:37 -0700645status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung71ba4b32022-10-06 12:09:49 -0700646NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700647{
648 status_t status = NO_ERROR;
649
Eric Laurent72e3f392015-05-20 14:43:50 -0700650 if (event->mRequiresSystemReady && !mSystemReady) {
651 event->mWaitStatus = false;
652 mPendingConfigEvents.add(event);
653 return status;
654 }
Eric Laurent10351942014-05-08 18:49:52 -0700655 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700656 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800657 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700658 mLock.unlock();
659 {
660 Mutex::Autolock _l(event->mLock);
661 while (event->mWaitStatus) {
662 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
663 event->mStatus = TIMED_OUT;
664 event->mWaitStatus = false;
665 }
666 }
667 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800668 }
Eric Laurent10351942014-05-08 18:49:52 -0700669 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800670 return status;
671}
672
Andy Hung71742ab2023-07-07 13:47:37 -0700673void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700674 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800675{
676 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700677 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800678}
679
680// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -0700681void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700682 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800683{
Andy Hungd0979812019-02-21 15:51:44 -0800684 // The audio statistics history is exponentially weighted to forget events
685 // about five or more seconds in the past. In order to have
686 // crisper statistics for mediametrics, we reset the statistics on
687 // an IoConfigEvent, to reflect different properties for a new device.
688 mIoJitterMs.reset();
689 mLatencyMs.reset();
690 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000691 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100692 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800693
Eric Laurent09f1ed22019-04-24 17:45:17 -0700694 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700695 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800696}
697
Andy Hung71742ab2023-07-07 13:47:37 -0700698void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700699{
700 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800701 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700702}
703
Eric Laurent81784c32012-11-19 14:55:58 -0800704// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -0700705void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800706 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800707{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800708 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700709 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800710}
711
Eric Laurent10351942014-05-08 18:49:52 -0700712// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -0700713status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800714{
Andy Hung2ddee192015-12-18 17:34:44 -0800715 sp<ConfigEvent> configEvent;
716 AudioParameter param(keyValuePair);
717 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700718 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800719 setMasterMono_l(value != 0);
720 if (param.size() == 1) {
721 return NO_ERROR; // should be a solo parameter - we don't pass down
722 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700723 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800724 configEvent = new SetParameterConfigEvent(param.toString());
725 } else {
726 configEvent = new SetParameterConfigEvent(keyValuePair);
727 }
Eric Laurent10351942014-05-08 18:49:52 -0700728 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700729}
730
Andy Hung71742ab2023-07-07 13:47:37 -0700731status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700732 const struct audio_patch *patch,
733 audio_patch_handle_t *handle)
734{
735 Mutex::Autolock _l(mLock);
736 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
737 status_t status = sendConfigEvent_l(configEvent);
738 if (status == NO_ERROR) {
739 CreateAudioPatchConfigEventData *data =
740 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
741 *handle = data->mHandle;
742 }
743 return status;
744}
745
Andy Hung71742ab2023-07-07 13:47:37 -0700746status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700747 const audio_patch_handle_t handle)
748{
749 Mutex::Autolock _l(mLock);
750 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
751 return sendConfigEvent_l(configEvent);
752}
753
Andy Hung71742ab2023-07-07 13:47:37 -0700754status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700755 const DeviceDescriptorBaseVector& outDevices)
756{
757 if (type() != RECORD) {
758 // The update out device operation is only for record thread.
759 return INVALID_OPERATION;
760 }
761 Mutex::Autolock _l(mLock);
762 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
763 return sendConfigEvent_l(configEvent);
764}
765
Andy Hung71742ab2023-07-07 13:47:37 -0700766void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200767{
768 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
769 sp<ConfigEvent> configEvent =
770 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
771 sendConfigEvent_l(configEvent);
772}
Eric Laurent1c333e22014-05-20 10:48:17 -0700773
Andy Hung71742ab2023-07-07 13:47:37 -0700774void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200775{
776 Mutex::Autolock _l(mLock);
777 sendCheckOutputStageEffectsEvent_l();
778}
779
Andy Hung71742ab2023-07-07 13:47:37 -0700780void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200781{
782 sp<ConfigEvent> configEvent =
783 (ConfigEvent *)new CheckOutputStageEffectsEvent();
784 sendConfigEvent_l(configEvent);
785}
786
Andy Hung71742ab2023-07-07 13:47:37 -0700787void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent6f9534f2022-05-03 18:15:04 +0200788{
789 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
790 sendConfigEvent_l(configEvent);
791}
792
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700793// post condition: mConfigEvents.isEmpty()
Andy Hung71742ab2023-07-07 13:47:37 -0700794void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700795{
Eric Laurent10351942014-05-08 18:49:52 -0700796 bool configChanged = false;
797
Eric Laurent81784c32012-11-19 14:55:58 -0800798 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700799 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700800 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800801 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700802 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700803 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700804 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
805 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800806 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700807 true /*asynchronous*/);
808 if (err != 0) {
809 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700810 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700811 }
812 } break;
813 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700814 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700815 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700816 } break;
817 case CFG_EVENT_SET_PARAMETER: {
818 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
819 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
820 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700821 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000822 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700823 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700824 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700825 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700826 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700827 CreateAudioPatchConfigEventData *data =
828 (CreateAudioPatchConfigEventData *)event->mData.get();
829 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700830 const DeviceTypeSet newDevices = getDeviceTypes();
Eric Laurent52568142022-10-28 11:23:28 +0200831 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700832 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
833 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
834 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700835 } break;
836 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700837 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700838 ReleaseAudioPatchConfigEventData *data =
839 (ReleaseAudioPatchConfigEventData *)event->mData.get();
840 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700841 const DeviceTypeSet newDevices = getDeviceTypes();
Eric Laurent52568142022-10-28 11:23:28 +0200842 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700843 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
844 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
845 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
846 } break;
847 case CFG_EVENT_UPDATE_OUT_DEVICE: {
848 UpdateOutDevicesConfigEventData *data =
849 (UpdateOutDevicesConfigEventData *)event->mData.get();
850 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700851 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200852 case CFG_EVENT_RESIZE_BUFFER: {
853 ResizeBufferConfigEventData *data =
854 (ResizeBufferConfigEventData *)event->mData.get();
855 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
856 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200857
858 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
859 setCheckOutputStageEffects();
860 } break;
861
Eric Laurent6f9534f2022-05-03 18:15:04 +0200862 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
863 onHalLatencyModesChanged_l();
864 } break;
865
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700866 default:
Eric Laurent10351942014-05-08 18:49:52 -0700867 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700868 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800869 }
Eric Laurent10351942014-05-08 18:49:52 -0700870 {
871 Mutex::Autolock _l(event->mLock);
872 if (event->mWaitStatus) {
873 event->mWaitStatus = false;
874 event->mCond.signal();
875 }
876 }
877 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
878 }
879
880 if (configChanged) {
881 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800882 }
Eric Laurent81784c32012-11-19 14:55:58 -0800883}
884
Marco Nelissenb2208842014-02-07 14:00:50 -0800885String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
886 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700887 const audio_channel_representation_t representation =
888 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700889
890 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800891 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700892 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
893 if (output) {
894 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
895 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
896 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700897 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700898 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
899 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
900 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
901 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
902 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
903 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
904 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
905 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
906 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
907 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
908 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
909 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700910 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
911 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
912 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
913 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
914 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
915 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
916 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700917 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700918 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
919 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700920 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
921 } else {
922 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
923 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
924 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
925 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
926 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
927 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
928 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
929 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
930 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
931 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
932 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
933 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700934 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
935 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
936 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700937 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700938 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
939 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700940 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
941 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
942 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
943 }
944 const int len = s.length();
945 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700946 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700947 s.unlockBuffer(len - 2); // remove trailing ", "
948 }
949 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800950 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700951 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
952 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
953 return s;
954 default:
955 s.appendFormat("unknown mask, representation:%d bits:%#x",
956 representation, audio_channel_mask_get_bits(mask));
957 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800958 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800959}
960
Andy Hung71742ab2023-07-07 13:47:37 -0700961void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung71ba4b32022-10-06 12:09:49 -0700962NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -0800963{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800964 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
965 this, mThreadName, getTid(), type(), threadTypeToString(type()));
966
Andy Hung21ff9672023-07-18 20:54:44 -0700967 const bool locked = afutils::dumpTryLock(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -0800968 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800969 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800970 }
971
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700972 dumpBase_l(fd, args);
973 dumpInternals_l(fd, args);
974 dumpTracks_l(fd, args);
975 dumpEffectChains_l(fd, args);
976
977 if (locked) {
978 mLock.unlock();
979 }
980
981 dprintf(fd, " Local log:\n");
982 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -0700983
984 // --all does the statistics
985 bool dumpAll = false;
986 for (const auto &arg : args) {
987 if (arg == String16("--all")) {
988 dumpAll = true;
989 }
990 }
991 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -0700992 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -0700993 if (!sched.empty()) {
994 (void)write(fd, sched.c_str(), sched.size());
995 }
996 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700997}
998
Andy Hung71742ab2023-07-07 13:47:37 -0700999void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001000{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001001 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001002 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001003 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001004 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001005 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001006 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001007 dprintf(fd, " Channel count: %u\n", mChannelCount);
1008 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00001009 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001010 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001011 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001012 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001013 size_t numConfig = mConfigEvents.size();
1014 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001015 const size_t SIZE = 256;
1016 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001017 for (size_t i = 0; i < numConfig; i++) {
1018 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001019 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001020 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001021 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001022 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001023 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001024 }
Andy Hung293558a2017-03-21 12:19:20 -07001025 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001026 dprintf(fd, " Output devices: %s (%s)\n",
1027 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
1028 dprintf(fd, " Input device: %#x (%s)\n",
1029 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001030 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001031
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001032 // Dump timestamp statistics for the Thread types that support it.
1033 if (mType == RECORD
1034 || mType == MIXER
1035 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001036 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001037 || mType == OFFLOAD
1038 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001039 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -07001040 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001041 }
1042
Andy Hung446f4df2019-02-21 12:26:41 -08001043 if (mLastIoBeginNs > 0) { // MMAP may not set this
1044 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1045 isOutput() ? "write" : "read",
1046 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1047 }
1048
1049 if (mProcessTimeMs.getN() > 0) {
1050 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1051 }
1052
1053 if (mIoJitterMs.getN() > 0) {
1054 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1055 isOutput() ? "write" : "read",
1056 mIoJitterMs.toString().c_str());
1057 }
1058
Andy Hunge6c37112019-02-26 17:38:10 -08001059 if (mLatencyMs.getN() > 0) {
1060 dprintf(fd, " Threadloop %s latency stats: %s\n",
1061 isOutput() ? "write" : "read",
1062 mLatencyMs.toString().c_str());
1063 }
Robert Wu06db0a32021-08-10 19:05:34 +00001064
1065 if (mMonopipePipeDepthStats.getN() > 0) {
1066 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1067 isOutput() ? "write" : "read",
1068 mMonopipePipeDepthStats.toString().c_str());
1069 }
Eric Laurent81784c32012-11-19 14:55:58 -08001070}
1071
Andy Hung71742ab2023-07-07 13:47:37 -07001072void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001073{
1074 const size_t SIZE = 256;
1075 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001076
Marco Nelissenb2208842014-02-07 14:00:50 -08001077 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001078 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001079 write(fd, buffer, strlen(buffer));
1080
Marco Nelissenb2208842014-02-07 14:00:50 -08001081 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hungbd72c542023-06-20 18:56:17 -07001082 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001083 if (chain != 0) {
1084 chain->dump(fd, args);
1085 }
1086 }
1087}
1088
Andy Hung71742ab2023-07-07 13:47:37 -07001089void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001090{
1091 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07001092 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001093}
1094
Andy Hung71742ab2023-07-07 13:47:37 -07001095String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001096{
1097 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001098 case MIXER:
1099 return String16("AudioMix");
1100 case DIRECT:
1101 return String16("AudioDirectOut");
1102 case DUPLICATING:
1103 return String16("AudioDup");
1104 case RECORD:
1105 return String16("AudioIn");
1106 case OFFLOAD:
1107 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001108 case MMAP_PLAYBACK:
1109 return String16("MmapPlayback");
1110 case MMAP_CAPTURE:
1111 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001112 case SPATIALIZER:
1113 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001114 default:
1115 ALOG_ASSERT(false);
1116 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001117 }
1118}
1119
Andy Hung71742ab2023-07-07 13:47:37 -07001120void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001121{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001122 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001123 if (mPowerManager != 0) {
1124 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001125 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001126 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1127 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001128 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001129 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001130 {} /* workSource */,
1131 {} /* historyTag */);
1132 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001133 mWakeLockToken = binder;
1134 }
Chris Ye6597d732020-02-28 22:38:25 -08001135 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001136 }
Wei Jia3f273d12015-11-24 09:06:49 -08001137
Andy Hung3f0c9022016-01-15 17:49:46 -08001138 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001139 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1140 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001141}
1142
Andy Hung71742ab2023-07-07 13:47:37 -07001143void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001144{
1145 Mutex::Autolock _l(mLock);
1146 releaseWakeLock_l();
1147}
1148
Andy Hung71742ab2023-07-07 13:47:37 -07001149void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001150{
Andy Hung3f0c9022016-01-15 17:49:46 -08001151 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001152 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001153 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001154 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001155 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001156 }
1157 mWakeLockToken.clear();
1158 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001159}
1160
Andy Hung71742ab2023-07-07 13:47:37 -07001161void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001162 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001163 // use checkService() to avoid blocking if power service is not up yet
1164 sp<IBinder> binder =
1165 defaultServiceManager()->checkService(String16("power"));
1166 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001167 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001168 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001169 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001170 binder->linkToDeath(mDeathRecipient);
1171 }
1172 }
1173}
1174
Andy Hung71742ab2023-07-07 13:47:37 -07001175void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001176 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001177
1178#if !LOG_NDEBUG
1179 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001180 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001181 s << uid << " ";
1182 }
1183 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1184#endif
1185
Andy Hung438e7572015-12-14 15:51:17 -08001186 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1187 if (mSystemReady) {
1188 ALOGE("no wake lock to update, but system ready!");
1189 } else {
1190 ALOGW("no wake lock to update, system not ready yet");
1191 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001192 return;
1193 }
1194 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001195 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001196 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1197 mWakeLockToken, uidsAsInt);
1198 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001199 }
1200}
1201
Andy Hung71742ab2023-07-07 13:47:37 -07001202void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001203{
1204 Mutex::Autolock _l(mLock);
1205 releaseWakeLock_l();
1206 mPowerManager.clear();
1207}
1208
Andy Hung71742ab2023-07-07 13:47:37 -07001209void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001210 const DeviceDescriptorBaseVector& outDevices __unused)
1211{
1212 ALOGE("%s should only be called in RecordThread", __func__);
1213}
1214
Andy Hung71742ab2023-07-07 13:47:37 -07001215void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001216{
1217 ALOGE("%s should only be called in RecordThread", __func__);
1218}
1219
Andy Hung71742ab2023-07-07 13:47:37 -07001220void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001221{
1222 sp<ThreadBase> thread = mThread.promote();
1223 if (thread != 0) {
1224 thread->clearPowerManager();
1225 }
1226 ALOGW("power manager service died !!!");
1227}
1228
Andy Hung71742ab2023-07-07 13:47:37 -07001229void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001230 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001231{
Andy Hungbd72c542023-06-20 18:56:17 -07001232 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001233 if (chain != 0) {
1234 if (type != NULL) {
1235 chain->setEffectSuspended_l(type, suspend);
1236 } else {
1237 chain->setEffectSuspendedAll_l(suspend);
1238 }
1239 }
1240
1241 updateSuspendedSessions_l(type, suspend, sessionId);
1242}
1243
Andy Hung71742ab2023-07-07 13:47:37 -07001244void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001245{
1246 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1247 if (index < 0) {
1248 return;
1249 }
1250
1251 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1252 mSuspendedSessions.valueAt(index);
1253
1254 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001255 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001256 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hungbd72c542023-06-20 18:56:17 -07001257 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001258 chain->setEffectSuspendedAll_l(true);
1259 } else {
1260 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1261 desc->mType.timeLow);
1262 chain->setEffectSuspended_l(&desc->mType, true);
1263 }
1264 }
1265 }
1266}
1267
Andy Hung71742ab2023-07-07 13:47:37 -07001268void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001269 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001270 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001271{
1272 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1273
1274 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1275
1276 if (suspend) {
1277 if (index >= 0) {
1278 sessionEffects = mSuspendedSessions.valueAt(index);
1279 } else {
1280 mSuspendedSessions.add(sessionId, sessionEffects);
1281 }
1282 } else {
1283 if (index < 0) {
1284 return;
1285 }
1286 sessionEffects = mSuspendedSessions.valueAt(index);
1287 }
1288
1289
Andy Hungbd72c542023-06-20 18:56:17 -07001290 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001291 if (type != NULL) {
1292 key = type->timeLow;
1293 }
1294 index = sessionEffects.indexOfKey(key);
1295
1296 sp<SuspendedSessionDesc> desc;
1297 if (suspend) {
1298 if (index >= 0) {
1299 desc = sessionEffects.valueAt(index);
1300 } else {
1301 desc = new SuspendedSessionDesc();
1302 if (type != NULL) {
1303 desc->mType = *type;
1304 }
1305 sessionEffects.add(key, desc);
1306 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1307 }
1308 desc->mRefCount++;
1309 } else {
1310 if (index < 0) {
1311 return;
1312 }
1313 desc = sessionEffects.valueAt(index);
1314 if (--desc->mRefCount == 0) {
1315 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1316 sessionEffects.removeItemsAt(index);
1317 if (sessionEffects.isEmpty()) {
1318 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1319 sessionId);
1320 mSuspendedSessions.removeItem(sessionId);
1321 }
1322 }
1323 }
1324 if (!sessionEffects.isEmpty()) {
1325 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1326 }
1327}
1328
Andy Hung71742ab2023-07-07 13:47:37 -07001329void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001330 audio_session_t sessionId,
Andy Hung71ba4b32022-10-06 12:09:49 -07001331 bool threadLocked)
1332NO_THREAD_SAFETY_ANALYSIS // manual locking
1333{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001334 if (!threadLocked) {
1335 mLock.lock();
1336 }
Eric Laurent81784c32012-11-19 14:55:58 -08001337
Eric Laurent81784c32012-11-19 14:55:58 -08001338 if (mType != RECORD) {
1339 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1340 // another session. This gives the priority to well behaved effect control panels
1341 // and applications not using global effects.
1342 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1343 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001344 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001345 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1346 }
1347 }
1348
Eric Laurent6b446ce2019-12-13 10:56:31 -08001349 if (!threadLocked) {
1350 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001351 }
1352}
1353
Eric Laurent4c415062016-06-17 16:14:16 -07001354// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07001355status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001356 const effect_descriptor_t *desc, audio_session_t sessionId)
1357{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001358 // No global output effect sessions on record threads
1359 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1360 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001361 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1362 desc->name, mThreadName);
1363 return BAD_VALUE;
1364 }
1365 // only pre processing effects on record thread
1366 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1367 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1368 desc->name, mThreadName);
1369 return BAD_VALUE;
1370 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001371
1372 // always allow effects without processing load or latency
1373 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1374 return NO_ERROR;
1375 }
1376
Eric Laurent4c415062016-06-17 16:14:16 -07001377 audio_input_flags_t flags = mInput->flags;
1378 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1379 if (flags & AUDIO_INPUT_FLAG_RAW) {
1380 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1381 desc->name, mThreadName);
1382 return BAD_VALUE;
1383 }
1384 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1385 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1386 desc->name, mThreadName);
1387 return BAD_VALUE;
1388 }
1389 }
jiabineb3bda02020-06-30 14:07:03 -07001390
Andy Hungbd72c542023-06-20 18:56:17 -07001391 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001392 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1393 return BAD_VALUE;
1394 }
Eric Laurent4c415062016-06-17 16:14:16 -07001395 return NO_ERROR;
1396}
1397
1398// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07001399status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001400 const effect_descriptor_t *desc, audio_session_t sessionId)
1401{
1402 // no preprocessing on playback threads
1403 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001404 ALOGW("%s: pre processing effect %s created on playback"
1405 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001406 return BAD_VALUE;
1407 }
1408
Eric Laurent3e4de772017-07-16 16:55:08 -07001409 // always allow effects without processing load or latency
1410 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1411 return NO_ERROR;
1412 }
1413
Andy Hungbd72c542023-06-20 18:56:17 -07001414 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
jiabineb3bda02020-06-30 14:07:03 -07001415 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1416 __func__);
1417 return BAD_VALUE;
1418 }
1419
Eric Laurentf690c462021-09-17 14:47:03 +02001420 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1421 && mType != SPATIALIZER) {
1422 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1423 __func__, mType);
1424 return BAD_VALUE;
1425 }
1426
Eric Laurent4c415062016-06-17 16:14:16 -07001427 switch (mType) {
1428 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001429 audio_output_flags_t flags = mOutput->flags;
1430 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1431 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1432 // global effects are applied only to non fast tracks if they are SW
1433 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1434 break;
1435 }
1436 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1437 // only post processing on output stage session
1438 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001439 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1440 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001441 return BAD_VALUE;
1442 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001443 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1444 // only post processing on output stage session
1445 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001446 ALOGW("%s: non post processing effect %s not allowed on device session",
1447 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001448 return BAD_VALUE;
1449 }
Eric Laurent4c415062016-06-17 16:14:16 -07001450 } else {
1451 // no restriction on effects applied on non fast tracks
1452 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1453 break;
1454 }
1455 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001456
Eric Laurent4c415062016-06-17 16:14:16 -07001457 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001458 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001459 return BAD_VALUE;
1460 }
1461 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001462 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1463 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001464 return BAD_VALUE;
1465 }
1466 }
1467 } break;
1468 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001469 // nothing actionable on offload threads, if the effect:
1470 // - is offloadable: the effect can be created
1471 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1472 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001473 break;
1474 case DIRECT:
1475 // Reject any effect on Direct output threads for now, since the format of
1476 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001477 ALOGW("%s: effect %s on DIRECT output thread %s",
1478 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001479 return BAD_VALUE;
1480 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001481 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001482 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1483 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001484 return BAD_VALUE;
1485 }
1486 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001487 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1488 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001489 return BAD_VALUE;
1490 }
1491 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001492 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1493 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001494 return BAD_VALUE;
1495 }
1496 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001497 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001498 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1499 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1500 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1501 // are supported and added after the spatializer.
1502 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1503 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1504 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001505 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001506 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1507 // only post processing , downmixer or spatializer effects on output stage session
1508 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1509 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1510 break;
1511 }
1512 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1513 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1514 __func__, desc->name);
1515 return BAD_VALUE;
1516 }
1517 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1518 // only post processing on output stage session
1519 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1520 ALOGW("%s: non post processing effect %s not allowed on device session",
1521 __func__, desc->name);
1522 return BAD_VALUE;
1523 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001524 }
1525 break;
jiabinc658e452022-10-21 20:52:21 +00001526 case BIT_PERFECT:
1527 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1528 // Allow HW accelerated effects of tunnel type
1529 break;
1530 }
1531 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1532 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1533 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1534 // 3) there is any bit-perfect track with the given session id.
1535 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1536 sessionId == AUDIO_SESSION_DEVICE) {
1537 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1538 __func__, desc->name, mThreadName);
1539 return BAD_VALUE;
1540 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1541 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1542 __func__, desc->name, sessionId);
1543 return BAD_VALUE;
1544 }
1545 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001546 default:
1547 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1548 }
1549
1550 return NO_ERROR;
1551}
1552
Eric Laurent81784c32012-11-19 14:55:58 -08001553// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07001554sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hungd65869f2023-06-27 17:05:02 -07001555 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001556 const sp<IEffectClient>& effectClient,
1557 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001558 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001559 effect_descriptor_t *desc,
1560 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001561 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001562 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001563 bool probe,
1564 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001565{
Andy Hungbd72c542023-06-20 18:56:17 -07001566 sp<IAfEffectModule> effect;
1567 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001568 status_t lStatus;
Andy Hungbd72c542023-06-20 18:56:17 -07001569 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001570 bool chainCreated = false;
1571 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001572 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001573
1574 lStatus = initCheck();
1575 if (lStatus != NO_ERROR) {
1576 ALOGW("createEffect_l() Audio driver not initialized.");
1577 goto Exit;
1578 }
1579
Eric Laurent81784c32012-11-19 14:55:58 -08001580 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1581
1582 { // scope for mLock
1583 Mutex::Autolock _l(mLock);
1584
Eric Laurent4c415062016-06-17 16:14:16 -07001585 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001586 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001587 goto Exit;
1588 }
1589
Eric Laurent81784c32012-11-19 14:55:58 -08001590 // check for existing effect chain with the requested audio session
1591 chain = getEffectChain_l(sessionId);
1592 if (chain == 0) {
1593 // create a new chain for this session
1594 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Andy Hungbd72c542023-06-20 18:56:17 -07001595 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001596 addEffectChain_l(chain);
1597 chain->setStrategy(getStrategyForSession_l(sessionId));
1598 chainCreated = true;
1599 } else {
1600 effect = chain->getEffectFromDesc_l(desc);
1601 }
1602
1603 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1604
1605 if (effect == 0) {
Andy Hung2cbc2722023-07-17 17:05:00 -07001606 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001607 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001608 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001609 if (lStatus != NO_ERROR) {
1610 goto Exit;
1611 }
1612 effectCreated = true;
1613
jiabinc52b1ff2019-10-31 17:20:42 -07001614 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001615 effect->setDevices(outDeviceTypeAddrs());
1616 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung2cbc2722023-07-17 17:05:00 -07001617 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001618 effect->setAudioSource(mAudioSource);
1619 }
jiabin1319f5a2021-03-30 22:21:24 +00001620 if (effect->isHapticGenerator()) {
1621 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1622 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001623 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung2cbc2722023-07-17 17:05:00 -07001624 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001625 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001626 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001627 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001628 }
1629 }
Eric Laurent81784c32012-11-19 14:55:58 -08001630 // create effect handle and connect it to effect module
Andy Hungbd72c542023-06-20 18:56:17 -07001631 handle = IAfEffectHandle::create(
1632 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001633 lStatus = handle->initCheck();
1634 if (lStatus == OK) {
1635 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001636 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001637 }
Eric Laurent81784c32012-11-19 14:55:58 -08001638 if (enabled != NULL) {
1639 *enabled = (int)effect->isEnabled();
1640 }
1641 }
1642
1643Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001644 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001645 Mutex::Autolock _l(mLock);
1646 if (effectCreated) {
1647 chain->removeEffect_l(effect);
1648 }
Eric Laurent81784c32012-11-19 14:55:58 -08001649 if (chainCreated) {
1650 removeEffectChain_l(chain);
1651 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001652 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001653 }
1654
Glenn Kasten9156ef32013-08-06 15:39:08 -07001655 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001656 return handle;
1657}
1658
Andy Hung71742ab2023-07-07 13:47:37 -07001659void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001660 bool unpinIfLast)
1661{
1662 bool remove = false;
Andy Hungbd72c542023-06-20 18:56:17 -07001663 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001664 {
1665 Mutex::Autolock _l(mLock);
Andy Hungbd72c542023-06-20 18:56:17 -07001666 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001667 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001668 return;
1669 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001670 effect = effectBase->asEffectModule();
1671 if (effect == nullptr) {
1672 return;
1673 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001674 // restore suspended effects if the disconnected handle was enabled and the last one.
1675 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1676 if (remove) {
1677 removeEffect_l(effect, true);
1678 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001679 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001680 }
1681 if (remove) {
Andy Hung2cbc2722023-07-17 17:05:00 -07001682 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001683 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001684 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001685 }
1686 }
1687}
1688
Andy Hung71742ab2023-07-07 13:47:37 -07001689void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001690 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001691 Mutex::Autolock _l(mLock);
1692 broadcast_l();
1693 }
1694 if (!effect->isOffloadable()) {
1695 if (mType == ThreadBase::OFFLOAD) {
1696 PlaybackThread *t = (PlaybackThread *)this;
1697 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1698 }
1699 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung2cbc2722023-07-17 17:05:00 -07001700 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001701 }
1702 }
1703}
1704
Andy Hung71742ab2023-07-07 13:47:37 -07001705void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001706 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001707 Mutex::Autolock _l(mLock);
1708 broadcast_l();
1709 }
1710}
1711
Andy Hung71742ab2023-07-07 13:47:37 -07001712sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung4989d312023-06-29 21:19:25 -07001713 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001714{
1715 Mutex::Autolock _l(mLock);
1716 return getEffect_l(sessionId, effectId);
1717}
1718
Andy Hung71742ab2023-07-07 13:47:37 -07001719sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung4989d312023-06-29 21:19:25 -07001720 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001721{
Andy Hungbd72c542023-06-20 18:56:17 -07001722 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001723 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1724}
1725
Andy Hung71742ab2023-07-07 13:47:37 -07001726std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001727{
Andy Hungbd72c542023-06-20 18:56:17 -07001728 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent6c796322019-04-09 14:13:17 -07001729 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1730}
1731
Eric Laurent81784c32012-11-19 14:55:58 -08001732// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1733// PlaybackThread::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07001734status_t ThreadBase::addEffect_l(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001735{
1736 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001737 audio_session_t sessionId = effect->sessionId();
Andy Hungbd72c542023-06-20 18:56:17 -07001738 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001739 bool chainCreated = false;
1740
Eric Laurent5baf2af2013-09-12 17:37:00 -07001741 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001742 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001743 this, effect->desc().name, effect->desc().flags);
1744
Eric Laurent81784c32012-11-19 14:55:58 -08001745 if (chain == 0) {
1746 // create a new chain for this session
1747 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Andy Hungbd72c542023-06-20 18:56:17 -07001748 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001749 addEffectChain_l(chain);
1750 chain->setStrategy(getStrategyForSession_l(sessionId));
1751 chainCreated = true;
1752 }
1753 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1754
1755 if (chain->getEffectFromId_l(effect->id()) != 0) {
1756 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1757 this, effect->desc().name, chain.get());
1758 return BAD_VALUE;
1759 }
1760
Eric Laurent5baf2af2013-09-12 17:37:00 -07001761 effect->setOffloaded(mType == OFFLOAD, mId);
1762
Eric Laurent81784c32012-11-19 14:55:58 -08001763 status_t status = chain->addEffect_l(effect);
1764 if (status != NO_ERROR) {
1765 if (chainCreated) {
1766 removeEffectChain_l(chain);
1767 }
1768 return status;
1769 }
1770
jiabin8f278ee2019-11-11 12:16:27 -08001771 effect->setDevices(outDeviceTypeAddrs());
1772 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung2cbc2722023-07-17 17:05:00 -07001773 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001774 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001775
Eric Laurent81784c32012-11-19 14:55:58 -08001776 return NO_ERROR;
1777}
1778
Andy Hung71742ab2023-07-07 13:47:37 -07001779void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001780
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001781 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001782 effect_descriptor_t desc = effect->desc();
1783 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1784 detachAuxEffect_l(effect->id());
1785 }
1786
Andy Hungbd72c542023-06-20 18:56:17 -07001787 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001788 if (chain != 0) {
1789 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001790 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001791 removeEffectChain_l(chain);
1792 }
1793 } else {
1794 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1795 }
1796}
1797
Andy Hung71742ab2023-07-07 13:47:37 -07001798void ThreadBase::lockEffectChains_l(
Andy Hungbd72c542023-06-20 18:56:17 -07001799 Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung71ba4b32022-10-06 12:09:49 -07001800NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001801{
1802 effectChains = mEffectChains;
1803 for (size_t i = 0; i < mEffectChains.size(); i++) {
1804 mEffectChains[i]->lock();
1805 }
1806}
1807
Andy Hung71742ab2023-07-07 13:47:37 -07001808void ThreadBase::unlockEffectChains(
Andy Hungbd72c542023-06-20 18:56:17 -07001809 const Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung71ba4b32022-10-06 12:09:49 -07001810NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001811{
1812 for (size_t i = 0; i < effectChains.size(); i++) {
1813 effectChains[i]->unlock();
1814 }
1815}
1816
Andy Hung71742ab2023-07-07 13:47:37 -07001817sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001818{
1819 Mutex::Autolock _l(mLock);
1820 return getEffectChain_l(sessionId);
1821}
1822
Andy Hung71742ab2023-07-07 13:47:37 -07001823sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001824 const
Eric Laurent81784c32012-11-19 14:55:58 -08001825{
1826 size_t size = mEffectChains.size();
1827 for (size_t i = 0; i < size; i++) {
1828 if (mEffectChains[i]->sessionId() == sessionId) {
1829 return mEffectChains[i];
1830 }
1831 }
1832 return 0;
1833}
1834
Andy Hung71742ab2023-07-07 13:47:37 -07001835void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001836{
1837 Mutex::Autolock _l(mLock);
1838 size_t size = mEffectChains.size();
1839 for (size_t i = 0; i < size; i++) {
1840 mEffectChains[i]->setMode_l(mode);
1841 }
1842}
1843
Andy Hung71742ab2023-07-07 13:47:37 -07001844void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001845{
1846 config->type = AUDIO_PORT_TYPE_MIX;
1847 config->ext.mix.handle = mId;
1848 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001849 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001850 config->channel_mask = mChannelMask;
1851 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1852 AUDIO_PORT_CONFIG_FORMAT;
1853}
1854
Andy Hung71742ab2023-07-07 13:47:37 -07001855void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001856{
1857 Mutex::Autolock _l(mLock);
1858 if (mSystemReady) {
1859 return;
1860 }
1861 mSystemReady = true;
1862
1863 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1864 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1865 }
1866 mPendingConfigEvents.clear();
1867}
1868
Andy Hungdae27702016-10-31 14:01:16 -07001869template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001870ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001871 ssize_t index = mActiveTracks.indexOf(track);
1872 if (index >= 0) {
1873 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1874 return index;
1875 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001876 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001877 mActiveTracksGeneration++;
1878 mLatestActiveTrack = track;
1879 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001880 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001881 return mActiveTracks.add(track);
1882}
1883
1884template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001885ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001886 ssize_t index = mActiveTracks.remove(track);
1887 if (index < 0) {
1888 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1889 return index;
1890 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001891 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001892 mActiveTracksGeneration++;
1893 --mBatteryCounter[track->uid()].second;
1894 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001895 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001896#ifdef TEE_SINK
1897 track->dumpTee(-1 /* fd */, "_REMOVE");
1898#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001899 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001900 return index;
1901}
1902
1903template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001904void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001905 for (const sp<T> &track : mActiveTracks) {
1906 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001907 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001908 }
1909 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001910 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001911 mActiveTracks.clear();
1912 mLatestActiveTrack.clear();
1913 mBatteryCounter.clear();
1914}
1915
1916template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001917void ThreadBase::ActiveTracks<T>::updatePowerState(
Andy Hung71ba4b32022-10-06 12:09:49 -07001918 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001919 // Updates ActiveTracks client uids to the thread wakelock.
1920 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1921 thread->updateWakeLockUids_l(getWakeLockUids());
1922 mLastActiveTracksGeneration = mActiveTracksGeneration;
1923 }
1924
1925 // Updates BatteryNotifier uids
1926 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1927 const uid_t uid = it->first;
1928 ssize_t &previous = it->second.first;
1929 ssize_t &current = it->second.second;
1930 if (current > 0) {
1931 if (previous == 0) {
1932 BatteryNotifier::getInstance().noteStartAudio(uid);
1933 }
1934 previous = current;
1935 ++it;
1936 } else if (current == 0) {
1937 if (previous > 0) {
1938 BatteryNotifier::getInstance().noteStopAudio(uid);
1939 }
1940 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1941 } else /* (current < 0) */ {
1942 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1943 }
1944 }
1945}
Eric Laurent83b88082014-06-20 18:31:16 -07001946
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001947template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001948bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001949 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001950 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001951
1952 for (const sp<T> &track : mActiveTracks) {
1953 // Do not short-circuit as all hasChanged states must be reset
1954 // as all the metadata are going to be sent
1955 hasChanged |= track->readAndClearHasChanged();
1956 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001957 return hasChanged;
1958}
1959
1960template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001961void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001962 const char *funcName, const sp<T> &track) const {
1963 if (mLocalLog != nullptr) {
1964 String8 result;
1965 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00001966 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001967 }
1968}
1969
Andy Hung71742ab2023-07-07 13:47:37 -07001970void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08001971{
1972 // Thread could be blocked waiting for async
1973 // so signal it to handle state changes immediately
1974 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1975 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1976 mSignalPending = true;
1977 mWaitWorkCV.broadcast();
1978}
1979
Andy Hungd0979812019-02-21 15:51:44 -08001980// Call only from threadLoop() or when it is idle.
1981// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hung71742ab2023-07-07 13:47:37 -07001982void ThreadBase::sendStatistics(bool force)
Andy Hungd0979812019-02-21 15:51:44 -08001983{
1984 // Do not log if we have no stats.
1985 // We choose the timestamp verifier because it is the most likely item to be present.
1986 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1987 if (nstats == 0) {
1988 return;
1989 }
1990
1991 // Don't log more frequently than once per 12 hours.
1992 // We use BOOTTIME to include suspend time.
1993 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1994 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1995 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1996 return;
1997 }
1998
1999 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2000 mLastRecordedTimeNs = timeNs;
2001
Ray Essickf27e9872019-12-07 06:28:46 -08002002 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002003
2004#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2005
2006 // thread configuration
2007 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2008 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2009 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2010 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2011 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2012 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2013 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07002014 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
2015 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002016
2017 // thread statistics
2018 if (mIoJitterMs.getN() > 0) {
2019 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2020 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2021 }
2022 if (mProcessTimeMs.getN() > 0) {
2023 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2024 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2025 }
2026 const auto tsjitter = mTimestampVerifier.getJitterMs();
2027 if (tsjitter.getN() > 0) {
2028 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2029 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2030 }
2031 if (mLatencyMs.getN() > 0) {
2032 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2033 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2034 }
Robert Wu06db0a32021-08-10 19:05:34 +00002035 if (mMonopipePipeDepthStats.getN() > 0) {
2036 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2037 mMonopipePipeDepthStats.getMean());
2038 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2039 mMonopipePipeDepthStats.getStdDev());
2040 }
Andy Hungd0979812019-02-21 15:51:44 -08002041
2042 item->selfrecord();
2043}
2044
Andy Hung71742ab2023-07-07 13:47:37 -07002045product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002046{
Andy Hung2cbc2722023-07-17 17:05:00 -07002047 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002048 return PRODUCT_STRATEGY_NONE;
2049 }
2050 return AudioSystem::getStrategyForStream(stream);
2051}
2052
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002053// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002054void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002055 const sp<audio_utils::MelProcessor>& /*processor*/)
2056{
2057 // Do nothing
2058 ALOGW("%s: ThreadBase does not support CSD", __func__);
2059}
2060
2061// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002062void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002063{
2064 // Do nothing
2065 ALOGW("%s: ThreadBase does not support CSD", __func__);
2066}
2067
Eric Laurent81784c32012-11-19 14:55:58 -08002068// ----------------------------------------------------------------------------
2069// Playback
2070// ----------------------------------------------------------------------------
2071
Andy Hung2cbc2722023-07-17 17:05:00 -07002072PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002073 AudioStreamOut* output,
2074 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002075 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002076 bool systemReady,
2077 audio_config_base_t *mixerConfig)
Andy Hung2cbc2722023-07-17 17:05:00 -07002078 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002079 mNormalFrameCount(0), mSinkBuffer(NULL),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002080 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002081 mMixerBuffer(NULL),
2082 mMixerBufferSize(0),
2083 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2084 mMixerBufferValid(false),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002085 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002086 mEffectBuffer(NULL),
2087 mEffectBufferSize(0),
2088 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2089 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002090 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002091 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002092 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002093 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002094 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002095 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002096 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002097 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002098 mMixerStatus(MIXER_IDLE),
2099 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung18bef9b2023-07-20 21:31:38 -07002100 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002101 mBytesRemaining(0),
2102 mCurrentWriteLength(0),
2103 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002104 mWriteAckSequence(0),
2105 mDrainSequence(0),
Andy Hung01b29482023-07-19 16:22:58 -07002106 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002107 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002108 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002109 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002110 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl9e661ad2022-07-27 18:01:07 +02002111 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002112 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002113{
Glenn Kastend7dca052015-03-05 16:05:54 -08002114 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung2cbc2722023-07-17 17:05:00 -07002115 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002116
2117 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2118 // it would be safer to explicitly pass initial masterVolume/masterMute as
2119 // parameter.
2120 //
2121 // If the HAL we are using has support for master volume or master mute,
2122 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2123 // and the mute set to false).
Andy Hung2cbc2722023-07-17 17:05:00 -07002124 mMasterVolume = afThreadCallback->masterVolume_l();
2125 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002126 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002127 if (mOutput->audioHwDev->canSetMasterVolume()) {
2128 mMasterVolume = 1.0;
2129 }
2130
2131 if (mOutput->audioHwDev->canSetMasterMute()) {
2132 mMasterMute = false;
2133 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002134 mIsMsdDevice = strcmp(
2135 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002136 }
2137
Eric Laurentf1f22e72021-07-13 14:04:14 +02002138 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2139 mMixerChannelMask = mixerConfig->channel_mask;
2140 }
2141
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002142 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002143
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002144 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002145 && mMixerChannelMask != mChannelMask) {
2146 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2147 mChannelMask, mMixerChannelMask);
2148 }
2149
Andy Hungc8fddf32018-08-08 18:32:37 -07002150 // TODO: We may also match on address as well as device type for
2151 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002152 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002153 // TODO: This property should be ensure that only contains one single device type.
2154 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2155 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002156 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2157 : AUDIO_DEVICE_NONE));
2158 }
2159
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002160 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2161 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002162 mStreamTypes[stream].volume = 0.0f;
Andy Hung2cbc2722023-07-17 17:05:00 -07002163 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002164 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002165 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002166 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2167 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002168 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2169 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002170}
2171
Andy Hung71742ab2023-07-07 13:47:37 -07002172PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002173{
Andy Hung2cbc2722023-07-17 17:05:00 -07002174 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002175 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002176 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002177 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002178 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002179}
2180
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002181// Thread virtuals
2182
Andy Hung71742ab2023-07-07 13:47:37 -07002183void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002184{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002185 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002186 ALOGE("The stream is not open yet"); // This should not happen.
2187 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002188 // Callbacks take strong or weak pointers as a parameter.
2189 // Since PlaybackThread passes itself as a callback handler, it can only
2190 // be done outside of the constructor. Creating weak and especially strong
2191 // pointers to a refcounted object in its own constructor is strongly
2192 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2193 // Even if a function takes a weak pointer, it is possible that it will
2194 // need to convert it to a strong pointer down the line.
2195 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2196 mOutput->stream->setCallback(this) == OK) {
2197 mUseAsyncWrite = true;
Andy Hung71742ab2023-07-07 13:47:37 -07002198 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002199 }
2200
jiabinf6eb4c32020-02-25 14:06:25 -08002201 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002202 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002203 }
2204 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002205 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002206 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002207}
2208
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002209// ThreadBase virtuals
Andy Hung71742ab2023-07-07 13:47:37 -07002210void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002211{
2212 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002213 status_t result = mOutput->stream->exit();
2214 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002215}
2216
Andy Hung71742ab2023-07-07 13:47:37 -07002217void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002218{
Eric Laurent81784c32012-11-19 14:55:58 -08002219 String8 result;
2220
Marco Nelissenb2208842014-02-07 14:00:50 -08002221 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002222 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2223 const stream_type_t *st = &mStreamTypes[i];
2224 if (i > 0) {
2225 result.appendFormat(", ");
2226 }
2227 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2228 if (st->mute) {
2229 result.append("M");
2230 }
2231 }
2232 result.append("\n");
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002233 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002234 result.clear();
2235
Eric Laurent81784c32012-11-19 14:55:58 -08002236 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2237 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002238 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002239 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002240
2241 size_t numtracks = mTracks.size();
2242 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002243 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002244 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002245 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002246 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002247 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002248 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002249 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002250 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002251 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002252 if (track != 0) {
2253 bool active = mActiveTracks.indexOf(track) >= 0;
2254 if (active) {
2255 numactiveseen++;
2256 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002257 result.append(prefix);
2258 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002259 }
2260 }
2261 } else {
2262 result.append("\n");
2263 }
2264 if (numactiveseen != numactive) {
2265 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002266 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002267 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002268 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002269 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002270 for (size_t i = 0; i < numactive; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002271 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002272 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002273 result.append(prefix);
2274 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002275 }
2276 }
2277 }
2278
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002279 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002280}
2281
Andy Hung71742ab2023-07-07 13:47:37 -07002282void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002283{
Andy Hung04cb8f72020-03-20 13:44:33 -07002284 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002285 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002286 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2287 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002288 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2289 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2290 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2291 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002292 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002293 dprintf(fd, " Total writes: %d\n", mNumWrites);
2294 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2295 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2296 dprintf(fd, " Suspend count: %d\n", mSuspended);
2297 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2298 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2299 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2300 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002301 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002302 AudioStreamOut *output = mOutput;
2303 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002304 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002305 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002306 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2307 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2308 if (mPipeSink.get() != nullptr) {
2309 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2310 }
2311 if (output != nullptr) {
2312 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002313 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002314 }
Eric Laurent81784c32012-11-19 14:55:58 -08002315}
2316
Eric Laurent81784c32012-11-19 14:55:58 -08002317// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002318sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hungd65869f2023-06-27 17:05:02 -07002319 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002320 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002321 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002322 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002323 audio_format_t format,
2324 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002325 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002326 size_t *pNotificationFrameCount,
2327 uint32_t notificationsPerBuffer,
2328 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002329 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002330 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002331 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002332 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002333 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002334 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002335 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002336 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002337 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002338 bool isSpatialized,
2339 bool isBitPerfect)
Eric Laurent81784c32012-11-19 14:55:58 -08002340{
Glenn Kasten74935e42013-12-19 08:56:45 -08002341 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002342 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung3ff4b552023-06-26 19:20:57 -07002343 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002344 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002345 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002346 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002347 uint32_t sampleRate;
2348
2349 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2350 lStatus = BAD_VALUE;
2351 goto Exit;
2352 }
Eric Laurent21da6472017-11-09 16:29:26 -08002353
2354 if (*pSampleRate == 0) {
2355 *pSampleRate = mSampleRate;
2356 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002357 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002358
2359 // special case for FAST flag considered OK if fast mixer is present
2360 if (hasFastMixer()) {
2361 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2362 }
2363
2364 // Check if requested flags are compatible with output stream flags
2365 if ((*flags & outputFlags) != *flags) {
2366 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2367 *flags, outputFlags);
2368 *flags = (audio_output_flags_t)(*flags & outputFlags);
2369 }
Eric Laurent81784c32012-11-19 14:55:58 -08002370
jiabinc658e452022-10-21 20:52:21 +00002371 if (isBitPerfect) {
Andy Hungbd72c542023-06-20 18:56:17 -07002372 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002373 if (chain.get() != nullptr) {
2374 // Bit-perfect is required according to the configuration and preferred mixer
2375 // attributes, but it is not in the output flag from the client's request. Explicitly
2376 // adding bit-perfect flag to check the compatibility
2377 audio_output_flags_t flagsToCheck =
2378 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2379 chain->checkOutputFlagCompatibility(&flagsToCheck);
2380 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2381 ALOGE("%s cannot create track as there is data-processing effect attached to "
2382 "given session id(%d)", __func__, sessionId);
2383 lStatus = BAD_VALUE;
2384 goto Exit;
2385 }
2386 *flags = flagsToCheck;
2387 }
2388 }
2389
Eric Laurent81784c32012-11-19 14:55:58 -08002390 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002391 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002392 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002393 // PCM data
2394 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002395 // TODO: extract as a data library function that checks that a computationally
2396 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002397 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002398 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2399 (channelMask == AUDIO_CHANNEL_OUT_MONO
2400 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002401 // hardware sample rate
2402 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002403 // normal mixer has an associated fast mixer
2404 hasFastMixer() &&
2405 // there are sufficient fast track slots available
2406 (mFastTrackAvailMask != 0)
2407 // FIXME test that MixerThread for this fast track has a capable output HAL
2408 // FIXME add a permission test also?
2409 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002410 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2411 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002412 // read the fast track multiplier property the first time it is needed
2413 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2414 if (ok != 0) {
2415 ALOGE("%s pthread_once failed: %d", __func__, ok);
2416 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002417 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002418 }
Eric Laurent4c415062016-06-17 16:14:16 -07002419
2420 // check compatibility with audio effects.
2421 { // scope for mLock
2422 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002423 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002424 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002425 AUDIO_SESSION_OUTPUT_STAGE,
2426 AUDIO_SESSION_OUTPUT_MIX,
2427 sessionId,
2428 }) {
Andy Hungbd72c542023-06-20 18:56:17 -07002429 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002430 if (chain.get() != nullptr) {
2431 audio_output_flags_t old = *flags;
2432 chain->checkOutputFlagCompatibility(flags);
2433 if (old != *flags) {
2434 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2435 (int)session, (int)old, (int)*flags);
2436 }
Eric Laurent4c415062016-06-17 16:14:16 -07002437 }
2438 }
2439 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002440 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002441 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2442 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002443 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002444 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002445 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002446 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002447 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002448 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002449 audio_is_linear_pcm(format), channelMask, sampleRate,
2450 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002451 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002452 }
2453 }
Eric Laurent21da6472017-11-09 16:29:26 -08002454
2455 if (!audio_has_proportional_frames(format)) {
2456 if (sharedBuffer != 0) {
2457 // Same comment as below about ignoring frameCount parameter for set()
2458 frameCount = sharedBuffer->size();
2459 } else if (frameCount == 0) {
2460 frameCount = mNormalFrameCount;
2461 }
2462 if (notificationFrameCount != frameCount) {
2463 notificationFrameCount = frameCount;
2464 }
2465 } else if (sharedBuffer != 0) {
2466 // FIXME: Ensure client side memory buffers need
2467 // not have additional alignment beyond sample
2468 // (e.g. 16 bit stereo accessed as 32 bit frame).
2469 size_t alignment = audio_bytes_per_sample(format);
2470 if (alignment & 1) {
2471 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2472 alignment = 1;
2473 }
2474 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2475 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2476 if (channelCount > 1) {
2477 // More than 2 channels does not require stronger alignment than stereo
2478 alignment <<= 1;
2479 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002480 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002481 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002482 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002483 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002484 goto Exit;
2485 }
Eric Laurent21da6472017-11-09 16:29:26 -08002486
2487 // When initializing a shared buffer AudioTrack via constructors,
2488 // there's no frameCount parameter.
2489 // But when initializing a shared buffer AudioTrack via set(),
2490 // there _is_ a frameCount parameter. We silently ignore it.
2491 frameCount = sharedBuffer->size() / frameSize;
2492 } else {
2493 size_t minFrameCount = 0;
2494 // For fast tracks we try to respect the application's request for notifications per buffer.
2495 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2496 if (notificationsPerBuffer > 0) {
2497 // Avoid possible arithmetic overflow during multiplication.
2498 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2499 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2500 notificationsPerBuffer, mFrameCount);
2501 } else {
2502 minFrameCount = mFrameCount * notificationsPerBuffer;
2503 }
2504 }
2505 } else {
2506 // For normal PCM streaming tracks, update minimum frame count.
2507 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2508 // cover audio hardware latency.
2509 // This is probably too conservative, but legacy application code may depend on it.
2510 // If you change this calculation, also review the start threshold which is related.
2511 uint32_t latencyMs = latency_l();
2512 if (latencyMs == 0) {
2513 ALOGE("Error when retrieving output stream latency");
2514 lStatus = UNKNOWN_ERROR;
2515 goto Exit;
2516 }
2517
2518 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2519 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2520
Eric Laurent81784c32012-11-19 14:55:58 -08002521 }
Eric Laurent21da6472017-11-09 16:29:26 -08002522 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002523 frameCount = minFrameCount;
2524 }
Eric Laurent81784c32012-11-19 14:55:58 -08002525 }
Eric Laurent21da6472017-11-09 16:29:26 -08002526
2527 // Make sure that application is notified with sufficient margin before underrun.
2528 // The client can divide the AudioTrack buffer into sub-buffers,
2529 // and expresses its desire to server as the notification frame count.
2530 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2531 size_t maxNotificationFrames;
2532 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2533 // notify every HAL buffer, regardless of the size of the track buffer
2534 maxNotificationFrames = mFrameCount;
2535 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002536 // Triple buffer the notification period for a triple buffered mixer period;
2537 // otherwise, double buffering for the notification period is fine.
2538 //
2539 // TODO: This should be moved to AudioTrack to modify the notification period
2540 // on AudioTrack::setBufferSizeInFrames() changes.
2541 const int nBuffering =
2542 (uint64_t{frameCount} * mSampleRate)
2543 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2544
Eric Laurent21da6472017-11-09 16:29:26 -08002545 maxNotificationFrames = frameCount / nBuffering;
2546 // If client requested a fast track but this was denied, then use the smaller maximum.
2547 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2548 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2549 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2550 maxNotificationFrames = maxNotificationFramesFastDenied;
2551 }
2552 }
2553 }
2554 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2555 if (notificationFrameCount == 0) {
2556 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2557 maxNotificationFrames, frameCount);
2558 } else {
2559 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2560 notificationFrameCount, maxNotificationFrames, frameCount);
2561 }
2562 notificationFrameCount = maxNotificationFrames;
2563 }
2564 }
2565
Glenn Kasten74935e42013-12-19 08:56:45 -08002566 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002567 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002568
Glenn Kastenc3df8382014-03-13 15:05:25 -07002569 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002570 case BIT_PERFECT:
2571 if (isBitPerfect) {
2572 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2573 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2574 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2575 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2576 mChannelMask);
2577 lStatus = BAD_VALUE;
2578 goto Exit;
2579 }
2580 }
2581 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002582
2583 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002584 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002585 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002586 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2587 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002588 sampleRate, format, channelMask, mOutput, mFormat);
2589 lStatus = BAD_VALUE;
2590 goto Exit;
2591 }
2592 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002593 break;
2594
2595 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002596 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002597 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2598 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002599 sampleRate, format, channelMask, mOutput, mFormat);
2600 lStatus = BAD_VALUE;
2601 goto Exit;
2602 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002603 break;
2604
2605 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002606 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002607 ALOGE("createTrack_l() Bad parameter: format %#x \""
2608 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002609 format, mOutput, mFormat);
2610 lStatus = BAD_VALUE;
2611 goto Exit;
2612 }
Andy Hungcd044842014-08-07 11:04:34 -07002613 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002614 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2615 lStatus = BAD_VALUE;
2616 goto Exit;
2617 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002618 break;
2619
Eric Laurent81784c32012-11-19 14:55:58 -08002620 }
2621
2622 lStatus = initCheck();
2623 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002624 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002625 goto Exit;
2626 }
2627
2628 { // scope for mLock
2629 Mutex::Autolock _l(mLock);
2630
2631 // all tracks in same audio session must share the same routing strategy otherwise
2632 // conflicts will happen when tracks are moved from one output to another by audio policy
2633 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002634 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002635 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002636 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002637 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002638 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002639 if (sessionId == t->sessionId() && strategy != actual) {
2640 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2641 strategy, actual);
2642 lStatus = BAD_VALUE;
2643 goto Exit;
2644 }
2645 }
2646 }
2647
yucliuc9c49cd2020-07-13 16:25:21 -07002648 // Set DIRECT flag if current thread is DirectOutputThread. This can
2649 // happen when the playback is rerouted to direct output thread by
2650 // dynamic audio policy.
2651 // Do NOT report the flag changes back to client, since the client
2652 // doesn't explicitly request a direct flag.
2653 audio_output_flags_t trackFlags = *flags;
2654 if (mType == DIRECT) {
2655 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2656 }
2657
Andy Hung3ff4b552023-06-26 19:20:57 -07002658 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002659 channelMask, frameCount,
2660 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002661 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung3ff4b552023-06-26 19:20:57 -07002662 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002663 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002664
Glenn Kasten03003332013-08-06 15:40:54 -07002665 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2666 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002667 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002668 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002669 goto Exit;
2670 }
2671 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002672 {
2673 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2674 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002675 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002676 }
2677 }
Eric Laurent81784c32012-11-19 14:55:58 -08002678
Andy Hungbd72c542023-06-20 18:56:17 -07002679 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002680 if (chain != 0) {
2681 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2682 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002683 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002684 chain->incTrackCnt();
2685 }
2686
Eric Laurent05067782016-06-01 18:27:28 -07002687 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002688 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2689 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2690 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002691 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002692 }
2693 }
2694
2695 lStatus = NO_ERROR;
2696
2697Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002698 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002699 return track;
2700}
2701
Andy Hung1bc088a2018-02-09 15:57:31 -08002702template<typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07002703ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002704{
Andy Hungc0691382018-09-12 18:01:57 -07002705 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002706 const ssize_t index = mTracks.remove(track);
2707 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002708 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002709 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002710 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002711 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002712 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002713 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002714 }
2715 return index;
2716}
2717
Andy Hung71742ab2023-07-07 13:47:37 -07002718uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002719{
2720 return latency;
2721}
2722
Andy Hung71742ab2023-07-07 13:47:37 -07002723uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002724{
2725 Mutex::Autolock _l(mLock);
2726 return latency_l();
2727}
Andy Hung71742ab2023-07-07 13:47:37 -07002728uint32_t PlaybackThread::latency_l() const
Eric Laurent81784c32012-11-19 14:55:58 -08002729{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002730 uint32_t latency;
2731 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2732 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002733 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002734 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002735}
2736
Andy Hung71742ab2023-07-07 13:47:37 -07002737void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002738{
2739 Mutex::Autolock _l(mLock);
2740 // Don't apply master volume in SW if our HAL can do it for us.
2741 if (mOutput && mOutput->audioHwDev &&
2742 mOutput->audioHwDev->canSetMasterVolume()) {
2743 mMasterVolume = 1.0;
2744 } else {
2745 mMasterVolume = value;
2746 }
2747}
2748
Andy Hung71742ab2023-07-07 13:47:37 -07002749void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002750{
2751 mMasterBalance.store(balance);
2752}
2753
Andy Hung71742ab2023-07-07 13:47:37 -07002754void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002755{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002756 if (isDuplicating()) {
2757 return;
2758 }
Eric Laurent81784c32012-11-19 14:55:58 -08002759 Mutex::Autolock _l(mLock);
2760 // Don't apply master mute in SW if our HAL can do it for us.
2761 if (mOutput && mOutput->audioHwDev &&
2762 mOutput->audioHwDev->canSetMasterMute()) {
2763 mMasterMute = false;
2764 } else {
2765 mMasterMute = muted;
2766 }
2767}
2768
Andy Hung71742ab2023-07-07 13:47:37 -07002769void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002770{
2771 Mutex::Autolock _l(mLock);
2772 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002773 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002774}
2775
Andy Hung71742ab2023-07-07 13:47:37 -07002776void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002777{
2778 Mutex::Autolock _l(mLock);
2779 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002780 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002781}
2782
Andy Hung71742ab2023-07-07 13:47:37 -07002783float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002784{
2785 Mutex::Autolock _l(mLock);
2786 return mStreamTypes[stream].volume;
2787}
2788
Andy Hung71742ab2023-07-07 13:47:37 -07002789void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002790{
2791 mOutput->stream->setVolume(left, right);
2792}
2793
Eric Laurent81784c32012-11-19 14:55:58 -08002794// addTrack_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002795status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Andy Hung71ba4b32022-10-06 12:09:49 -07002796NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent81784c32012-11-19 14:55:58 -08002797{
2798 status_t status = ALREADY_EXISTS;
2799
Eric Laurent81784c32012-11-19 14:55:58 -08002800 if (mActiveTracks.indexOf(track) < 0) {
2801 // the track is newly added, make sure it fills up all its
2802 // buffers before playing. This is to ensure the client will
2803 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002804 if (track->isExternalTrack()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002805 IAfTrackBase::track_state state = track->state();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002806 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002807 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002808 mLock.lock();
2809 // abort track was stopped/paused while we released the lock
Andy Hung3ff4b552023-06-26 19:20:57 -07002810 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002811 if (status == NO_ERROR) {
2812 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002813 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002814 mLock.lock();
2815 }
2816 return INVALID_OPERATION;
2817 }
2818 // abort if start is rejected by audio policy manager
2819 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002820 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2821 // current playback thread is reopened, which may happen when clients set preferred
2822 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2823 // immediately.
2824 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002825 }
2826#ifdef ADD_BATTERY_DATA
2827 // to track the speaker usage
2828 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2829#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002830 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002831 }
2832
Eric Laurent51716182016-02-29 18:00:56 -08002833 // set retry count for buffer fill
2834 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002835 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002836 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002837 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07002838 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002839 }
Andy Hung3ff4b552023-06-26 19:20:57 -07002840 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002841 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07002842 track->retryCount() = kMaxTrackStartupRetries;
2843 track->fillingStatus() =
2844 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002845 }
2846
Andy Hungbd72c542023-06-20 18:56:17 -07002847 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002848 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2849 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2850 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002851 // Unlock due to VibratorService will lock for this call and will
2852 // call Tracks.mute/unmute which also require thread's lock.
2853 mLock.unlock();
Andy Hung9554ec02023-07-20 21:23:42 -07002854 const os::HapticScale intensity = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002855 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002856 std::optional<media::AudioVibratorInfo> vibratorInfo;
2857 {
2858 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2859 // used to play this track.
Andy Hung2cbc2722023-07-17 17:05:00 -07002860 Mutex::Autolock _l(mAfThreadCallback->mutex());
2861 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002862 }
jiabin57303cc2018-12-18 15:45:57 -08002863 mLock.lock();
Simon Bowden62823412022-10-17 14:52:26 +00002864 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002865 if (vibratorInfo) {
2866 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2867 }
2868
jiabin57303cc2018-12-18 15:45:57 -08002869 // Haptic playback should be enabled by vibrator service.
2870 if (track->getHapticPlaybackEnabled()) {
2871 // Disable haptic playback of all active track to ensure only
2872 // one track playing haptic if current track should play haptic.
2873 for (const auto &t : mActiveTracks) {
2874 t->setHapticPlaybackEnabled(false);
2875 }
jiabin245cdd92018-12-07 17:55:15 -08002876 }
jiabine70bc7f2020-06-30 22:07:55 -07002877
2878 // Set haptic intensity for effect
2879 if (chain != nullptr) {
2880 chain->setHapticIntensity_l(track->id(), intensity);
2881 }
jiabin245cdd92018-12-07 17:55:15 -08002882 }
2883
Andy Hung3ff4b552023-06-26 19:20:57 -07002884 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002885 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002886 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002887 if (chain != 0) {
2888 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2889 track->sessionId());
2890 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002891 }
2892
Andy Hungc2b11cb2020-04-22 09:04:01 -07002893 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002894 status = NO_ERROR;
2895 }
2896
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002897 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002898 return status;
2899}
2900
Andy Hung71742ab2023-07-07 13:47:37 -07002901bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002902{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002903 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002904 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002905 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung3ff4b552023-06-26 19:20:57 -07002906 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002907 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002908 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002909 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002910 if (track->isPausePending()) {
2911 track->pauseAck();
2912 }
Andy Hung3ff4b552023-06-26 19:20:57 -07002913 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002914 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002915
2916 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002917}
2918
Andy Hung71742ab2023-07-07 13:47:37 -07002919void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002920{
2921 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002922
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002923 String8 result;
2924 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002925 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002926
Eric Laurent81784c32012-11-19 14:55:58 -08002927 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002928 {
2929 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2930 mAudioTrackCallbacks.erase(track);
2931 }
Eric Laurent81784c32012-11-19 14:55:58 -08002932 if (track->isFastTrack()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002933 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002934 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002935 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2936 mFastTrackAvailMask |= 1 << index;
2937 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung3ff4b552023-06-26 19:20:57 -07002938 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002939 }
Andy Hungbd72c542023-06-20 18:56:17 -07002940 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002941 if (chain != 0) {
2942 chain->decTrackCnt();
2943 }
2944}
2945
Andy Hung71742ab2023-07-07 13:47:37 -07002946String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08002947{
Eric Laurent81784c32012-11-19 14:55:58 -08002948 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002949 String8 out_s8;
2950 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2951 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002952 }
Andy Hung71ba4b32022-10-06 12:09:49 -07002953 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08002954}
2955
Andy Hung71742ab2023-07-07 13:47:37 -07002956status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002957 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002958 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002959 return NO_INIT;
2960 }
2961 return mOutput->stream->selectPresentation(presentationId, programId);
2962}
2963
Andy Hung71742ab2023-07-07 13:47:37 -07002964void PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002965 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002966 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07002967 sp<AudioIoDescriptor> desc;
2968 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002969 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002970 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002971 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002972 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002973 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
2974 mSampleRate, mFormat, mChannelMask,
2975 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
2976 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08002977 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002978 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002979 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07002980 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002981 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002982 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002983 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08002984 break;
2985 }
Andy Hung2cbc2722023-07-17 17:05:00 -07002986 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002987}
2988
Andy Hung71742ab2023-07-07 13:47:37 -07002989void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002990{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002991 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002992}
2993
Andy Hung71742ab2023-07-07 13:47:37 -07002994void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002995{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002996 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002997}
2998
Andy Hung71742ab2023-07-07 13:47:37 -07002999void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003000{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003001 mCallbackThread->setAsyncError();
3002}
3003
Andy Hung71742ab2023-07-07 13:47:37 -07003004void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08003005 const std::basic_string<uint8_t>& metadataBs)
3006{
Andy Hung71742ab2023-07-07 13:47:37 -07003007 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003008 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hung71742ab2023-07-07 13:47:37 -07003009 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003010 if (playbackThread == nullptr) {
3011 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3012 return;
3013 }
3014
jiabinf6eb4c32020-02-25 14:06:25 -08003015 audio_utils::metadata::Data metadata =
3016 audio_utils::metadata::dataFromByteString(metadataBs);
3017 if (metadata.empty()) {
3018 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3019 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3020 (int)metadataBs.size());
3021 return;
3022 }
3023
3024 audio_utils::metadata::ByteString metaDataStr =
3025 audio_utils::metadata::byteStringFromData(metadata);
3026 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
3027 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07003028 for (const auto& callbackPair : mAudioTrackCallbacks) {
3029 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003030 }
3031 }).detach();
3032}
3033
Andy Hung71742ab2023-07-07 13:47:37 -07003034void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003035{
3036 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003037 // reject out of sequence requests
3038 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3039 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003040 mWaitWorkCV.signal();
3041 }
3042}
3043
Andy Hung71742ab2023-07-07 13:47:37 -07003044void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003045{
3046 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003047 // reject out of sequence requests
3048 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003049 // Register discontinuity when HW drain is completed because that can cause
3050 // the timestamp frame position to reset to 0 for direct and offload threads.
3051 // (Out of sequence requests are ignored, since the discontinuity would be handled
3052 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003053 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003054 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003055 mWaitWorkCV.signal();
3056 }
3057}
3058
Andy Hung71742ab2023-07-07 13:47:37 -07003059void PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003060{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003061 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003062 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3063 mSampleRate = audioConfig.sample_rate;
3064 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003065 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003066 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003067 }
Andy Hung71742ab2023-07-07 13:47:37 -07003068 if (hasMixer() && !AudioFlinger::isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003069 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3070 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003071 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003072
3073 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3074 mMixerChannelMask = mChannelMask;
3075 }
3076
Andy Hunge5412692014-05-16 11:25:07 -07003077 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003078 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003079
Eric Laurentf1f22e72021-07-13 14:04:14 +02003080 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3081
Phil Burkca5e6142015-07-14 09:42:29 -07003082 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003083 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003084 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003085 // Get format from the shim, which will be different than the HAL format
3086 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003087 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003088 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003089 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003090 }
Andy Hung71742ab2023-07-07 13:47:37 -07003091 if (hasMixer() && !AudioFlinger::isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003092 LOG_FATAL("HAL format %#x not supported for mixed output",
3093 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003094 }
Phil Burk062e67a2015-02-11 13:40:50 -08003095 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003096 result = mOutput->stream->getBufferSize(&mBufferSize);
3097 LOG_ALWAYS_FATAL_IF(result != OK,
3098 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003099 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003100 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003101 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003102 mFrameCount);
3103 }
3104
Eric Laurentd1f69b02014-12-15 14:33:13 -08003105 mHwSupportsPause = false;
3106 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003107 bool supportsPause = false, supportsResume = false;
3108 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3109 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003110 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003111 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003112 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003113 } else if (supportsResume) {
3114 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003115 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003116 }
3117 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003118 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3119 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3120 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003121
Andy Hungfbfc3952015-01-15 13:33:51 -08003122 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3123 // For best precision, we use float instead of the associated output
3124 // device format (typically PCM 16 bit).
3125
3126 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3127 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3128 mBufferSize = mFrameSize * mFrameCount;
3129
3130 // TODO: We currently use the associated output device channel mask and sample rate.
3131 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3132 // (if a valid mask) to avoid premature downmix.
3133 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3134 // instead of the output device sample rate to avoid loss of high frequency information.
3135 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3136 }
3137
Andy Hung09a50072014-02-27 14:30:47 -08003138 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003139 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003140 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003141 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3142 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003143 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3144 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003145
Eric Laurent81784c32012-11-19 14:55:58 -08003146 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3147 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3148 maxNormalFrameCount = maxNormalFrameCount & ~15;
3149 if (maxNormalFrameCount < minNormalFrameCount) {
3150 maxNormalFrameCount = minNormalFrameCount;
3151 }
3152 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3153 if (multiplier <= 1.0) {
3154 multiplier = 1.0;
3155 } else if (multiplier <= 2.0) {
3156 if (2 * mFrameCount <= maxNormalFrameCount) {
3157 multiplier = 2.0;
3158 } else {
3159 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3160 }
3161 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003162 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003163 }
3164 }
3165 mNormalFrameCount = multiplier * mFrameCount;
3166 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003167 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003168 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3169 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003170 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003171 mNormalFrameCount);
3172
Andy Hung08fb1742015-05-31 23:22:10 -07003173 // Check if we want to throttle the processing to no more than 2x normal rate
3174 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003175 mThreadThrottleTimeMs = 0;
3176 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003177 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3178
Andy Hung010a1a12014-03-13 13:57:33 -07003179 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3180 // Originally this was int16_t[] array, need to remove legacy implications.
3181 free(mSinkBuffer);
3182 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003183
Andy Hung5b10a202014-03-13 13:59:29 -07003184 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3185 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3186 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003187 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003188
Andy Hung69aed5f2014-02-25 17:24:40 -08003189 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3190 // drives the output.
3191 free(mMixerBuffer);
3192 mMixerBuffer = NULL;
3193 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003194 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003195 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003196 * audio_bytes_per_sample(mMixerBufferFormat);
3197 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3198 }
Andy Hung98ef9782014-03-04 14:46:50 -08003199 free(mEffectBuffer);
3200 mEffectBuffer = NULL;
3201 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003202 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003203 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003204 * audio_bytes_per_sample(mEffectBufferFormat);
3205 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3206 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003207
Eric Laurentb62d0362021-10-26 17:40:18 +02003208 if (mType == SPATIALIZER) {
3209 free(mPostSpatializerBuffer);
3210 mPostSpatializerBuffer = nullptr;
3211 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3212 * audio_bytes_per_sample(mEffectBufferFormat);
3213 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3214 }
3215
Mikhail Naganov55773032020-10-01 15:08:13 -07003216 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3217 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003218 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3219 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003220 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003221
Eric Laurent81784c32012-11-19 14:55:58 -08003222 // force reconfiguration of effect chains and engines to take new buffer size and audio
3223 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003224 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003225 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3226 // matter.
3227 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
Andy Hungbd72c542023-06-20 18:56:17 -07003228 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003229 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung2cbc2722023-07-17 17:05:00 -07003230 mAfThreadCallback->moveEffectChain_l(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003231 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003232 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003233
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003234 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003235 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003236 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3237 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3238 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3239 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3240 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3241 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3242 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3243 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3244 (int32_t)mHapticChannelMask)
3245 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3246 (int32_t)mHapticChannelCount)
3247 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3248 formatToString(mHALFormat).c_str())
3249 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3250 (int32_t)mFrameCount) // sic - added HAL
3251 ;
3252 uint32_t latencyMs;
3253 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3254 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3255 }
3256 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003257}
3258
Andy Hung71742ab2023-07-07 13:47:37 -07003259ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003260{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003261 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003262 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003263 }
3264 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003265 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung3ff4b552023-06-26 19:20:57 -07003266 for (const sp<IAfTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -07003267 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003268 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003269 }
Kevin Rocard12381092018-04-11 09:19:59 -07003270 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003271 MetadataUpdate change;
3272 change.playbackMetadataUpdate = metadata.tracks;
3273 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003274}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003275
Andy Hung71742ab2023-07-07 13:47:37 -07003276void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003277 const StreamOutHalInterface::SourceMetadata& metadata)
3278{
3279 mOutput->stream->updateSourceMetadata(metadata);
3280};
3281
Andy Hung71742ab2023-07-07 13:47:37 -07003282status_t PlaybackThread::getRenderPosition(
Andy Hung4989d312023-06-29 21:19:25 -07003283 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003284{
3285 if (halFrames == NULL || dspFrames == NULL) {
3286 return BAD_VALUE;
3287 }
3288 Mutex::Autolock _l(mLock);
3289 if (initCheck() != NO_ERROR) {
3290 return INVALID_OPERATION;
3291 }
Andy Hung818e7a32016-02-16 18:08:07 -08003292 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003293 *halFrames = framesWritten;
3294
3295 if (isSuspended()) {
3296 // return an estimation of rendered frames when the output is suspended
3297 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003298 *dspFrames = (uint32_t)
3299 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003300 return NO_ERROR;
3301 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003302 status_t status;
3303 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003304 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003305 *dspFrames = (size_t)frames;
3306 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003307 }
3308}
3309
Andy Hung71742ab2023-07-07 13:47:37 -07003310product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003311{
3312 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3313 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3314 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003315 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003316 }
3317 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003318 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003319 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003320 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003321 }
3322 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003323 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003324}
3325
3326
Andy Hung71742ab2023-07-07 13:47:37 -07003327AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003328{
3329 Mutex::Autolock _l(mLock);
3330 return mOutput;
3331}
3332
Andy Hung71742ab2023-07-07 13:47:37 -07003333AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003334{
3335 Mutex::Autolock _l(mLock);
3336 AudioStreamOut *output = mOutput;
3337 mOutput = NULL;
3338 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3339 // must push a NULL and wait for ack
3340 mOutputSink.clear();
3341 mPipeSink.clear();
3342 mNormalSink.clear();
3343 return output;
3344}
3345
3346// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hung71742ab2023-07-07 13:47:37 -07003347sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003348{
3349 if (mOutput == NULL) {
3350 return NULL;
3351 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003352 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003353}
3354
Andy Hung71742ab2023-07-07 13:47:37 -07003355uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003356{
3357 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3358}
3359
Andy Hung71742ab2023-07-07 13:47:37 -07003360status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003361{
3362 if (!isValidSyncEvent(event)) {
3363 return BAD_VALUE;
3364 }
3365
3366 Mutex::Autolock _l(mLock);
3367
3368 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003369 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003370 if (event->triggerSession() == track->sessionId()) {
3371 (void) track->setSyncEvent(event);
3372 return NO_ERROR;
3373 }
3374 }
3375
3376 return NAME_NOT_FOUND;
3377}
3378
Andy Hung71742ab2023-07-07 13:47:37 -07003379bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003380{
3381 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3382}
3383
Andy Hung71742ab2023-07-07 13:47:37 -07003384void PlaybackThread::threadLoop_removeTracks(
Andy Hung3ff4b552023-06-26 19:20:57 -07003385 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003386{
Andy Hungfe726a62018-09-27 15:17:25 -07003387 // Miscellaneous track cleanup when removed from the active list,
3388 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003389#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003390 for (const auto& track : tracksToRemove) {
3391 if (track->isExternalTrack()) {
3392 // to track the speaker usage
3393 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003394 }
3395 }
Andy Hungfe726a62018-09-27 15:17:25 -07003396#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003397}
3398
Andy Hung71742ab2023-07-07 13:47:37 -07003399void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003400{
3401 if (!mMasterMute) {
3402 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003403 if (mOutDeviceTypeAddrs.empty()) {
3404 ALOGD("ro.audio.silent is ignored since no output device is set");
3405 return;
3406 }
jiabinc52b1ff2019-10-31 17:20:42 -07003407 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003408 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3409 return;
3410 }
Eric Laurent81784c32012-11-19 14:55:58 -08003411 if (property_get("ro.audio.silent", value, "0") > 0) {
3412 char *endptr;
3413 unsigned long ul = strtoul(value, &endptr, 0);
3414 if (*endptr == '\0' && ul != 0) {
3415 ALOGD("Silence is golden");
3416 // The setprop command will not allow a property to be changed after
3417 // the first time it is set, so we don't have to worry about un-muting.
3418 setMasterMute_l(true);
3419 }
3420 }
3421 }
3422}
3423
3424// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung71742ab2023-07-07 13:47:37 -07003425ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003426{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003427 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003428 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003429 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003430 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003431
3432 // If an NBAIO sink is present, use it to write the normal mixer's submix
3433 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003434
Andy Hung010a1a12014-03-13 13:57:33 -07003435 const size_t count = mBytesRemaining / mFrameSize;
3436
Simon Wilson2d590962012-11-29 15:18:50 -08003437 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003438 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung01b29482023-07-19 16:22:58 -07003439 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003440 if (screenState != mScreenState) {
3441 mScreenState = screenState;
3442 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3443 if (pipe != NULL) {
3444 pipe->setAvgFrames((mScreenState & 1) ?
3445 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3446 }
3447 }
Andy Hung010a1a12014-03-13 13:57:33 -07003448 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003449 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003450
Eric Laurent81784c32012-11-19 14:55:58 -08003451 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003452 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003453
Andy Hung8946a282018-04-19 20:04:56 -07003454#ifdef TEE_SINK
3455 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3456#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003457 } else {
3458 bytesWritten = framesWritten;
3459 }
3460 // otherwise use the HAL / AudioStreamOut directly
3461 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003462 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003463
Eric Laurentbfb1b832013-01-07 09:53:42 -08003464 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003465 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3466 mWriteAckSequence += 2;
3467 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003468 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003469 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003470 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003471 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003472 // FIXME We should have an implementation of timestamps for direct output threads.
3473 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003474 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003475 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003476
Eric Laurentbfb1b832013-01-07 09:53:42 -08003477 if (mUseAsyncWrite &&
3478 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3479 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003480 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003481 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003482 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003483 }
Eric Laurent81784c32012-11-19 14:55:58 -08003484 }
3485
Eric Laurent81784c32012-11-19 14:55:58 -08003486 mNumWrites++;
3487 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003488 if (mStandby) {
3489 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003490 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003491 mStandby = false;
3492 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003493 return bytesWritten;
3494}
3495
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003496// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07003497void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003498 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003499{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003500 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003501 if (outputSink != nullptr) {
3502 outputSink->startMelComputation(processor);
3503 }
Vlad Popab042ee62022-10-20 18:05:00 +02003504}
3505
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003506// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07003507void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003508{
3509 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003510 if (outputSink != nullptr) {
3511 outputSink->stopMelComputation();
3512 }
Vlad Popab042ee62022-10-20 18:05:00 +02003513}
3514
Andy Hung71742ab2023-07-07 13:47:37 -07003515void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003516{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003517 bool supportsDrain = false;
3518 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003519 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3520 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003521 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3522 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003523 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003524 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003525 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003526 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003527 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003528 }
3529}
3530
Andy Hung71742ab2023-07-07 13:47:37 -07003531void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003532{
Eric Laurent275e8e92014-11-30 15:14:47 -08003533 {
3534 Mutex::Autolock _l(mLock);
3535 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003536 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003537 track->invalidate();
3538 }
Andy Hungdae27702016-10-31 14:01:16 -07003539 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3540 // After we exit there are no more track changes sent to BatteryNotifier
3541 // because that requires an active threadLoop.
3542 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3543 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003544 }
Eric Laurent81784c32012-11-19 14:55:58 -08003545}
3546
3547/*
3548The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003549 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003550 - mActiveSleepTimeUs from activeSleepTimeUs()
3551 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003552 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3553 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003554 - maxPeriod from frame count and sample rate (MIXER only)
3555
3556The parameters that affect these derived values are:
3557 - frame count
3558 - frame size
3559 - sample rate
3560 - device type: A2DP or not
3561 - device latency
3562 - format: PCM or not
3563 - active sleep time
3564 - idle sleep time
3565*/
3566
Andy Hung71742ab2023-07-07 13:47:37 -07003567void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003568{
Andy Hung25c2dac2014-02-27 14:56:00 -08003569 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003570 mActiveSleepTimeUs = activeSleepTimeUs();
3571 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003572
Andy Hung18bef9b2023-07-20 21:31:38 -07003573 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003574
Eric Laurent42537be2016-01-08 17:16:42 -08003575 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3576 // truncating audio when going to standby.
jiabinc52b1ff2019-10-31 17:20:42 -07003577 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003578 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3579 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3580 }
3581 }
Eric Laurent81784c32012-11-19 14:55:58 -08003582}
3583
Andy Hung71742ab2023-07-07 13:47:37 -07003584bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003585{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003586 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003587 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003588 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003589 size_t size = mTracks.size();
3590 for (size_t i = 0; i < size; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003591 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003592 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003593 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003594 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003595 }
3596 }
Eric Laurent13084622016-05-17 10:51:49 -07003597 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003598}
3599
Andy Hung71742ab2023-07-07 13:47:37 -07003600void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003601{
3602 Mutex::Autolock _l(mLock);
3603 invalidateTracks_l(streamType);
3604}
3605
Andy Hung71742ab2023-07-07 13:47:37 -07003606void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003607 Mutex::Autolock _l(mLock);
3608 invalidateTracks_l(portIds);
3609}
3610
Andy Hung71742ab2023-07-07 13:47:37 -07003611bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003612 bool trackMatch = false;
3613 const size_t size = mTracks.size();
3614 for (size_t i = 0; i < size; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003615 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003616 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3617 t->invalidate();
3618 portIds.erase(t->portId());
3619 trackMatch = true;
3620 }
3621 if (portIds.empty()) {
3622 break;
3623 }
3624 }
3625 return trackMatch;
3626}
3627
jiabinf042b9b2021-05-07 23:46:28 +00003628// getTrackById_l must be called with holding thread lock
Andy Hung71742ab2023-07-07 13:47:37 -07003629IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003630 audio_port_handle_t trackPortId) {
3631 for (size_t i = 0; i < mTracks.size(); i++) {
3632 if (mTracks[i]->portId() == trackPortId) {
3633 return mTracks[i].get();
3634 }
3635 }
3636 return nullptr;
3637}
3638
Andy Hung71742ab2023-07-07 13:47:37 -07003639status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003640{
Glenn Kastend848eb42016-03-08 13:42:11 -08003641 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003642 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003643 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003644
Andy Hungd3639922022-04-28 18:00:49 -07003645 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003646 if (!audio_is_global_session(session)) {
3647 // player sessions on a spatializer output will use a dedicated input buffer and
3648 // will either output multi channel to mEffectBuffer if the track is spatilaized
3649 // or stereo to mPostSpatializerBuffer if not spatialized.
3650 uint32_t channelMask;
3651 bool isSessionSpatialized =
3652 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3653 if (isSessionSpatialized) {
3654 channelMask = mMixerChannelMask;
3655 } else {
3656 channelMask = mChannelMask;
3657 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003658 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003659 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung2cbc2722023-07-17 17:05:00 -07003660 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003661 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003662 &halInBuffer);
3663 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003664
Andy Hung2cbc2722023-07-17 17:05:00 -07003665 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003666 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3667 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3668 &halOutBuffer);
3669 if (result != OK) return result;
3670
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003671 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003672
Mikhail Naganov022b9952017-01-04 16:36:51 -08003673 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3674 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003675 } else {
3676 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3677 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3678 // mPostSpatializerBuffer as output buffer
3679 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung2cbc2722023-07-17 17:05:00 -07003680 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003681 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3682 if (result != OK) return result;
Andy Hung2cbc2722023-07-17 17:05:00 -07003683 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003684 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3685 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003686
Eric Laurentb62d0362021-10-26 17:40:18 +02003687 if (session == AUDIO_SESSION_DEVICE) {
3688 halInBuffer = halOutBuffer;
3689 }
3690 }
3691 } else {
Andy Hung2cbc2722023-07-17 17:05:00 -07003692 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003693 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3694 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3695 &halInBuffer);
3696 if (result != OK) return result;
3697 halOutBuffer = halInBuffer;
3698 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3699 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003700 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003701 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003702 // Only one effect chain can be present in direct output thread and it uses
3703 // the sink buffer as input
3704 if (mType != DIRECT) {
3705 size_t numSamples = mNormalFrameCount
3706 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3707 + mHapticChannelCount);
Andy Hung2cbc2722023-07-17 17:05:00 -07003708 const status_t allocateStatus =
3709 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003710 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003711 &halInBuffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07003712 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003713
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003714 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003715 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3716 buffer, session);
3717 }
3718 }
3719 }
3720
3721 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003722 // Attach all tracks with same session ID to this chain.
3723 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003724 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003725 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003726 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3727 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003728 track->setMainBuffer(buffer);
3729 chain->incTrackCnt();
3730 }
3731 }
3732
3733 // indicate all active tracks in the chain
Andy Hung3ff4b552023-06-26 19:20:57 -07003734 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003735 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003736 ALOGV("addEffectChain_l() activating track %p on session %d",
3737 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003738 chain->incActiveTrackCnt();
3739 }
3740 }
3741 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003742
Eric Laurentaaa44472014-09-12 17:41:50 -07003743 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003744 chain->setInBuffer(halInBuffer);
3745 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003746 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3747 // chains list in order to be processed last as it contains output device effects.
3748 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3749 // processing effects specific to an output stream before effects applied to all streams
3750 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003751 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3752 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003753 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003754 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003755 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003756 // Effect chain for other sessions are inserted at beginning of effect
3757 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003758 // sessions is not important.
3759 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003760 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3761 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003762 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003763 size_t size = mEffectChains.size();
3764 size_t i = 0;
3765 for (i = 0; i < size; i++) {
3766 if (mEffectChains[i]->sessionId() < session) {
3767 break;
3768 }
3769 }
3770 mEffectChains.insertAt(chain, i);
3771 checkSuspendOnAddEffectChain_l(chain);
3772
3773 return NO_ERROR;
3774}
3775
Andy Hung71742ab2023-07-07 13:47:37 -07003776size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003777{
Glenn Kastend848eb42016-03-08 13:42:11 -08003778 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003779
3780 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3781
3782 for (size_t i = 0; i < mEffectChains.size(); i++) {
3783 if (chain == mEffectChains[i]) {
3784 mEffectChains.removeAt(i);
3785 // detach all active tracks from the chain
Andy Hung3ff4b552023-06-26 19:20:57 -07003786 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003787 if (session == track->sessionId()) {
3788 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3789 chain.get(), session);
3790 chain->decActiveTrackCnt();
3791 }
3792 }
3793
3794 // detach all tracks with same session ID from this chain
Andy Hung71ba4b32022-10-06 12:09:49 -07003795 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003796 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003797 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003798 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003799 chain->decTrackCnt();
3800 }
3801 }
3802 break;
3803 }
3804 }
3805 return mEffectChains.size();
3806}
3807
Andy Hung71742ab2023-07-07 13:47:37 -07003808status_t PlaybackThread::attachAuxEffect(
Andy Hung3ff4b552023-06-26 19:20:57 -07003809 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003810{
3811 Mutex::Autolock _l(mLock);
3812 return attachAuxEffect_l(track, EffectId);
3813}
3814
Andy Hung71742ab2023-07-07 13:47:37 -07003815status_t PlaybackThread::attachAuxEffect_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07003816 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003817{
3818 status_t status = NO_ERROR;
3819
3820 if (EffectId == 0) {
3821 track->setAuxBuffer(0, NULL);
3822 } else {
3823 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hungbd72c542023-06-20 18:56:17 -07003824 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003825 if (effect != 0) {
3826 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3827 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3828 } else {
3829 status = INVALID_OPERATION;
3830 }
3831 } else {
3832 status = BAD_VALUE;
3833 }
3834 }
3835 return status;
3836}
3837
Andy Hung71742ab2023-07-07 13:47:37 -07003838void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003839{
3840 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003841 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003842 if (track->auxEffectId() == effectId) {
3843 attachAuxEffect_l(track, 0);
3844 }
3845 }
3846}
3847
Andy Hung71742ab2023-07-07 13:47:37 -07003848bool PlaybackThread::threadLoop()
Andy Hung71ba4b32022-10-06 12:09:49 -07003849NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003850{
Andy Hung4bf583b2023-05-30 18:10:23 -07003851 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003852
Andy Hung3ff4b552023-06-26 19:20:57 -07003853 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003854
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003855 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003856 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003857
3858 // MIXER
3859 nsecs_t lastWarning = 0;
3860
3861 // DUPLICATING
3862 // FIXME could this be made local to while loop?
3863 writeFrames = 0;
3864
3865 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003866 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003867
Andy Hungd3639922022-04-28 18:00:49 -07003868 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003869 sleepTimeShift = 0;
3870 }
3871
3872 CpuStats cpuStats;
3873 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3874
3875 acquireWakeLock();
3876
Glenn Kasteneef598c2017-04-03 14:41:13 -07003877 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3878 // thread associated with this PlaybackThread.
3879 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3880 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003881 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3882 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003883 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003884 const char *logString = NULL;
3885
rago1bb90822017-05-02 18:31:48 -07003886 // Estimated time for next buffer to be written to hal. This is used only on
3887 // suspended mode (for now) to help schedule the wait time until next iteration.
3888 nsecs_t timeLoopNextNs = 0;
3889
Eric Laurent664539d2013-09-23 18:24:31 -07003890 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003891
Andy Hung2dbffc22018-08-08 18:50:41 -07003892 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003893
Eric Laurentb3f315a2021-07-13 15:09:05 +02003894 sendCheckOutputStageEffectsEvent();
3895
Andy Hung446f4df2019-02-21 12:26:41 -08003896 // loopCount is used for statistics and diagnostics.
3897 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003898 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003899 // Log merge requests are performed during AudioFlinger binder transactions, but
3900 // that does not cover audio playback. It's requested here for that reason.
Andy Hung2cbc2722023-07-17 17:05:00 -07003901 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003902
Eric Laurent81784c32012-11-19 14:55:58 -08003903 cpuStats.sample(myName);
3904
Andy Hungbd72c542023-06-20 18:56:17 -07003905 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003906 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003907 bool isHapticSessionSpatialized = false;
Andy Hung3ff4b552023-06-26 19:20:57 -07003908 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003909
Andy Hung2dbffc22018-08-08 18:50:41 -07003910 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3911 //
jiabinc52b1ff2019-10-31 17:20:42 -07003912 // Note: we access outDeviceTypes() outside of mLock.
3913 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003914 // Here, we try for the AF lock, but do not block on it as the latency
3915 // is more informational.
Andy Hung2cbc2722023-07-17 17:05:00 -07003916 if (mAfThreadCallback->mutex().tryLock() == NO_ERROR) {
Andy Hungd63e79d2023-07-13 16:52:46 -07003917 std::vector<SoftwarePatch> swPatches;
Andy Hung71ba4b32022-10-06 12:09:49 -07003918 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07003919 status_t status = INVALID_OPERATION;
3920 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung2cbc2722023-07-17 17:05:00 -07003921 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungd63e79d2023-07-13 16:52:46 -07003922 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07003923 && swPatches.size() > 0) {
3924 status = swPatches[0].getLatencyMs_l(&latencyMs);
3925 downstreamPatchHandle = swPatches[0].getPatchHandle();
3926 }
3927 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003928 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003929 lastDownstreamPatchHandle = downstreamPatchHandle;
3930 }
3931 if (status == OK) {
3932 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003933 // latency of 5 seconds).
3934 const double minLatency = 0., maxLatency = 5000.;
3935 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003936 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003937 } else {
3938 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung71ba4b32022-10-06 12:09:49 -07003939 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07003940 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003941 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003942 }
Andy Hung2cbc2722023-07-17 17:05:00 -07003943 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07003944 }
3945 } else {
3946 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3947 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003948 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003949 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3950 }
3951 }
3952
Eric Laurentb3f315a2021-07-13 15:09:05 +02003953 if (mCheckOutputStageEffects.exchange(false)) {
3954 checkOutputStageEffects();
3955 }
3956
Vlad Popa7e81cea2023-01-19 16:34:16 +01003957 MetadataUpdate metadataUpdate;
Eric Laurent81784c32012-11-19 14:55:58 -08003958 { // scope for mLock
3959
3960 Mutex::Autolock _l(mLock);
3961
Eric Laurent021cf962014-05-13 10:18:14 -07003962 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003963 if (mCheckOutputStageEffects.load()) {
3964 continue;
3965 }
Eric Laurent10351942014-05-08 18:49:52 -07003966
Glenn Kasteneef598c2017-04-03 14:41:13 -07003967 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003968 if (logString != NULL) {
3969 mNBLogWriter->logTimestamp();
3970 mNBLogWriter->log(logString);
3971 logString = NULL;
3972 }
3973
Dean Wheatley12473e92021-03-18 23:00:55 +11003974 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003975
Eric Laurent81784c32012-11-19 14:55:58 -08003976 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003977 if (mSignalPending) {
3978 // A signal was raised while we were unlocked
3979 mSignalPending = false;
3980 } else if (waitingAsyncCallback_l()) {
3981 if (exitPending()) {
3982 break;
3983 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003984 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003985 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003986 releaseWakeLock_l();
3987 released = true;
3988 }
Andy Hung10cbff12017-02-21 17:30:14 -08003989
3990 const int64_t waitNs = computeWaitTimeNs_l();
3991 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3992 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3993 if (status == TIMED_OUT) {
3994 mSignalPending = true; // if timeout recheck everything
3995 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003996 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003997 if (released) {
3998 acquireWakeLock_l();
3999 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004000 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4001 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004002
4003 continue;
4004 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004005 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004006 isSuspended()) {
4007 // put audio hardware into standby after short delay
4008 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004009
4010 threadLoop_standby();
4011
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004012 // This is where we go into standby
4013 if (!mStandby) {
4014 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004015 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004016 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004017 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004018 }
Andy Hungd0979812019-02-21 15:51:44 -08004019 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004020 }
4021
Eric Tan39ec8d62018-07-24 09:49:29 -07004022 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004023 // we're about to wait, flush the binder command buffer
4024 IPCThreadState::self()->flushCommands();
4025
4026 clearOutputTracks();
4027
4028 if (exitPending()) {
4029 break;
4030 }
4031
4032 releaseWakeLock_l();
4033 // wait until we have something to do...
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00004034 ALOGV("%s going to sleep", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004035 mWaitWorkCV.wait(mLock);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00004036 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004037 acquireWakeLock_l();
4038
4039 mMixerStatus = MIXER_IDLE;
4040 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4041 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004042 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004043 checkSilentMode_l();
4044
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004045 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4046 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004047 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004048 sleepTimeShift = 0;
4049 }
4050
4051 continue;
4052 }
4053 }
Eric Laurent81784c32012-11-19 14:55:58 -08004054 // mMixerStatusIgnoringFastTracks is also updated internally
4055 mMixerStatus = prepareTracks_l(&tracksToRemove);
4056
Andy Hungdae27702016-10-31 14:01:16 -07004057 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004058
Vlad Popa7e81cea2023-01-19 16:34:16 +01004059 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004060
Eric Laurent81784c32012-11-19 14:55:58 -08004061 // prevent any changes in effect chain list and in each effect chain
4062 // during mixing and effect process as the audio buffers could be deleted
4063 // or modified if an effect is created or deleted
4064 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004065
4066 // Determine which session to pick up haptic data.
4067 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004068 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004069 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004070 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004071 for (const auto& track : mActiveTracks) {
Andy Hungbd72c542023-06-20 18:56:17 -07004072 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004073 if (effectChain != nullptr
4074 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004075 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004076 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004077 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004078 break;
4079 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004080 if (activeHapticSessionId == AUDIO_SESSION_NONE
4081 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004082 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004083 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004084 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004085 }
4086 }
4087 }
4088
Andy Hungc1646382019-04-30 16:12:10 -07004089 // Acquire a local copy of active tracks with lock (release w/o lock).
4090 //
4091 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4092 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4093 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4094 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent6f9534f2022-05-03 18:15:04 +02004095
4096 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004097
Jiabin Huangfb476842022-12-06 03:18:10 +00004098 for (const auto &track : mActiveTracks ) {
4099 track->updateTeePatches();
4100 }
4101
Eric Laurent19952e12023-04-20 10:08:29 +02004102 // signal actual start of output stream when the render position reported by the kernel
4103 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004104 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4105 && (mKernelPositionOnStandby
4106 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004107 mHalStarted = true;
4108 mWaitHalStartCV.broadcast();
4109 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004110 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004111
Eric Laurentbfb1b832013-01-07 09:53:42 -08004112 if (mBytesRemaining == 0) {
4113 mCurrentWriteLength = 0;
4114 if (mMixerStatus == MIXER_TRACKS_READY) {
4115 // threadLoop_mix() sets mCurrentWriteLength
4116 threadLoop_mix();
4117 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4118 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004119 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004120 // must be written to HAL
4121 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004122 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004123 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004124
4125 // Tally underrun frames as we are inserting 0s here.
4126 for (const auto& track : activeTracks) {
Andy Hung3ff4b552023-06-26 19:20:57 -07004127 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004128 && !track->isStopped()
4129 && !track->isPaused()
4130 && !track->isTerminated()) {
4131 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4132 __func__, track->id(), track->getTrackStateAsString(),
4133 mNormalFrameCount);
Andy Hung3ff4b552023-06-26 19:20:57 -07004134 track->audioTrackServerProxy()->tallyUnderrunFrames(
4135 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004136 }
4137 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004138 }
4139 }
Andy Hung98ef9782014-03-04 14:46:50 -08004140 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004141 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004142 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004143 // or mSinkBuffer (if there are no effects and there is no data already copied to
4144 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004145 //
4146 // This is done pre-effects computation; if effects change to
4147 // support higher precision, this needs to move.
4148 //
4149 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004150 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004151 uint32_t mixerChannelCount = mEffectBufferValid ?
4152 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004153 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004154 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4155 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4156
David Li88ee0902022-06-22 10:01:21 +08004157 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4158 // do these processes after effects are applied.
4159 if (!mEffectBufferValid) {
4160 // mono blend occurs for mixer threads only (not direct or offloaded)
4161 // and is handled here if we're going directly to the sink.
4162 if (requireMonoBlend()) {
4163 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4164 mNormalFrameCount, true /*limit*/);
4165 }
Andy Hung2ddee192015-12-18 17:34:44 -08004166
David Li88ee0902022-06-22 10:01:21 +08004167 if (!hasFastMixer()) {
4168 // Balance must take effect after mono conversion.
4169 // We do it here if there is no FastMixer.
4170 // mBalance detects zero balance within the class for speed
4171 // (not needed here).
4172 mBalance.setBalance(mMasterBalance.load());
4173 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4174 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004175 }
4176
Andy Hung98ef9782014-03-04 14:46:50 -08004177 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004178 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004179
4180 // If we're going directly to the sink and there are haptic channels,
4181 // we should adjust channels as the sample data is partially interleaved
4182 // in this case.
4183 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4184 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4185 mChannelCount + mHapticChannelCount,
4186 audio_bytes_per_sample(format),
4187 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4188 }
Andy Hung98ef9782014-03-04 14:46:50 -08004189 }
4190
Eric Laurentbfb1b832013-01-07 09:53:42 -08004191 mBytesRemaining = mCurrentWriteLength;
4192 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004193 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4194 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4195 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4196 mBytesWritten += mBytesRemaining;
4197 mFramesWritten += framesRemaining;
4198 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004199 mBytesRemaining = 0;
4200 }
Eric Laurent81784c32012-11-19 14:55:58 -08004201
Eric Laurentbfb1b832013-01-07 09:53:42 -08004202 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004203 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004204 for (size_t i = 0; i < effectChains.size(); i ++) {
4205 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004206 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004207 if (activeHapticSessionId != AUDIO_SESSION_NONE
4208 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004209 // Haptic data is active in this case, copy it directly from
4210 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004211 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4212 audio_channel_count_from_out_mask(mMixerChannelMask) :
4213 mChannelCount;
4214 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4215 hapticSessionChannelCount = mChannelCount;
4216 }
4217
jiabin47affe52019-04-04 18:02:07 -07004218 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004219 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004220 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004221 memcpy_by_audio_format(
4222 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004223 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004224 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004225 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004226 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004227 }
Eric Laurent81784c32012-11-19 14:55:58 -08004228 }
4229 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004230 // Process effect chains for offloaded thread even if no audio
4231 // was read from audio track: process only updates effect state
4232 // and thus does have to be synchronized with audio writes but may have
4233 // to be called while waiting for async write callback
4234 if (mType == OFFLOAD) {
4235 for (size_t i = 0; i < effectChains.size(); i ++) {
4236 effectChains[i]->process_l();
4237 }
4238 }
Eric Laurent81784c32012-11-19 14:55:58 -08004239
Andy Hung98ef9782014-03-04 14:46:50 -08004240 // Only if the Effects buffer is enabled and there is data in the
4241 // Effects buffer (buffer valid), we need to
4242 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004243 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004244 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004245 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004246 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004247 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004248 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004249 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004250 }
4251
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004252 if (!hasFastMixer()) {
4253 // Balance must take effect after mono conversion.
4254 // We do it here if there is no FastMixer.
4255 // mBalance detects zero balance within the class for speed (not needed here).
4256 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004257 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004258 }
4259
Eric Laurentb62d0362021-10-26 17:40:18 +02004260 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4261 // mPostSpatializerBuffer if the haptics track is spatialized.
4262 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4263 // For other thread types, the haptics channels are already in mEffectBuffer.
4264 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4265 const size_t srcBufferSize = mNormalFrameCount *
4266 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4267 mEffectBufferFormat);
4268 const size_t dstBufferSize = mNormalFrameCount
4269 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4270
4271 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4272 mEffectBufferFormat,
4273 (uint8_t*)mEffectBuffer + srcBufferSize,
4274 mEffectBufferFormat,
4275 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004276 }
Atneya Nair68436cf2022-09-19 17:51:37 -07004277 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4278 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4279 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4280 // Clamp PCM float values more than this distance from 0 to insulate
4281 // a HAL which doesn't handle NaN correctly.
4282 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4283 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4284 static_cast<const float*>(effectBuffer),
4285 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4286 } else {
4287 memcpy_by_audio_format(mSinkBuffer, mFormat,
4288 effectBuffer, mEffectBufferFormat, framesToCopy);
4289 }
jiabin245cdd92018-12-07 17:55:15 -08004290 // The sample data is partially interleaved when haptic channels exist,
4291 // we need to adjust channels here.
4292 if (mHapticChannelCount > 0) {
4293 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4294 mChannelCount + mHapticChannelCount,
4295 audio_bytes_per_sample(mFormat),
4296 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4297 }
Andy Hung98ef9782014-03-04 14:46:50 -08004298 }
4299
Eric Laurent81784c32012-11-19 14:55:58 -08004300 // enable changes in effect chain
4301 unlockEffectChains(effectChains);
4302
Vlad Popafce10862023-02-03 10:37:07 +01004303 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung2cbc2722023-07-17 17:05:00 -07004304 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004305 metadataUpdate.playbackMetadataUpdate);
4306 }
4307
Eric Laurentbfb1b832013-01-07 09:53:42 -08004308 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004309 // mSleepTimeUs == 0 means we must write to audio hardware
4310 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004311 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004312 // writePeriodNs is updated >= 0 when ret > 0.
4313 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004314 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004315 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004316 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004317 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004318 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004319 if (ret < 0) {
4320 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004321 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004322 mBytesWritten += ret;
4323 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004324 const int64_t frames = ret / mFrameSize;
4325 mFramesWritten += frames;
4326
4327 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4328 // process information relating to write time.
4329 if (audio_has_proportional_frames(mFormat)) {
4330 // we are in a continuous mixing cycle
4331 if (mMixerStatus == MIXER_TRACKS_READY &&
4332 loopCount == lastLoopCountWritten + 1) {
4333
4334 const double jitterMs =
4335 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4336 {frames, writePeriodNs},
4337 {0, 0} /* lastTimestamp */, mSampleRate);
4338 const double processMs =
4339 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4340
4341 Mutex::Autolock _l(mLock);
4342 mIoJitterMs.add(jitterMs);
4343 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004344
4345 if (mPipeSink.get() != nullptr) {
4346 // Using the Monopipe availableToWrite, we estimate the current
4347 // buffer size.
4348 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4349 const ssize_t
4350 availableToWrite = mPipeSink->availableToWrite();
4351 const size_t pipeFrames = monoPipe->maxFrames();
4352 const size_t
4353 remainingFrames = pipeFrames - max(availableToWrite, 0);
4354 mMonopipePipeDepthStats.add(remainingFrames);
4355 }
Andy Hung446f4df2019-02-21 12:26:41 -08004356 }
4357
4358 // write blocked detection
4359 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004360 if ((mType == MIXER || mType == SPATIALIZER)
4361 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004362 mNumDelayedWrites++;
4363 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4364 ATRACE_NAME("underrun");
4365 ALOGW("write blocked for %lld msecs, "
4366 "%d delayed writes, thread %d",
4367 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4368 mNumDelayedWrites, mId);
4369 lastWarning = lastIoEndNs;
4370 }
4371 }
4372 }
4373 // update timing info.
4374 mLastIoBeginNs = lastIoBeginNs;
4375 mLastIoEndNs = lastIoEndNs;
4376 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004377 }
4378 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4379 (mMixerStatus == MIXER_DRAIN_ALL)) {
4380 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004381 }
Andy Hungd3639922022-04-28 18:00:49 -07004382 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004383
4384 if (mThreadThrottle
4385 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004386 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004387 // Limit MixerThread data processing to no more than twice the
4388 // expected processing rate.
4389 //
4390 // This helps prevent underruns with NuPlayer and other applications
4391 // which may set up buffers that are close to the minimum size, or use
4392 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4393 //
4394 // The throttle smooths out sudden large data drains from the device,
4395 // e.g. when it comes out of standby, which often causes problems with
4396 // (1) mixer threads without a fast mixer (which has its own warm-up)
4397 // (2) minimum buffer sized tracks (even if the track is full,
4398 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004399 //
4400 // Total time spent in last processing cycle equals time spent in
4401 // 1. threadLoop_write, as well as time spent in
4402 // 2. threadLoop_mix (significant for heavy mixing, especially
4403 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004404
Andy Hung446f4df2019-02-21 12:26:41 -08004405 // it's OK if deltaMs is an overestimate.
4406
4407 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004408
Ivan Lozanoea04d392017-11-07 14:37:07 -08004409 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004410 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004411 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004412
Andy Hung08fb1742015-05-31 23:22:10 -07004413 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004414 // notify of throttle start on verbose log
4415 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4416 "mixer(%p) throttle begin:"
4417 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004418 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004419 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004420 // Throttle must be attributed to the previous mixer loop's write time
4421 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004422 // This also ensures proper timing statistics.
4423 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004424 } else {
4425 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4426 if (diff > 0) {
4427 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004428 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004429 ALOGD_IF(!isSingleDeviceType(
4430 outDeviceTypes(), audio_is_a2dp_out_device) &&
4431 !isSingleDeviceType(
4432 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004433 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004434 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4435 }
Andy Hung08fb1742015-05-31 23:22:10 -07004436 }
4437 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004438 }
Eric Laurent81784c32012-11-19 14:55:58 -08004439
Eric Laurentbfb1b832013-01-07 09:53:42 -08004440 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004441 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004442 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004443 // suspended requires accurate metering of sleep time.
4444 if (isSuspended()) {
4445 // advance by expected sleepTime
4446 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4447 const nsecs_t nowNs = systemTime();
4448
4449 // compute expected next time vs current time.
4450 // (negative deltas are treated as delays).
4451 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4452 if (deltaNs < -kMaxNextBufferDelayNs) {
4453 // Delays longer than the max allowed trigger a reset.
4454 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4455 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4456 timeLoopNextNs = nowNs + deltaNs;
4457 } else if (deltaNs < 0) {
4458 // Delays within the max delay allowed: zero the delta/sleepTime
4459 // to help the system catch up in the next iteration(s)
4460 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4461 deltaNs = 0;
4462 }
4463 // update sleep time (which is >= 0)
4464 mSleepTimeUs = deltaNs / 1000;
4465 }
Eric Laurente93cc032016-05-05 10:15:10 -07004466 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4467 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004468 }
Glenn Kastene7754022014-10-31 12:11:26 -07004469 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004470 }
Eric Laurent81784c32012-11-19 14:55:58 -08004471 }
4472
4473 // Finally let go of removed track(s), without the lock held
4474 // since we can't guarantee the destructors won't acquire that
4475 // same lock. This will also mutate and push a new fast mixer state.
4476 threadLoop_removeTracks(tracksToRemove);
4477 tracksToRemove.clear();
4478
4479 // FIXME I don't understand the need for this here;
4480 // it was in the original code but maybe the
4481 // assignment in saveOutputTracks() makes this unnecessary?
4482 clearOutputTracks();
4483
4484 // Effect chains will be actually deleted here if they were removed from
4485 // mEffectChains list during mixing or effects processing
4486 effectChains.clear();
4487
4488 // FIXME Note that the above .clear() is no longer necessary since effectChains
4489 // is now local to this block, but will keep it for now (at least until merge done).
4490 }
4491
Eric Laurentbfb1b832013-01-07 09:53:42 -08004492 threadLoop_exit();
4493
Eric Laurentcf817a22014-08-04 20:36:31 -07004494 if (!mStandby) {
4495 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004496 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004497 }
4498
4499 releaseWakeLock();
4500
4501 ALOGV("Thread %p type %d exiting", this, mType);
4502 return false;
4503}
4504
Andy Hung71742ab2023-07-07 13:47:37 -07004505void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004506{
Dean Wheatley12473e92021-03-18 23:00:55 +11004507 if (mStandby) {
4508 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4509 return;
4510 } else if (mHwPaused) {
4511 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4512 return;
4513 }
4514
4515 // Gather the framesReleased counters for all active tracks,
4516 // and associate with the sink frames written out. We need
4517 // this to convert the sink timestamp to the track timestamp.
4518 bool kernelLocationUpdate = false;
4519 ExtendedTimestamp timestamp; // use private copy to fetch
4520
4521 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4522 // HAL may be draining some small duration buffered data for fade out.
4523 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4524 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4525 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4526 mSampleRate);
4527
4528 if (isTimestampCorrectionEnabled()) {
4529 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4530 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4531 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4532 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4533 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4534 = correctedTimestamp.mFrames;
4535 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4536 = correctedTimestamp.mTimeNs;
4537 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4538 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4539 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4540
4541 // Note: Downstream latency only added if timestamp correction enabled.
4542 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4543 const int64_t newPosition =
4544 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4545 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4546 // prevent retrograde
4547 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4548 newPosition,
4549 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4550 - mSuspendedFrames));
4551 }
4552 }
4553
4554 // We always fetch the timestamp here because often the downstream
4555 // sink will block while writing.
4556
4557 // We keep track of the last valid kernel position in case we are in underrun
4558 // and the normal mixer period is the same as the fast mixer period, or there
4559 // is some error from the HAL.
4560 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4561 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4562 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4563 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4564 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4565
4566 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4567 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4568 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4569 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4570 }
4571
4572 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4573 kernelLocationUpdate = true;
4574 } else {
4575 ALOGVV("getTimestamp error - no valid kernel position");
4576 }
4577
4578 // copy over kernel info
4579 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4580 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4581 + mSuspendedFrames; // add frames discarded when suspended
4582 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4583 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4584 } else {
4585 mTimestampVerifier.error();
4586 }
4587
4588 // mFramesWritten for non-offloaded tracks are contiguous
4589 // even after standby() is called. This is useful for the track frame
4590 // to sink frame mapping.
4591 bool serverLocationUpdate = false;
4592 if (mFramesWritten != mLastFramesWritten) {
4593 serverLocationUpdate = true;
4594 mLastFramesWritten = mFramesWritten;
4595 }
4596 // Only update timestamps if there is a meaningful change.
4597 // Either the kernel timestamp must be valid or we have written something.
4598 if (kernelLocationUpdate || serverLocationUpdate) {
4599 if (serverLocationUpdate) {
4600 // use the time before we called the HAL write - it is a bit more accurate
4601 // to when the server last read data than the current time here.
4602 //
4603 // If we haven't written anything, mLastIoBeginNs will be -1
4604 // and we use systemTime().
4605 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4606 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4607 ? systemTime() : mLastIoBeginNs;
4608 }
4609
Andy Hung3ff4b552023-06-26 19:20:57 -07004610 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004611 if (!t->isFastTrack()) {
4612 t->updateTrackFrameInfo(
Andy Hung3ff4b552023-06-26 19:20:57 -07004613 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004614 mFramesWritten,
4615 mSampleRate,
4616 mTimestamp);
4617 }
4618 }
4619 }
4620
4621 if (audio_has_proportional_frames(mFormat)) {
4622 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4623 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4624 mLatencyMs.add(latencyMs);
4625 }
4626 }
4627#if 0
4628 // logFormat example
4629 if (z % 100 == 0) {
4630 timespec ts;
4631 clock_gettime(CLOCK_MONOTONIC, &ts);
4632 LOGT("This is an integer %d, this is a float %f, this is my "
4633 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4634 LOGT("A deceptive null-terminated string %\0");
4635 }
4636 ++z;
4637#endif
4638}
4639
Eric Laurentbfb1b832013-01-07 09:53:42 -08004640// removeTracks_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07004641void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hung71ba4b32022-10-06 12:09:49 -07004642NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurentbfb1b832013-01-07 09:53:42 -08004643{
Andy Hungfe726a62018-09-27 15:17:25 -07004644 for (const auto& track : tracksToRemove) {
4645 mActiveTracks.remove(track);
4646 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hungbd72c542023-06-20 18:56:17 -07004647 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004648 if (chain != 0) {
4649 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4650 __func__, track->id(), chain.get(), track->sessionId());
4651 chain->decActiveTrackCnt();
4652 }
4653 // If an external client track, inform APM we're no longer active, and remove if needed.
4654 // We do this under lock so that the state is consistent if the Track is destroyed.
4655 if (track->isExternalTrack()) {
4656 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004657 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004658 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004659 }
4660 }
Andy Hungfe726a62018-09-27 15:17:25 -07004661 if (track->isTerminated()) {
4662 // remove from our tracks vector
4663 removeTrack_l(track);
4664 }
jiabineb3bda02020-06-30 14:07:03 -07004665 if (mHapticChannelCount > 0 &&
4666 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4667 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004668 mLock.unlock();
4669 // Unlock due to VibratorService will lock for this call and will
4670 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung9554ec02023-07-20 21:23:42 -07004671 afutils::onExternalVibrationStop(track->getExternalVibration());
jiabin57303cc2018-12-18 15:45:57 -08004672 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004673
4674 // When the track is stop, set the haptic intensity as MUTE
4675 // for the HapticGenerator effect.
4676 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004677 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004678 }
jiabin245cdd92018-12-07 17:55:15 -08004679 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004680 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004681}
Eric Laurent81784c32012-11-19 14:55:58 -08004682
Andy Hung71742ab2023-07-07 13:47:37 -07004683status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004684{
4685 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004686 ExtendedTimestamp ets;
4687 status_t status = mNormalSink->getTimestamp(ets);
4688 if (status == NO_ERROR) {
4689 status = ets.getBestTimestamp(&timestamp);
4690 }
4691 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004692 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004693 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004694 collectTimestamps_l();
4695 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4696 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004697 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004698 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4699 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4700 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4701 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4702 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004703 }
4704 return INVALID_OPERATION;
4705}
Eric Laurent1c333e22014-05-20 10:48:17 -07004706
Eric Laurenteab90452019-06-24 15:17:46 -07004707// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4708// still applied by the mixer.
4709// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4710// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4711// if more than one track are active
Andy Hung71742ab2023-07-07 13:47:37 -07004712status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004713{
4714 status_t result = NO_ERROR;
4715 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4716 if (*volume != mLeftVolFloat) {
4717 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004718 // HAL can return INVALID_OPERATION if operation is not supported.
4719 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004720 "Error when setting output stream volume: %d", result);
4721 if (result == NO_ERROR) {
4722 mLeftVolFloat = *volume;
4723 }
4724 }
4725 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4726 // remove stream volume contribution from software volume.
4727 if (mLeftVolFloat == *volume) {
4728 *volume = 1.0f;
4729 }
4730 }
4731 return result;
4732}
4733
Andy Hung71742ab2023-07-07 13:47:37 -07004734status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004735 audio_patch_handle_t *handle)
4736{
Andy Hungf60abce2016-08-26 11:37:54 -07004737 status_t status;
4738 if (property_get_bool("af.patch_park", false /* default_value */)) {
4739 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4740 // or if HAL does not properly lock against access.
4741 AutoPark<FastMixer> park(mFastMixer);
4742 status = PlaybackThread::createAudioPatch_l(patch, handle);
4743 } else {
4744 status = PlaybackThread::createAudioPatch_l(patch, handle);
4745 }
Eric Laurentb0463942022-12-20 16:31:10 +01004746
4747 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004748 return status;
4749}
4750
Andy Hung71742ab2023-07-07 13:47:37 -07004751status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004752 audio_patch_handle_t *handle)
4753{
4754 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004755
4756 // store new device and send to effects
4757 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004758 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004759 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004760 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4761 && !mOutput->audioHwDev->supportsAudioPatches(),
4762 "Enumerated device type(%#x) must not be used "
4763 "as it does not support audio patches",
4764 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004765 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung71ba4b32022-10-06 12:09:49 -07004766 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4767 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004768 }
4769
François Gaffie0c280aa2018-07-25 10:02:15 +02004770 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004771#ifdef ADD_BATTERY_DATA
4772 // when changing the audio output device, call addBatteryData to notify
4773 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004774 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004775 uint32_t params = 0;
4776 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004777 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004778 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004779 }
4780
Eric Laurent054d9d32015-04-24 08:48:48 -07004781 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004782 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004783 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4784 }
4785
4786 if (params != 0) {
4787 addBatteryData(params);
4788 }
4789 }
4790#endif
4791
4792 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004793 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004794 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004795
jiabinc52b1ff2019-10-31 17:20:42 -07004796 // mPatch.num_sinks is not set when the thread is created so that
4797 // the first patch creation triggers an ioConfigChanged callback
4798 bool configChanged = (mPatch.num_sinks == 0) ||
4799 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004800 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004801 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004802 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004803
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004804 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004805 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4806 status = hwDevice->createAudioPatch(patch->num_sources,
4807 patch->sources,
4808 patch->num_sinks,
4809 patch->sinks,
4810 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004811 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004812 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004813 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004814 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004815 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004816
4817 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004818 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004819 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004820 // also dispatch to active AudioTracks for MediaMetrics
4821 for (const auto &track : mActiveTracks) {
4822 track->logEndInterval();
4823 track->logBeginInterval(patchSinksAsString);
4824 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004825
Eric Laurente8726fe2015-06-26 09:39:24 -07004826 if (configChanged) {
4827 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4828 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004829 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004830 mActiveTracks.setHasChanged();
4831
Eric Laurent1c333e22014-05-20 10:48:17 -07004832 return status;
4833}
4834
Andy Hung71742ab2023-07-07 13:47:37 -07004835status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004836{
Andy Hungf60abce2016-08-26 11:37:54 -07004837 status_t status;
4838 if (property_get_bool("af.patch_park", false /* default_value */)) {
4839 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4840 // or if HAL does not properly lock against access.
4841 AutoPark<FastMixer> park(mFastMixer);
4842 status = PlaybackThread::releaseAudioPatch_l(handle);
4843 } else {
4844 status = PlaybackThread::releaseAudioPatch_l(handle);
4845 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004846 return status;
4847}
4848
Andy Hung71742ab2023-07-07 13:47:37 -07004849status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004850{
4851 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004852
jiabinc52b1ff2019-10-31 17:20:42 -07004853 mPatch = audio_patch{};
4854 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004855
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004856 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004857 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4858 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004859 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004860 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004861 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004862 // Force meteadata update after a route change
4863 mActiveTracks.setHasChanged();
4864
Eric Laurent1c333e22014-05-20 10:48:17 -07004865 return status;
4866}
4867
Andy Hung71742ab2023-07-07 13:47:37 -07004868void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004869{
4870 Mutex::Autolock _l(mLock);
4871 mTracks.add(track);
4872}
4873
Andy Hung71742ab2023-07-07 13:47:37 -07004874void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004875{
4876 Mutex::Autolock _l(mLock);
4877 destroyTrack_l(track);
4878}
4879
Andy Hung71742ab2023-07-07 13:47:37 -07004880void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07004881{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004882 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004883 config->role = AUDIO_PORT_ROLE_SOURCE;
4884 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4885 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004886 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4887 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4888 config->flags.output = mOutput->flags;
4889 }
Eric Laurent83b88082014-06-20 18:31:16 -07004890}
4891
Eric Laurent81784c32012-11-19 14:55:58 -08004892// ----------------------------------------------------------------------------
4893
Andy Hung71742ab2023-07-07 13:47:37 -07004894/* static */
4895sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07004896 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hung71742ab2023-07-07 13:47:37 -07004897 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung2cbc2722023-07-17 17:05:00 -07004898 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hung71742ab2023-07-07 13:47:37 -07004899}
4900
Andy Hung2cbc2722023-07-17 17:05:00 -07004901MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004902 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung2cbc2722023-07-17 17:05:00 -07004903 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004904 // mAudioMixer below
4905 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01004906 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004907 mFastMixerFutex(0),
4908 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004909 // mOutputSink below
4910 // mPipeSink below
4911 // mNormalSink below
4912{
Andy Hung2cbc2722023-07-17 17:05:00 -07004913 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004914 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004915 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004916 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004917 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4918 mNormalFrameCount);
4919 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4920
Andy Hungfbfc3952015-01-15 13:33:51 -08004921 if (type == DUPLICATING) {
4922 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4923 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4924 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4925 return;
4926 }
Eric Laurent81784c32012-11-19 14:55:58 -08004927 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004928 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004929 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004930 const NBAIO_Format offers[1] = {Format_from_SR_C(
4931 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004932#if !LOG_NDEBUG
4933 ssize_t index =
4934#else
4935 (void)
4936#endif
4937 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004938 ALOG_ASSERT(index == 0);
4939
4940 // initialize fast mixer depending on configuration
4941 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00004942 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08004943 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004944 } else {
4945 switch (kUseFastMixer) {
4946 case FastMixer_Never:
4947 initFastMixer = false;
4948 break;
4949 case FastMixer_Always:
4950 initFastMixer = true;
4951 break;
4952 case FastMixer_Static:
4953 case FastMixer_Dynamic:
4954 initFastMixer = mFrameCount < mNormalFrameCount;
4955 break;
4956 }
4957 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4958 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4959 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004960 }
4961 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004962 audio_format_t fastMixerFormat;
4963 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4964 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4965 } else {
4966 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4967 }
4968 if (mFormat != fastMixerFormat) {
4969 // change our Sink format to accept our intermediate precision
4970 mFormat = fastMixerFormat;
4971 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004972 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004973 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4974 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4975 }
Eric Laurent81784c32012-11-19 14:55:58 -08004976
4977 // create a MonoPipe to connect our submix to FastMixer
4978 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004979
Andy Hung1258c1a2014-05-23 21:22:17 -07004980 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004981 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004982 format.mFormat = fastMixerFormat;
4983 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4984
Eric Laurent81784c32012-11-19 14:55:58 -08004985 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4986 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4987 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4988 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung71ba4b32022-10-06 12:09:49 -07004989 const NBAIO_Format offersFast[1] = {format};
4990 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004991#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02004992 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004993#else
4994 (void)
4995#endif
Andy Hung71ba4b32022-10-06 12:09:49 -07004996 monoPipe->negotiate(offersFast, std::size(offersFast),
4997 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08004998 ALOG_ASSERT(index == 0);
4999 monoPipe->setAvgFrames((mScreenState & 1) ?
5000 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5001 mPipeSink = monoPipe;
5002
Eric Laurent81784c32012-11-19 14:55:58 -08005003 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005004 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005005 FastMixerStateQueue *sq = mFastMixer->sq();
5006#ifdef STATE_QUEUE_DUMP
5007 sq->setObserverDump(&mStateQueueObserverDump);
5008 sq->setMutatorDump(&mStateQueueMutatorDump);
5009#endif
5010 FastMixerState *state = sq->begin();
5011 FastTrack *fastTrack = &state->mFastTracks[0];
5012 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5013 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5014 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005015 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5016 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5017 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005018 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005019 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07005020 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01005021 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005022 fastTrack->mGeneration++;
5023 state->mFastTracksGen++;
5024 state->mTrackMask = 1;
5025 // fast mixer will use the HAL output sink
5026 state->mOutputSink = mOutputSink.get();
5027 state->mOutputSinkGen++;
5028 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005029 // specify sink channel mask when haptic channel mask present as it can not
5030 // be calculated directly from channel count
5031 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005032 ? AUDIO_CHANNEL_NONE
5033 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005034 state->mCommand = FastMixerState::COLD_IDLE;
5035 // already done in constructor initialization list
5036 //mFastMixerFutex = 0;
5037 state->mColdFutexAddr = &mFastMixerFutex;
5038 state->mColdGen++;
5039 state->mDumpState = &mFastMixerDumpState;
Andy Hung2cbc2722023-07-17 17:05:00 -07005040 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005041 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005042 sq->end();
5043 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5044
Eric Tan0513b5d2018-09-17 10:32:48 -07005045 NBLog::thread_info_t info;
5046 info.id = mId;
5047 info.type = NBLog::FASTMIXER;
5048 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5049
Eric Laurent81784c32012-11-19 14:55:58 -08005050 // start the fast mixer
5051 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5052 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005053 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005054 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005055
5056#ifdef AUDIO_WATCHDOG
5057 // create and start the watchdog
5058 mAudioWatchdog = new AudioWatchdog();
5059 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5060 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5061 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005062 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005063#endif
Andy Hung8946a282018-04-19 20:04:56 -07005064 } else {
5065#ifdef TEE_SINK
5066 // Only use the MixerThread tee if there is no FastMixer.
5067 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5068 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5069#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005070 }
5071
5072 switch (kUseFastMixer) {
5073 case FastMixer_Never:
5074 case FastMixer_Dynamic:
5075 mNormalSink = mOutputSink;
5076 break;
5077 case FastMixer_Always:
5078 mNormalSink = mPipeSink;
5079 break;
5080 case FastMixer_Static:
5081 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5082 break;
5083 }
5084}
5085
Andy Hung71742ab2023-07-07 13:47:37 -07005086MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005087{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005088 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005089 FastMixerStateQueue *sq = mFastMixer->sq();
5090 FastMixerState *state = sq->begin();
5091 if (state->mCommand == FastMixerState::COLD_IDLE) {
5092 int32_t old = android_atomic_inc(&mFastMixerFutex);
5093 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005094 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005095 }
5096 }
5097 state->mCommand = FastMixerState::EXIT;
5098 sq->end();
5099 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5100 mFastMixer->join();
5101 // Though the fast mixer thread has exited, it's state queue is still valid.
5102 // We'll use that extract the final state which contains one remaining fast track
5103 // corresponding to our sub-mix.
5104 state = sq->begin();
5105 ALOG_ASSERT(state->mTrackMask == 1);
5106 FastTrack *fastTrack = &state->mFastTracks[0];
5107 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5108 delete fastTrack->mBufferProvider;
5109 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005110 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005111#ifdef AUDIO_WATCHDOG
5112 if (mAudioWatchdog != 0) {
5113 mAudioWatchdog->requestExit();
5114 mAudioWatchdog->requestExitAndWait();
5115 mAudioWatchdog.clear();
5116 }
5117#endif
5118 }
Andy Hung2cbc2722023-07-17 17:05:00 -07005119 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005120 delete mAudioMixer;
5121}
5122
Andy Hung71742ab2023-07-07 13:47:37 -07005123void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005124 PlaybackThread::onFirstRef();
5125
5126 Mutex::Autolock _l(mLock);
5127 if (mOutput != nullptr && mOutput->stream != nullptr) {
5128 status_t status = mOutput->stream->setLatencyModeCallback(this);
5129 if (status != INVALID_OPERATION) {
5130 updateHalSupportedLatencyModes_l();
5131 }
5132 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5133 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5134 mBluetoothLatencyModesEnabled.store(
5135 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5136 }
5137}
Eric Laurent81784c32012-11-19 14:55:58 -08005138
Andy Hung71742ab2023-07-07 13:47:37 -07005139uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005140{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005141 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005142 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5143 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5144 }
5145 return latency;
5146}
5147
Andy Hung71742ab2023-07-07 13:47:37 -07005148ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005149{
5150 // FIXME we should only do one push per cycle; confirm this is true
5151 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005152 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005153 FastMixerStateQueue *sq = mFastMixer->sq();
5154 FastMixerState *state = sq->begin();
5155 if (state->mCommand != FastMixerState::MIX_WRITE &&
5156 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5157 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005158
5159 // FIXME workaround for first HAL write being CPU bound on some devices
5160 ATRACE_BEGIN("write");
5161 mOutput->write((char *)mSinkBuffer, 0);
5162 ATRACE_END();
5163
Eric Laurent81784c32012-11-19 14:55:58 -08005164 int32_t old = android_atomic_inc(&mFastMixerFutex);
5165 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005166 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005167 }
5168#ifdef AUDIO_WATCHDOG
5169 if (mAudioWatchdog != 0) {
5170 mAudioWatchdog->resume();
5171 }
5172#endif
5173 }
5174 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005175#ifdef FAST_THREAD_STATISTICS
Andy Hung2cbc2722023-07-17 17:05:00 -07005176 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005177 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005178#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005179 sq->end();
5180 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5181 if (kUseFastMixer == FastMixer_Dynamic) {
5182 mNormalSink = mPipeSink;
5183 }
5184 } else {
5185 sq->end(false /*didModify*/);
5186 }
5187 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005188 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005189}
5190
Andy Hung71742ab2023-07-07 13:47:37 -07005191void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005192{
5193 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005194 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005195 FastMixerStateQueue *sq = mFastMixer->sq();
5196 FastMixerState *state = sq->begin();
5197 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005198 // Report any frames trapped in the Monopipe
5199 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5200 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5201 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5202 "monoPipeWritten:%lld monoPipeLeft:%lld",
5203 (long long)mFramesWritten, (long long)mSuspendedFrames,
5204 (long long)mPipeSink->framesWritten(), pipeFrames);
5205 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5206
Eric Laurent81784c32012-11-19 14:55:58 -08005207 state->mCommand = FastMixerState::COLD_IDLE;
5208 state->mColdFutexAddr = &mFastMixerFutex;
5209 state->mColdGen++;
5210 mFastMixerFutex = 0;
5211 sq->end();
5212 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5213 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5214 if (kUseFastMixer == FastMixer_Dynamic) {
5215 mNormalSink = mOutputSink;
5216 }
5217#ifdef AUDIO_WATCHDOG
5218 if (mAudioWatchdog != 0) {
5219 mAudioWatchdog->pause();
5220 }
5221#endif
5222 } else {
5223 sq->end(false /*didModify*/);
5224 }
5225 }
5226 PlaybackThread::threadLoop_standby();
5227}
5228
Andy Hung71742ab2023-07-07 13:47:37 -07005229bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005230{
5231 return false;
5232}
5233
Andy Hung71742ab2023-07-07 13:47:37 -07005234bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005235{
5236 return !mStandby;
5237}
5238
Andy Hung71742ab2023-07-07 13:47:37 -07005239bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005240{
5241 Mutex::Autolock _l(mLock);
5242 return waitingAsyncCallback_l();
5243}
5244
Eric Laurent81784c32012-11-19 14:55:58 -08005245// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung71742ab2023-07-07 13:47:37 -07005246void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005247{
5248 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005249 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005250 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005251 // discard any pending drain or write ack by incrementing sequence
5252 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5253 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005254 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005255 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5256 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005257 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005258 mHwPaused = false;
Eric Laurent6f9534f2022-05-03 18:15:04 +02005259 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005260}
5261
Andy Hung71742ab2023-07-07 13:47:37 -07005262void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005263{
5264 ALOGV("signal playback thread");
5265 broadcast_l();
5266}
5267
Andy Hung71742ab2023-07-07 13:47:37 -07005268void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005269{
5270 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5271 invalidateTracks((audio_stream_type_t)i);
5272 }
5273}
5274
Andy Hung71742ab2023-07-07 13:47:37 -07005275void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005276{
Eric Laurent81784c32012-11-19 14:55:58 -08005277 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005278 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005279 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005280 // increase sleep time progressively when application underrun condition clears.
5281 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5282 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5283 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005284 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005285 sleepTimeShift--;
5286 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005287 mSleepTimeUs = 0;
5288 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005289 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005290
Eric Laurent81784c32012-11-19 14:55:58 -08005291}
5292
Andy Hung71742ab2023-07-07 13:47:37 -07005293void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005294{
5295 // If no tracks are ready, sleep once for the duration of an output
5296 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005297 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005298 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005299 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5300 // Using the Monopipe availableToWrite, we estimate the
5301 // sleep time to retry for more data (before we underrun).
5302 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5303 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5304 const size_t pipeFrames = monoPipe->maxFrames();
5305 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5306 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5307 const size_t framesDelay = std::min(
5308 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5309 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5310 pipeFrames, framesLeft, framesDelay);
5311 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5312 } else {
5313 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5314 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5315 mSleepTimeUs = kMinThreadSleepTimeUs;
5316 }
5317 // reduce sleep time in case of consecutive application underruns to avoid
5318 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5319 // duration we would end up writing less data than needed by the audio HAL if
5320 // the condition persists.
5321 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5322 sleepTimeShift++;
5323 }
Eric Laurent81784c32012-11-19 14:55:58 -08005324 }
5325 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005326 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005327 }
5328 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005329 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5330 // before effects processing or output.
5331 if (mMixerBufferValid) {
5332 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005333 if (mType == SPATIALIZER) {
5334 memset(mSinkBuffer, 0, mSinkBufferSize);
5335 }
Andy Hung98ef9782014-03-04 14:46:50 -08005336 } else {
5337 memset(mSinkBuffer, 0, mSinkBufferSize);
5338 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005339 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005340 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5341 "anticipated start");
5342 }
5343 // TODO add standby time extension fct of effect tail
5344}
5345
5346// prepareTracks_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07005347PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07005348 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005349{
Andy Hungc0691382018-09-12 18:01:57 -07005350 // clean up deleted track ids in AudioMixer before allocating new tracks
5351 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5352 // for each trackId, destroy it in the AudioMixer
5353 if (mAudioMixer->exists(trackId)) {
5354 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005355 }
5356 });
Andy Hungc0691382018-09-12 18:01:57 -07005357 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005358
5359 mixer_state mixerStatus = MIXER_IDLE;
5360 // find out which tracks need to be processed
5361 size_t count = mActiveTracks.size();
5362 size_t mixedTracks = 0;
5363 size_t tracksWithEffect = 0;
5364 // counts only _active_ fast tracks
5365 size_t fastTracks = 0;
5366 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5367
5368 float masterVolume = mMasterVolume;
5369 bool masterMute = mMasterMute;
5370
5371 if (masterMute) {
5372 masterVolume = 0;
5373 }
5374 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hungbd72c542023-06-20 18:56:17 -07005375 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005376 if (chain != 0) {
5377 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5378 chain->setVolume_l(&v, &v);
5379 masterVolume = (float)((v + (1 << 23)) >> 24);
5380 chain.clear();
5381 }
5382
5383 // prepare a new state to push
5384 FastMixerStateQueue *sq = NULL;
5385 FastMixerState *state = NULL;
5386 bool didModify = false;
5387 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005388 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005389 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005390 sq = mFastMixer->sq();
5391 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005392 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005393 }
5394
Andy Hung69aed5f2014-02-25 17:24:40 -08005395 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005396 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005397
Andy Hungbd3b2b02018-05-21 10:53:11 -07005398 // DeferredOperations handles statistics after setting mixerStatus.
5399 class DeferredOperations {
5400 public:
Andy Hungea840382020-05-05 21:50:17 -07005401 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5402 : mMixerStatus(mixerStatus)
5403 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005404
5405 // when leaving scope, tally frames properly.
5406 ~DeferredOperations() {
5407 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5408 // because that is when the underrun occurs.
5409 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005410 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005411 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005412 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005413 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005414 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005415 }
5416 }
Andy Hungea840382020-05-05 21:50:17 -07005417 // send the max underrun frames for this mixer period
5418 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005419 }
5420
5421 // tallyUnderrunFrames() is called to update the track counters
5422 // with the number of underrun frames for a particular mixer period.
5423 // We defer tallying until we know the final mixer status.
Andy Hung3ff4b552023-06-26 19:20:57 -07005424 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005425 mUnderrunFrames.emplace_back(track, underrunFrames);
5426 }
5427
5428 private:
5429 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005430 ThreadMetrics * const mThreadMetrics;
Andy Hung3ff4b552023-06-26 19:20:57 -07005431 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005432 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005433 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005434
jiabin245cdd92018-12-07 17:55:15 -08005435 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005436 for (size_t i=0 ; i<count ; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005437 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005438
5439 // this const just means the local variable doesn't change
Andy Hung3ff4b552023-06-26 19:20:57 -07005440 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005441
5442 // process fast tracks
5443 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005444 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5445 "%s(%d): FastTrack(%d) present without FastMixer",
5446 __func__, id(), track->id());
5447
jiabin245cdd92018-12-07 17:55:15 -08005448 if (track->getHapticPlaybackEnabled()) {
5449 noFastHapticTrack = false;
5450 }
Eric Laurent81784c32012-11-19 14:55:58 -08005451
5452 // It's theoretically possible (though unlikely) for a fast track to be created
5453 // and then removed within the same normal mix cycle. This is not a problem, as
5454 // the track never becomes active so it's fast mixer slot is never touched.
5455 // The converse, of removing an (active) track and then creating a new track
5456 // at the identical fast mixer slot within the same normal mix cycle,
5457 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung3ff4b552023-06-26 19:20:57 -07005458 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005459 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005460 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5461 FastTrack *fastTrack = &state->mFastTracks[j];
5462
5463 // Determine whether the track is currently in underrun condition,
5464 // and whether it had a recent underrun.
5465 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5466 FastTrackUnderruns underruns = ftDump->mUnderruns;
5467 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung3ff4b552023-06-26 19:20:57 -07005468 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005469 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung3ff4b552023-06-26 19:20:57 -07005470 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005471 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung3ff4b552023-06-26 19:20:57 -07005472 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005473 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung3ff4b552023-06-26 19:20:57 -07005474 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005475 // don't count underruns that occur while stopping or pausing
5476 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005477 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005478 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5479 recentUnderruns > 0) {
5480 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005481 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005482 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005483 // Immediately account for FastTrack underruns.
Andy Hung3ff4b552023-06-26 19:20:57 -07005484 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005485
5486 // This is similar to the state machine for normal tracks,
5487 // with a few modifications for fast tracks.
5488 bool isActive = true;
Andy Hung3ff4b552023-06-26 19:20:57 -07005489 switch (track->state()) {
5490 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005491 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005492 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005493 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005494 }
5495 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005496 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005497 // ramp down is not yet implemented
5498 track->setPaused();
5499 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005500 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005501 // ramp up is not yet implemented
Andy Hung3ff4b552023-06-26 19:20:57 -07005502 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005503 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005504 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005505 if (recentFull > 0 || recentPartial > 0) {
5506 // track has provided at least some frames recently: reset retry count
Andy Hung3ff4b552023-06-26 19:20:57 -07005507 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005508 }
5509 if (recentUnderruns == 0) {
5510 // no recent underruns: stay active
5511 break;
5512 }
5513 // there has recently been an underrun of some kind
5514 if (track->sharedBuffer() == 0) {
5515 // were any of the recent underruns "empty" (no frames available)?
5516 if (recentEmpty == 0) {
5517 // no, then ignore the partial underruns as they are allowed indefinitely
5518 break;
5519 }
5520 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung3ff4b552023-06-26 19:20:57 -07005521 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005522 break;
5523 }
5524 // indicate to client process that the track was disabled because of underrun;
5525 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005526 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005527 // remove from active list, but state remains ACTIVE [confusing but true]
5528 isActive = false;
5529 break;
5530 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005531 FALLTHROUGH_INTENDED;
Andy Hung3ff4b552023-06-26 19:20:57 -07005532 case IAfTrackBase::STOPPING_2:
5533 case IAfTrackBase::PAUSED:
5534 case IAfTrackBase::STOPPED:
5535 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005536 // Check for presentation complete if track is inactive
5537 // We have consumed all the buffers of this track.
5538 // This would be incomplete if we auto-paused on underrun
5539 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005540 uint32_t latency = 0;
5541 status_t result = mOutput->stream->getLatency(&latency);
5542 ALOGE_IF(result != OK,
5543 "Error when retrieving output stream latency: %d", result);
5544 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005545 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005546 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5547 // track stays in active list until presentation is complete
5548 break;
5549 }
5550 }
5551 if (track->isStopping_2()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005552 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005553 }
5554 if (track->isStopped()) {
5555 // Can't reset directly, as fast mixer is still polling this track
5556 // track->reset();
5557 // So instead mark this track as needing to be reset after push with ack
5558 resetMask |= 1 << i;
5559 }
5560 isActive = false;
5561 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005562 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005563 default:
Andy Hung3ff4b552023-06-26 19:20:57 -07005564 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005565 }
5566
5567 if (isActive) {
5568 // was it previously inactive?
5569 if (!(state->mTrackMask & (1 << j))) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005570 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5571 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005572 fastTrack->mBufferProvider = eabp;
5573 fastTrack->mVolumeProvider = vp;
Andy Hung3ff4b552023-06-26 19:20:57 -07005574 fastTrack->mChannelMask = track->channelMask();
5575 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005576 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005577 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005578 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005579 fastTrack->mGeneration++;
5580 state->mTrackMask |= 1 << j;
5581 didModify = true;
5582 // no acknowledgement required for newly active tracks
5583 }
Andy Hung3ff4b552023-06-26 19:20:57 -07005584 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005585 float volume;
5586 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5587 volume = 0.f;
5588 } else {
5589 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5590 }
5591
5592 handleVoipVolume_l(&volume);
5593
Eric Laurent81784c32012-11-19 14:55:58 -08005594 // cache the combined master volume and stream type volume for fast mixer; this
5595 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005596 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005597 proxy->framesReleased()).first;
5598 volume *= vh;
Andy Hung3ff4b552023-06-26 19:20:57 -07005599 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005600 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005601 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5602 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005603
Andy Hung2cbc2722023-07-17 17:05:00 -07005604 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005605 /*muteState=*/{masterVolume == 0.f,
5606 mStreamTypes[track->streamType()].volume == 0.f,
5607 mStreamTypes[track->streamType()].mute,
5608 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005609 vlf == 0.f && vrf == 0.f,
5610 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005611
5612 vlf *= volume;
5613 vrf *= volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005614
jiabin76d94692022-12-15 21:51:21 +00005615 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005616 ++fastTracks;
5617 } else {
5618 // was it previously active?
5619 if (state->mTrackMask & (1 << j)) {
5620 fastTrack->mBufferProvider = NULL;
5621 fastTrack->mGeneration++;
5622 state->mTrackMask &= ~(1 << j);
5623 didModify = true;
5624 // If any fast tracks were removed, we must wait for acknowledgement
5625 // because we're about to decrement the last sp<> on those tracks.
5626 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5627 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005628 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5629 // AudioTrack may start (which may not be with a start() but with a write()
5630 // after underrun) and immediately paused or released. In that case the
5631 // FastTrack state hasn't had time to update.
5632 // TODO Remove the ALOGW when this theory is confirmed.
5633 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005634 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung3ff4b552023-06-26 19:20:57 -07005635 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005636 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005637 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005638 }
5639 tracksToRemove->add(track);
5640 // Avoids a misleading display in dumpsys
Andy Hung3ff4b552023-06-26 19:20:57 -07005641 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005642 }
jiabin245cdd92018-12-07 17:55:15 -08005643 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5644 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5645 didModify = true;
5646 }
Eric Laurent81784c32012-11-19 14:55:58 -08005647 continue;
5648 }
5649
5650 { // local variable scope to avoid goto warning
5651
5652 audio_track_cblk_t* cblk = track->cblk();
5653
5654 // The first time a track is added we wait
5655 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005656 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005657
5658 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005659 // use the trackId as the AudioMixer name.
5660 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005661 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005662 trackId,
Andy Hung3ff4b552023-06-26 19:20:57 -07005663 track->channelMask(),
5664 track->format(),
5665 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005666 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005667 ALOGW("%s(): AudioMixer cannot create track(%d)"
5668 " mask %#x, format %#x, sessionId %d",
5669 __func__, trackId,
Andy Hung3ff4b552023-06-26 19:20:57 -07005670 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005671 tracksToRemove->add(track);
5672 track->invalidate(); // consider it dead.
5673 continue;
5674 }
5675 }
5676
Eric Laurent81784c32012-11-19 14:55:58 -08005677 // make sure that we have enough frames to mix one full buffer.
5678 // enforce this condition only once to enable draining the buffer in case the client
5679 // app does not call stop() and relies on underrun to stop:
5680 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5681 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005682 size_t desiredFrames;
Andy Hung3ff4b552023-06-26 19:20:57 -07005683 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5684 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005685
5686 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005687 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005688 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5689 // add frames already consumed but not yet released by the resampler
5690 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005691 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005692
Eric Laurent81784c32012-11-19 14:55:58 -08005693 uint32_t minFrames = 1;
5694 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5695 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005696 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005697 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005698
5699 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005700 if (ATRACE_ENABLED()) {
5701 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005702 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005703 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005704 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005705 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005706 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005707 !track->isPaused() && !track->isTerminated())
5708 {
Andy Hungc0691382018-09-12 18:01:57 -07005709 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005710
5711 mixedTracks++;
5712
Andy Hung69aed5f2014-02-25 17:24:40 -08005713 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5714 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005715 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005716 if (track->mainBuffer() != mSinkBuffer &&
5717 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005718 if (mEffectBufferEnabled) {
5719 mEffectBufferValid = true; // Later can set directly.
5720 }
Eric Laurent81784c32012-11-19 14:55:58 -08005721 chain = getEffectChain_l(track->sessionId());
5722 // Delegate volume control to effect in track effect chain if needed
5723 if (chain != 0) {
5724 tracksWithEffect++;
5725 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005726 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005727 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005728 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005729 }
5730 }
5731
5732
5733 int param = AudioMixer::VOLUME;
Andy Hung3ff4b552023-06-26 19:20:57 -07005734 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005735 // no ramp for the first volume setting
Andy Hung3ff4b552023-06-26 19:20:57 -07005736 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5737 if (track->state() == IAfTrackBase::RESUMING) {
5738 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005739 // If a new track is paused immediately after start, do not ramp on resume.
5740 if (cblk->mServer != 0) {
5741 param = AudioMixer::RAMP_VOLUME;
5742 }
Eric Laurent81784c32012-11-19 14:55:58 -08005743 }
Andy Hungc0691382018-09-12 18:01:57 -07005744 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005745 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005746 // FIXME should not make a decision based on mServer
5747 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005748 // If the track is stopped before the first frame was mixed,
5749 // do not apply ramp
5750 param = AudioMixer::RAMP_VOLUME;
5751 }
5752
5753 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005754 uint32_t vl, vr; // in U8.24 integer format
5755 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005756 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005757 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005758 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung3ff4b552023-06-26 19:20:57 -07005759 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005760 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung3ff4b552023-06-26 19:20:57 -07005761 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005762
Eric Laurenteab90452019-06-24 15:17:46 -07005763 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5764 v = 0;
5765 }
5766
5767 handleVoipVolume_l(&v);
5768
5769 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005770 vl = vr = 0;
5771 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005772 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005773 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005774 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005775 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5776 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005777 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005778 if (vlf > GAIN_FLOAT_UNITY) {
5779 ALOGV("Track left volume out of range: %.3g", vlf);
5780 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005781 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005782 if (vrf > GAIN_FLOAT_UNITY) {
5783 ALOGV("Track right volume out of range: %.3g", vrf);
5784 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005785 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005786
Andy Hung2cbc2722023-07-17 17:05:00 -07005787 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005788 /*muteState=*/{masterVolume == 0.f,
5789 mStreamTypes[track->streamType()].volume == 0.f,
5790 mStreamTypes[track->streamType()].mute,
5791 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005792 vlf == 0.f && vrf == 0.f,
5793 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005794
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005795 // now apply the master volume and stream type volume and shaper volume
5796 vlf *= v * vh;
5797 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005798 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005799 // then derive vl and vr as U8.24 versions for the effect chain
5800 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5801 vl = (uint32_t) (scaleto8_24 * vlf);
5802 vr = (uint32_t) (scaleto8_24 * vrf);
5803 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005804 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005805 // send level comes from shared memory and so may be corrupt
5806 if (sendLevel > MAX_GAIN_INT) {
5807 ALOGV("Track send level out of range: %04X", sendLevel);
5808 sendLevel = MAX_GAIN_INT;
5809 }
Andy Hung6be49402014-05-30 10:42:03 -07005810 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5811 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005812 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005813
jiabin76d94692022-12-15 21:51:21 +00005814 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005815
Eric Laurent81784c32012-11-19 14:55:58 -08005816 // Delegate volume control to effect in track effect chain if needed
5817 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5818 // Do not ramp volume if volume is controlled by effect
5819 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005820 // Update remaining floating point volume levels
5821 vlf = (float)vl / (1 << 24);
5822 vrf = (float)vr / (1 << 24);
Andy Hung3ff4b552023-06-26 19:20:57 -07005823 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005824 } else {
5825 // force no volume ramp when volume controller was just disabled or removed
5826 // from effect chain to avoid volume spike
Andy Hung3ff4b552023-06-26 19:20:57 -07005827 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005828 param = AudioMixer::VOLUME;
5829 }
Andy Hung3ff4b552023-06-26 19:20:57 -07005830 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005831 }
5832
Eric Laurent81784c32012-11-19 14:55:58 -08005833 // XXX: these things DON'T need to be done each time
Andy Hung3ff4b552023-06-26 19:20:57 -07005834 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005835 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005836
Andy Hungc0691382018-09-12 18:01:57 -07005837 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5838 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5839 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005840 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005841 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005842 AudioMixer::TRACK,
5843 AudioMixer::FORMAT, (void *)track->format());
5844 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005845 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005846 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005847 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005848
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005849 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005850 mAudioMixer->setParameter(
5851 trackId,
5852 AudioMixer::TRACK,
5853 AudioMixer::MIXER_CHANNEL_MASK,
5854 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5855 } else {
5856 mAudioMixer->setParameter(
5857 trackId,
5858 AudioMixer::TRACK,
5859 AudioMixer::MIXER_CHANNEL_MASK,
5860 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5861 }
5862
Glenn Kastene3aa6592012-12-04 12:22:46 -08005863 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005864 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005865 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005866 if (reqSampleRate == 0) {
5867 reqSampleRate = mSampleRate;
5868 } else if (reqSampleRate > maxSampleRate) {
5869 reqSampleRate = maxSampleRate;
5870 }
Eric Laurent81784c32012-11-19 14:55:58 -08005871 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005872 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005873 AudioMixer::RESAMPLE,
5874 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005875 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005876
Andy Hung8edb8dc2015-03-26 19:13:55 -07005877 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005878 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005879 AudioMixer::TIMESTRETCH,
5880 AudioMixer::PLAYBACK_RATE,
Andy Hung71ba4b32022-10-06 12:09:49 -07005881 // cast away constness for this generic API.
5882 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005883
Andy Hung69aed5f2014-02-25 17:24:40 -08005884 /*
5885 * Select the appropriate output buffer for the track.
5886 *
Andy Hung98ef9782014-03-04 14:46:50 -08005887 * Tracks with effects go into their own effects chain buffer
5888 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005889 *
5890 * Other tracks can use mMixerBuffer for higher precision
5891 * channel accumulation. If this buffer is enabled
5892 * (mMixerBufferEnabled true), then selected tracks will accumulate
5893 * into it.
5894 *
5895 */
5896 if (mMixerBufferEnabled
5897 && (track->mainBuffer() == mSinkBuffer
5898 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005899 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005900 mAudioMixer->setParameter(
5901 trackId,
5902 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005903 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005904 mAudioMixer->setParameter(
5905 trackId,
5906 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005907 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005908 } else {
5909 mAudioMixer->setParameter(
5910 trackId,
5911 AudioMixer::TRACK,
5912 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5913 mAudioMixer->setParameter(
5914 trackId,
5915 AudioMixer::TRACK,
5916 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5917 // TODO: override track->mainBuffer()?
5918 mMixerBufferValid = true;
5919 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005920 } else {
5921 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005922 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005923 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07005924 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005925 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005926 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005927 AudioMixer::TRACK,
5928 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5929 }
Eric Laurent81784c32012-11-19 14:55:58 -08005930 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005931 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005932 AudioMixer::TRACK,
5933 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005934 mAudioMixer->setParameter(
5935 trackId,
5936 AudioMixer::TRACK,
5937 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005938 mAudioMixer->setParameter(
5939 trackId,
5940 AudioMixer::TRACK,
5941 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung3ff4b552023-06-26 19:20:57 -07005942 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005943 mAudioMixer->setParameter(
5944 trackId,
5945 AudioMixer::TRACK,
Andy Hung3ff4b552023-06-26 19:20:57 -07005946 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08005947
5948 // reset retry count
Andy Hung3ff4b552023-06-26 19:20:57 -07005949 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005950
5951 // If one track is ready, set the mixer ready if:
5952 // - the mixer was not ready during previous round OR
5953 // - no other track is not ready
5954 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5955 mixerStatus != MIXER_TRACKS_ENABLED) {
5956 mixerStatus = MIXER_TRACKS_READY;
5957 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005958
5959 // Enable the next few lines to instrument a test for underrun log handling.
5960 // TODO: Remove when we have a better way of testing the underrun log.
5961#if 0
5962 static int i;
5963 if ((++i & 0xf) == 0) {
5964 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5965 }
5966#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005967 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005968 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005969 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005970 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5971 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005972 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005973 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005974 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005975
Eric Laurent81784c32012-11-19 14:55:58 -08005976 // clear effect chain input buffer if an active track underruns to avoid sending
5977 // previous audio buffer again to effects
5978 chain = getEffectChain_l(track->sessionId());
5979 if (chain != 0) {
5980 chain->clearInputBuffer();
5981 }
5982
Andy Hungc0691382018-09-12 18:01:57 -07005983 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005984 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5985 track->isStopped() || track->isPaused()) {
5986 // We have consumed all the buffers of this track.
5987 // Remove it from the list of active tracks.
5988 // TODO: use actual buffer filling status instead of latency when available from
5989 // audio HAL
5990 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005991 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005992 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5993 if (track->isStopped()) {
5994 track->reset();
5995 }
5996 tracksToRemove->add(track);
5997 }
5998 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005999 // No buffers for this track. Give it a few chances to
6000 // fill a buffer, then remove it from active list.
Andy Hung3ff4b552023-06-26 19:20:57 -07006001 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07006002 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
6003 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006004 tracksToRemove->add(track);
6005 // indicate to client process that the track was disabled because of underrun;
6006 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006007 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006008 // If one track is not ready, mark the mixer also not ready if:
6009 // - the mixer was ready during previous round OR
6010 // - no other track is ready
6011 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6012 mixerStatus != MIXER_TRACKS_READY) {
6013 mixerStatus = MIXER_TRACKS_ENABLED;
6014 }
6015 }
Andy Hungc0691382018-09-12 18:01:57 -07006016 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006017 }
6018
6019 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006020
6021 }
6022
jiabin245cdd92018-12-07 17:55:15 -08006023 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6024 // When there is no fast track playing haptic and FastMixer exists,
6025 // enabling the first FastTrack, which provides mixed data from normal
6026 // tracks, to play haptic data.
6027 FastTrack *fastTrack = &state->mFastTracks[0];
6028 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6029 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6030 didModify = true;
6031 }
6032 }
6033
Eric Laurent81784c32012-11-19 14:55:58 -08006034 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006035 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006036 if (didModify) {
6037 state->mFastTracksGen++;
6038 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6039 if (kUseFastMixer == FastMixer_Dynamic &&
6040 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6041 state->mCommand = FastMixerState::COLD_IDLE;
6042 state->mColdFutexAddr = &mFastMixerFutex;
6043 state->mColdGen++;
6044 mFastMixerFutex = 0;
6045 if (kUseFastMixer == FastMixer_Dynamic) {
6046 mNormalSink = mOutputSink;
6047 }
6048 // If we go into cold idle, need to wait for acknowledgement
6049 // so that fast mixer stops doing I/O.
6050 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6051 pauseAudioWatchdog = true;
6052 }
Eric Laurent81784c32012-11-19 14:55:58 -08006053 }
6054 if (sq != NULL) {
6055 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006056 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6057 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6058 // when bringing the output sink into standby.)
6059 //
6060 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6061 //
6062 // This occurs with BT suspend when we idle the FastMixer with
6063 // active tracks, which may be added or removed.
6064 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006065 }
6066#ifdef AUDIO_WATCHDOG
6067 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6068 mAudioWatchdog->pause();
6069 }
6070#endif
6071
6072 // Now perform the deferred reset on fast tracks that have stopped
6073 while (resetMask != 0) {
6074 size_t i = __builtin_ctz(resetMask);
6075 ALOG_ASSERT(i < count);
6076 resetMask &= ~(1 << i);
Andy Hung3ff4b552023-06-26 19:20:57 -07006077 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006078 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6079 track->reset();
6080 }
6081
Andy Hung80d03d22018-04-10 10:32:11 -07006082 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6083 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6084 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6085 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6086 // See also the implementation of destroyTrack_l().
6087 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006088 const int trackId = track->id();
6089 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6090 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006091 }
6092 }
6093
Eric Laurent81784c32012-11-19 14:55:58 -08006094 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006095 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006096
Eric Laurentb3f315a2021-07-13 15:09:05 +02006097 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6098 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006099 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006100 }
6101
6102 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006103 // as long as there are effects we should clear the effects buffer, to avoid
6104 // passing a non-clean buffer to the effect chain
6105 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006106 if (mType == SPATIALIZER) {
6107 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6108 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006109 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006110 // sink or mix buffer must be cleared if all tracks are connected to an
6111 // effect chain as in this case the mixer will not write to the sink or mix buffer
6112 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006113 // always clear sink buffer for spatializer output as the output of the spatializer
6114 // effect will be accumulated into it
6115 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6116 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006117 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006118 if (mMixerBufferValid) {
6119 memset(mMixerBuffer, 0, mMixerBufferSize);
6120 // TODO: In testing, mSinkBuffer below need not be cleared because
6121 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6122 // after mixing.
6123 //
6124 // To enforce this guarantee:
6125 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6126 // (mixedTracks == 0 && fastTracks > 0))
6127 // must imply MIXER_TRACKS_READY.
6128 // Later, we may clear buffers regardless, and skip much of this logic.
6129 }
Andy Hung98ef9782014-03-04 14:46:50 -08006130 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006131 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006132 }
6133
6134 // if any fast tracks, then status is ready
6135 mMixerStatusIgnoringFastTracks = mixerStatus;
6136 if (fastTracks > 0) {
6137 mixerStatus = MIXER_TRACKS_READY;
6138 }
6139 return mixerStatus;
6140}
6141
Eric Laurentad7dd962016-09-22 12:38:37 -07006142// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006143uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006144{
6145 uint32_t trackCount = 0;
6146 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006147 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006148 trackCount++;
6149 }
6150 }
6151 return trackCount;
6152}
6153
Andy Hung71742ab2023-07-07 13:47:37 -07006154bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006155{
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006156 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6157 // could falsely detect that the frame position has stalled due to underrun because we haven't
6158 // given the Audio HAL enough time to update.
6159 const nsecs_t nowNs = systemTime();
6160 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6161 return mLatchedValue;
6162 }
6163 mPreviousNs = nowNs;
6164 mLatchedValue = false;
6165 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006166 uint64_t position = 0;
6167 struct timespec unused;
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006168 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006169 if (ret == NO_ERROR) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006170 if (position != mPreviousPosition) {
6171 mPreviousPosition = position;
6172 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006173 }
6174 }
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006175 return mLatchedValue;
6176}
6177
Andy Hung71742ab2023-07-07 13:47:37 -07006178void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006179{
6180 mLatchedValue = true;
6181 mPreviousPosition = 0;
6182 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006183}
6184
Andy Hung1bc088a2018-02-09 15:57:31 -08006185// isTrackAllowed_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006186bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006187 audio_channel_mask_t channelMask, audio_format_t format,
6188 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006189{
Andy Hung1bc088a2018-02-09 15:57:31 -08006190 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6191 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006192 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006193 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006194 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006195 ALOGW("%s: invalid format: %#x", __func__, format);
6196 return false;
6197 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006198 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006199 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6200 return false;
6201 }
6202 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006203}
6204
Eric Laurent10351942014-05-08 18:49:52 -07006205// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006206bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006207 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006208{
Eric Laurent81784c32012-11-19 14:55:58 -08006209 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006210 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006211
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006212 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006213
Eric Laurent10351942014-05-08 18:49:52 -07006214 AudioParameter param = AudioParameter(keyValuePair);
6215 int value;
6216 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6217 reconfig = true;
6218 }
6219 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung71742ab2023-07-07 13:47:37 -07006220 if (!AudioFlinger::isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006221 status = BAD_VALUE;
6222 } else {
6223 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006224 reconfig = true;
6225 }
Eric Laurent10351942014-05-08 18:49:52 -07006226 }
6227 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung71742ab2023-07-07 13:47:37 -07006228 if (!AudioFlinger::isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006229 status = BAD_VALUE;
6230 } else {
6231 // no need to save value, since it's constant
6232 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006233 }
Eric Laurent10351942014-05-08 18:49:52 -07006234 }
6235 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6236 // do not accept frame count changes if tracks are open as the track buffer
6237 // size depends on frame count and correct behavior would not be guaranteed
6238 // if frame count is changed after track creation
6239 if (!mTracks.isEmpty()) {
6240 status = INVALID_OPERATION;
6241 } else {
6242 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006243 }
Eric Laurent10351942014-05-08 18:49:52 -07006244 }
6245 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006246 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006247 }
Eric Laurent81784c32012-11-19 14:55:58 -08006248
Eric Laurent10351942014-05-08 18:49:52 -07006249 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006250 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006251 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungb72a5502023-03-27 15:53:06 -07006252 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6253 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006254 mOutput->standby();
Andy Hungb72a5502023-03-27 15:53:06 -07006255 mThreadMetrics.logEndInterval();
6256 mThreadSnapshot.onEnd();
Andy Hungdda7aed2023-03-27 15:53:06 -07006257 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006258 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006259 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006260 }
Eric Laurent10351942014-05-08 18:49:52 -07006261 if (status == NO_ERROR && reconfig) {
6262 readOutputParameters_l();
6263 delete mAudioMixer;
6264 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006265 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006266 const int trackId = track->id();
Andy Hung71ba4b32022-10-06 12:09:49 -07006267 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006268 trackId,
Andy Hung3ff4b552023-06-26 19:20:57 -07006269 track->channelMask(),
6270 track->format(),
6271 track->sessionId());
Andy Hung71ba4b32022-10-06 12:09:49 -07006272 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006273 "%s(): AudioMixer cannot create track(%d)"
6274 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006275 __func__,
Andy Hung3ff4b552023-06-26 19:20:57 -07006276 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006277 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006278 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006279 }
Eric Laurent81784c32012-11-19 14:55:58 -08006280 }
6281
Dean Wheatley68918102021-03-19 22:09:19 +11006282 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006283}
6284
6285
Andy Hung71742ab2023-07-07 13:47:37 -07006286void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006287{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006288 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006289 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006290 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006291 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006292 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6293 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6294 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006295 if (hasFastMixer()) {
6296 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6297
6298 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6299 // while we are dumping it. It may be inconsistent, but it won't mutate!
6300 // This is a large object so we place it on the heap.
6301 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006302 const std::unique_ptr<FastMixerDumpState> copy =
6303 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006304 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006305
6306#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006307 // Similar for state queue
6308 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6309 observerCopy.dump(fd);
6310 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6311 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006312#endif
6313
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006314#ifdef AUDIO_WATCHDOG
6315 if (mAudioWatchdog != 0) {
6316 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6317 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6318 wdCopy.dump(fd);
6319 }
6320#endif
6321
6322 } else {
6323 dprintf(fd, " No FastMixer\n");
6324 }
Eric Laurent90cea102023-05-15 15:08:27 +02006325
6326 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6327 mBluetoothLatencyModesEnabled ? "" : "not ");
6328 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6329 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6330 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006331}
6332
Andy Hung71742ab2023-07-07 13:47:37 -07006333uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006334{
6335 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6336}
6337
Andy Hung71742ab2023-07-07 13:47:37 -07006338uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006339{
6340 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6341}
6342
Andy Hung71742ab2023-07-07 13:47:37 -07006343void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006344{
6345 PlaybackThread::cacheParameters_l();
6346
6347 // FIXME: Relaxed timing because of a certain device that can't meet latency
6348 // Should be reduced to 2x after the vendor fixes the driver issue
6349 // increase threshold again due to low power audio mode. The way this warning
6350 // threshold is calculated and its usefulness should be reconsidered anyway.
6351 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6352}
6353
Andy Hung71742ab2023-07-07 13:47:37 -07006354void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung2cbc2722023-07-17 17:05:00 -07006355 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006356}
6357
Andy Hung71742ab2023-07-07 13:47:37 -07006358void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006359 // Only handle latency mode if:
6360 // - mBluetoothLatencyModesEnabled is true
6361 // - the HAL supports latency modes
6362 // - the selected device is Bluetooth LE or A2DP
6363 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6364 return;
6365 }
6366 if (mOutDeviceTypeAddrs.size() != 1
6367 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6368 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6369 return;
6370 }
6371
6372 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6373 if (mSupportedLatencyModes.size() == 1) {
6374 // If the HAL only support one latency mode currently, confirm the choice
6375 latencyMode = mSupportedLatencyModes[0];
6376 } else if (mSupportedLatencyModes.size() > 1) {
6377 // Request low latency if:
6378 // - At least one active track is either:
6379 // - a fast track with gaming usage or
6380 // - a track with acessibility usage
6381 for (const auto& track : mActiveTracks) {
6382 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6383 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6384 latencyMode = AUDIO_LATENCY_MODE_LOW;
6385 break;
6386 }
6387 }
6388 }
6389
6390 if (latencyMode != mSetLatencyMode) {
6391 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6392 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6393 __func__, mId, toString(latencyMode).c_str(), status);
6394 if (status == NO_ERROR) {
6395 mSetLatencyMode = latencyMode;
6396 }
6397 }
6398}
6399
Andy Hung71742ab2023-07-07 13:47:37 -07006400void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006401
6402 if (mOutput == nullptr || mOutput->stream == nullptr) {
6403 return;
6404 }
6405 std::vector<audio_latency_mode_t> latencyModes;
6406 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6407 if (status != NO_ERROR) {
6408 latencyModes.clear();
6409 }
6410 if (latencyModes != mSupportedLatencyModes) {
6411 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6412 __func__, mId, status, toString(latencyModes).c_str());
6413 mSupportedLatencyModes.swap(latencyModes);
6414 sendHalLatencyModesChangedEvent_l();
6415 }
6416}
6417
Andy Hung71742ab2023-07-07 13:47:37 -07006418status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006419 std::vector<audio_latency_mode_t>* modes) {
6420 if (modes == nullptr) {
6421 return BAD_VALUE;
6422 }
6423 Mutex::Autolock _l(mLock);
6424 *modes = mSupportedLatencyModes;
6425 return NO_ERROR;
6426}
6427
Andy Hung71742ab2023-07-07 13:47:37 -07006428void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006429 std::vector<audio_latency_mode_t> modes) {
6430 Mutex::Autolock _l(mLock);
6431 if (modes != mSupportedLatencyModes) {
6432 ALOGD("%s: thread(%d) supported latency modes: %s",
6433 __func__, mId, toString(modes).c_str());
6434 mSupportedLatencyModes.swap(modes);
6435 sendHalLatencyModesChangedEvent_l();
6436 }
6437}
6438
Andy Hung71742ab2023-07-07 13:47:37 -07006439status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006440 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6441 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6442 return INVALID_OPERATION;
6443 }
6444 mBluetoothLatencyModesEnabled.store(enabled);
6445 return NO_ERROR;
6446}
6447
Eric Laurent81784c32012-11-19 14:55:58 -08006448// ----------------------------------------------------------------------------
6449
Andy Hung71742ab2023-07-07 13:47:37 -07006450/* static */
6451sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07006452 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07006453 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6454 const audio_offload_info_t& offloadInfo) {
6455 return sp<DirectOutputThread>::make(
Andy Hung2cbc2722023-07-17 17:05:00 -07006456 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung71742ab2023-07-07 13:47:37 -07006457}
6458
Andy Hung2cbc2722023-07-17 17:05:00 -07006459DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fenn56576722022-10-05 13:42:36 -07006460 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6461 const audio_offload_info_t& offloadInfo)
Andy Hung2cbc2722023-07-17 17:05:00 -07006462 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fenn56576722022-10-05 13:42:36 -07006463 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006464{
Andy Hung2cbc2722023-07-17 17:05:00 -07006465 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006466}
6467
Andy Hung71742ab2023-07-07 13:47:37 -07006468DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006469{
6470}
6471
Andy Hung71742ab2023-07-07 13:47:37 -07006472void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006473{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006474 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006475 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6476 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6477}
6478
Andy Hung71742ab2023-07-07 13:47:37 -07006479void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006480{
6481 Mutex::Autolock _l(mLock);
6482 if (mMasterBalance != balance) {
6483 mMasterBalance.store(balance);
6484 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6485 broadcast_l();
6486 }
6487}
6488
Andy Hung71742ab2023-07-07 13:47:37 -07006489void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006490{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006491 float left, right;
6492
Andy Hung333ab962019-05-28 20:23:35 -07006493 // Ensure volumeshaper state always advances even when muted.
Andy Hung3ff4b552023-06-26 19:20:57 -07006494 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hungee86cee2022-12-13 19:19:53 -08006495
Andy Hungee86cee2022-12-13 19:19:53 -08006496 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6497 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6498
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006499 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6500 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hungee86cee2022-12-13 19:19:53 -08006501
6502 const int64_t volumeShaperFrames =
6503 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6504 const auto [shaperVolume, shaperActive] =
6505 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006506 mVolumeShaperActive = shaperActive;
6507
Vlad Popae2f5aef2022-07-25 16:00:20 +02006508 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6509 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6510 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6511
6512 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6513
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006514 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006515 left = right = 0;
6516 } else {
6517 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006518 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006519
Glenn Kastenc56f3422014-03-21 17:53:17 -07006520 if (left > GAIN_FLOAT_UNITY) {
6521 left = GAIN_FLOAT_UNITY;
6522 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006523 if (right > GAIN_FLOAT_UNITY) {
6524 right = GAIN_FLOAT_UNITY;
6525 }
zhangjincheng73e73872023-01-16 17:17:38 +08006526 left *= v;
6527 right *= v;
Andy Hung2cbc2722023-07-17 17:05:00 -07006528 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng73e73872023-01-16 17:17:38 +08006529 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6530 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6531 right *= mMasterBalanceRight;
6532 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006533 }
6534
Andy Hung2cbc2722023-07-17 17:05:00 -07006535 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006536 /*muteState=*/{mMasterMute,
6537 mStreamTypes[track->streamType()].volume == 0.f,
6538 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006539 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006540 clientVolumeMute,
6541 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006542
Eric Laurentbfb1b832013-01-07 09:53:42 -08006543 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006544 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006545 if (left != mLeftVolFloat || right != mRightVolFloat) {
6546 mLeftVolFloat = left;
6547 mRightVolFloat = right;
6548
Eric Laurentbfb1b832013-01-07 09:53:42 -08006549 // Delegate volume control to effect in track effect chain if needed
6550 // only one effect chain can be present on DirectOutputThread, so if
6551 // there is one, the track is connected to it
6552 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006553 // if effect chain exists, volume is handled by it.
6554 // Convert volumes from float to 8.24
6555 uint32_t vl = (uint32_t)(left * (1 << 24));
6556 uint32_t vr = (uint32_t)(right * (1 << 24));
6557 // Direct/Offload effect chains set output volume in setVolume_l().
6558 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6559 } else {
6560 // otherwise we directly set the volume.
6561 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006562 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006563 }
6564 }
6565}
6566
Andy Hung71742ab2023-07-07 13:47:37 -07006567void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006568{
Andy Hung3ff4b552023-06-26 19:20:57 -07006569 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6570 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006571
Eric Laurent0f0631e2015-07-06 18:01:25 -07006572 if (previousTrack != 0 && latestTrack != 0) {
6573 if (mType == DIRECT) {
6574 if (previousTrack.get() != latestTrack.get()) {
6575 mFlushPending = true;
6576 }
6577 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006578 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6579 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006580 mFlushPending = true;
6581 }
6582 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006583 } else if (previousTrack == 0) {
6584 // there could be an old track added back during track transition for direct
6585 // output, so always issues flush to flush data of the previous track if it
6586 // was already destroyed with HAL paused, then flush can resume the playback
6587 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006588 }
6589 PlaybackThread::onAddNewTrack_l();
6590}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006591
Andy Hung71742ab2023-07-07 13:47:37 -07006592PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07006593 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006594)
6595{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006596 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006597 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006598 bool doHwPause = false;
6599 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006600
6601 // find out which tracks need to be processed
Andy Hung3ff4b552023-06-26 19:20:57 -07006602 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006603 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006604 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006605 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006606 continue;
6607 }
6608
Andy Hung3ff4b552023-06-26 19:20:57 -07006609 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006610#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006611 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006612#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006613 // Only consider last track started for volume and mixer state control.
6614 // In theory an older track could underrun and restart after the new one starts
6615 // but as we only care about the transition phase between two tracks on a
6616 // direct output, it is not a problem to ignore the underrun case.
Andy Hung3ff4b552023-06-26 19:20:57 -07006617 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006618 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006619
Kuowei Li23666472021-01-20 10:23:25 +08006620 if (track->isPausePending()) {
6621 track->pauseAck();
6622 // It is possible a track might have been flushed or stopped.
6623 // Other operations such as flush pending might occur on the next prepare.
6624 if (track->isPausing()) {
6625 track->setPaused();
6626 }
6627 // Always perform pause, as an immediate flush will change
6628 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006629 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006630 doHwPause = true;
6631 mHwPaused = true;
6632 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006633 } else if (track->isFlushPending()) {
6634 track->flushAck();
6635 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006636 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006637 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006638 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006639 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006640 if (last) {
6641 mLeftVolFloat = mRightVolFloat = -1.0;
6642 if (mHwPaused) {
6643 doHwResume = true;
6644 mHwPaused = false;
6645 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006646 }
6647 }
6648
Eric Laurent81784c32012-11-19 14:55:58 -08006649 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006650 // for all its buffers to be filled before processing it.
6651 // Allow draining the buffer in case the client
6652 // app does not call stop() and relies on underrun to stop:
Andy Hung3ff4b552023-06-26 19:20:57 -07006653 // hence the test on (track->retryCount() > 1).
6654 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006655 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6656 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006657 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006658
6659 // target retry count that we will use is based on the time we wait for retries.
6660 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6661 // the retry threshold is when we accept any size for PCM data. This is slightly
6662 // smaller than the retry count so we can push small bits of data without a glitch.
6663 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006664 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006665 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung3ff4b552023-06-26 19:20:57 -07006666 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006667 minFrames = mNormalFrameCount;
6668 } else {
6669 minFrames = 1;
6670 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006671
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006672 const size_t framesReady = track->framesReady();
6673 const int trackId = track->id();
6674 if (ATRACE_ENABLED()) {
6675 std::string traceName("nRdy");
6676 traceName += std::to_string(trackId);
6677 ATRACE_INT(traceName.c_str(), framesReady);
6678 }
6679 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006680 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006681 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006682 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006683
Andy Hung3ff4b552023-06-26 19:20:57 -07006684 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6685 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006686 if (last) {
6687 // make sure processVolume_l() will apply new volume even if 0
6688 mLeftVolFloat = mRightVolFloat = -1.0;
6689 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006690 if (!mHwSupportsPause) {
6691 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006692 }
6693 }
6694
6695 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006696 processVolume_l(track, last);
6697 if (last) {
Andy Hung3ff4b552023-06-26 19:20:57 -07006698 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006699 if (previousTrack != 0) {
6700 if (track != previousTrack.get()) {
6701 // Flush any data still being written from last track
6702 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006703 // Invalidate previous track to force a seek when resuming.
6704 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006705 }
6706 }
6707 mPreviousTrack = track;
6708
Eric Laurentd595b7c2013-04-03 17:27:56 -07006709 // reset retry count
Andy Hung3ff4b552023-06-26 19:20:57 -07006710 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006711 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006712 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006713 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006714 doHwResume = true;
6715 mHwPaused = false;
6716 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006717 }
Eric Laurent81784c32012-11-19 14:55:58 -08006718 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006719 // clear effect chain input buffer if the last active track started underruns
6720 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006721 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006722 mEffectChains[0]->clearInputBuffer();
6723 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006724 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07006725 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006726 if (last && mHwPaused) {
6727 doHwResume = true;
6728 mHwPaused = false;
6729 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006730 }
6731 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6732 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006733 // We have consumed all the buffers of this track.
6734 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006735 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006736 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006737 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006738 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006739 if (presComplete) {
6740 mOutput->presentationComplete();
6741 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006742 if (track->isStopping_2()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07006743 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006744 }
Eric Laurent81784c32012-11-19 14:55:58 -08006745 if (track->isStopped()) {
6746 track->reset();
6747 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006748 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006749 }
6750 } else {
6751 // No buffers for this track. Give it a few chances to
6752 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006753 // Only consider last track started for mixer state control
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006754 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07006755 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung3ff4b552023-06-26 19:20:57 -07006756 && --(track->retryCount()) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006757 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung3ff4b552023-06-26 19:20:57 -07006758 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006759 } else {
6760 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6761 tracksToRemove->add(track);
6762 // indicate to client process that the track was disabled because of
6763 // underrun; it will then automatically call start() when data is available
6764 track->disable();
6765 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6766 // unlike mixerthread, HAL can be paused for direct output
6767 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6768 "minFrames = %u, mFormat = %#x",
6769 framesReady, minFrames, mFormat);
6770 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6771 doHwPause = true;
6772 mHwPaused = true;
6773 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006774 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006775 } else if (last) {
6776 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006777 }
6778 }
6779 }
6780 }
6781
Eric Laurentd1f69b02014-12-15 14:33:13 -08006782 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006783 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006784 for (size_t i = 0; i < mTracks.size(); i++) {
6785 if (mTracks[i]->isFlushPending()) {
6786 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006787 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006788 }
6789 }
6790 }
6791
6792 // make sure the pause/flush/resume sequence is executed in the right order.
6793 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6794 // before flush and then resume HW. This can happen in case of pause/flush/resume
6795 // if resume is received before pause is executed.
6796 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006797 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006798 status_t result = mOutput->stream->pause();
6799 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006800 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006801 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006802 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006803 flushHw_l();
6804 }
6805 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006806 status_t result = mOutput->stream->resume();
6807 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006808 }
Eric Laurent81784c32012-11-19 14:55:58 -08006809 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006810 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006811
6812 return mixerStatus;
6813}
6814
Andy Hung71742ab2023-07-07 13:47:37 -07006815void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006816{
Eric Laurent81784c32012-11-19 14:55:58 -08006817 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006818 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006819 // output audio to hardware
6820 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006821 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006822 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006823 status_t status = mActiveTrack->getNextBuffer(&buffer);
6824 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006825 // no need to pad with 0 for compressed audio
6826 if (audio_has_proportional_frames(mFormat)) {
6827 memset(curBuf, 0, frameCount * mFrameSize);
6828 }
Eric Laurent81784c32012-11-19 14:55:58 -08006829 break;
6830 }
6831 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6832 frameCount -= buffer.frameCount;
6833 curBuf += buffer.frameCount * mFrameSize;
6834 mActiveTrack->releaseBuffer(&buffer);
6835 }
Andy Hung2098f272014-02-27 14:00:06 -08006836 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006837 mSleepTimeUs = 0;
6838 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006839 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006840}
6841
Andy Hung71742ab2023-07-07 13:47:37 -07006842void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006843{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006844 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006845 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006846 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006847 return;
6848 }
Andy Hung85ba3332021-04-27 17:40:26 -07006849 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6850 mSleepTimeUs = mActiveSleepTimeUs;
6851 } else {
6852 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006853 }
Andy Hung85ba3332021-04-27 17:40:26 -07006854 // Note: In S or later, we do not write zeroes for
6855 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006856}
6857
Andy Hung71742ab2023-07-07 13:47:37 -07006858void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006859{
6860 {
6861 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006862 for (size_t i = 0; i < mTracks.size(); i++) {
6863 if (mTracks[i]->isFlushPending()) {
6864 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006865 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006866 }
6867 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006868 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006869 flushHw_l();
6870 }
6871 }
6872 PlaybackThread::threadLoop_exit();
6873}
6874
6875// must be called with thread mutex locked
Andy Hung71742ab2023-07-07 13:47:37 -07006876bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006877{
6878 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006879 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006880
6881 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6882 // after a timeout and we will enter standby then.
6883 if (mTracks.size() > 0) {
6884 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006885 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung3ff4b552023-06-26 19:20:57 -07006886 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006887 }
6888
Eric Laurent5cff4032015-05-26 13:49:58 -07006889 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006890}
6891
Eric Laurent10351942014-05-08 18:49:52 -07006892// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006893bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006894 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006895{
6896 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006897 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006898
Eric Laurent10351942014-05-08 18:49:52 -07006899 AudioParameter param = AudioParameter(keyValuePair);
6900 int value;
6901 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006902 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006903 }
Eric Laurent10351942014-05-08 18:49:52 -07006904 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6905 // do not accept frame count changes if tracks are open as the track buffer
6906 // size depends on frame count and correct behavior would not be garantied
6907 // if frame count is changed after track creation
6908 if (!mTracks.isEmpty()) {
6909 status = INVALID_OPERATION;
6910 } else {
6911 reconfig = true;
6912 }
6913 }
6914 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006915 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006916 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006917 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006918 if (!mStandby) {
6919 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006920 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02006921 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07006922 }
Eric Laurent10351942014-05-08 18:49:52 -07006923 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006924 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006925 }
6926 if (status == NO_ERROR && reconfig) {
6927 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006928 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006929 }
6930 }
6931
Dean Wheatley68918102021-03-19 22:09:19 +11006932 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006933}
6934
Andy Hung71742ab2023-07-07 13:47:37 -07006935uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006936{
6937 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006938 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006939 time = PlaybackThread::activeSleepTimeUs();
6940 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006941 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006942 }
6943 return time;
6944}
6945
Andy Hung71742ab2023-07-07 13:47:37 -07006946uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006947{
6948 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006949 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006950 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6951 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006952 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006953 }
6954 return time;
6955}
6956
Andy Hung71742ab2023-07-07 13:47:37 -07006957uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006958{
6959 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006960 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006961 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6962 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006963 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006964 }
6965 return time;
6966}
6967
Andy Hung71742ab2023-07-07 13:47:37 -07006968void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006969{
6970 PlaybackThread::cacheParameters_l();
6971
6972 // use shorter standby delay as on normal output to release
6973 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006974 // no delay on outputs with HW A/V sync
6975 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006976 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006977 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006978 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006979 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006980 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006981 }
Eric Laurent81784c32012-11-19 14:55:58 -08006982}
6983
Andy Hung71742ab2023-07-07 13:47:37 -07006984void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07006985{
ziyangch8f194f12021-12-01 13:48:04 -08006986 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08006987 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006988 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006989 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006990 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006991 mTimestamp.clear();
Andy Hungee86cee2022-12-13 19:19:53 -08006992 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07006993}
6994
Andy Hung71742ab2023-07-07 13:47:37 -07006995int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08006996 // If a VolumeShaper is active, we must wake up periodically to update volume.
6997 const int64_t NS_PER_MS = 1000000;
6998 return mVolumeShaperActive ?
6999 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7000}
7001
Eric Laurent81784c32012-11-19 14:55:58 -08007002// ----------------------------------------------------------------------------
7003
Andy Hung71742ab2023-07-07 13:47:37 -07007004AsyncCallbackThread::AsyncCallbackThread(
7005 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007006 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007007 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007008 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007009 mDrainSequence(0),
7010 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007011{
7012}
7013
Andy Hung71742ab2023-07-07 13:47:37 -07007014void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007015{
7016 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7017}
7018
Andy Hung71742ab2023-07-07 13:47:37 -07007019bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007020{
7021 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007022 uint32_t writeAckSequence;
7023 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007024 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007025
7026 {
7027 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007028 while (!((mWriteAckSequence & 1) ||
7029 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007030 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007031 exitPending())) {
7032 mWaitWorkCV.wait(mLock);
7033 }
7034
Eric Laurentbfb1b832013-01-07 09:53:42 -08007035 if (exitPending()) {
7036 break;
7037 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007038 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7039 mWriteAckSequence, mDrainSequence);
7040 writeAckSequence = mWriteAckSequence;
7041 mWriteAckSequence &= ~1;
7042 drainSequence = mDrainSequence;
7043 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007044 asyncError = mAsyncError;
7045 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007046 }
7047 {
Andy Hung71742ab2023-07-07 13:47:37 -07007048 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007049 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007050 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007051 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007052 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007053 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007054 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007055 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007056 if (asyncError) {
7057 playbackThread->onAsyncError();
7058 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007059 }
7060 }
7061 }
7062 return false;
7063}
7064
Andy Hung71742ab2023-07-07 13:47:37 -07007065void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007066{
7067 ALOGV("AsyncCallbackThread::exit");
7068 Mutex::Autolock _l(mLock);
7069 requestExit();
7070 mWaitWorkCV.broadcast();
7071}
7072
Andy Hung71742ab2023-07-07 13:47:37 -07007073void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007074{
7075 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007076 // bit 0 is cleared
7077 mWriteAckSequence = sequence << 1;
7078}
7079
Andy Hung71742ab2023-07-07 13:47:37 -07007080void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007081{
7082 Mutex::Autolock _l(mLock);
7083 // ignore unexpected callbacks
7084 if (mWriteAckSequence & 2) {
7085 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007086 mWaitWorkCV.signal();
7087 }
7088}
7089
Andy Hung71742ab2023-07-07 13:47:37 -07007090void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007091{
7092 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007093 // bit 0 is cleared
7094 mDrainSequence = sequence << 1;
7095}
7096
Andy Hung71742ab2023-07-07 13:47:37 -07007097void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007098{
7099 Mutex::Autolock _l(mLock);
7100 // ignore unexpected callbacks
7101 if (mDrainSequence & 2) {
7102 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007103 mWaitWorkCV.signal();
7104 }
7105}
7106
Andy Hung71742ab2023-07-07 13:47:37 -07007107void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007108{
7109 Mutex::Autolock _l(mLock);
7110 mAsyncError = true;
7111 mWaitWorkCV.signal();
7112}
7113
Eric Laurentbfb1b832013-01-07 09:53:42 -08007114
7115// ----------------------------------------------------------------------------
Andy Hung71742ab2023-07-07 13:47:37 -07007116
7117/* static */
7118sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07007119 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07007120 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7121 const audio_offload_info_t& offloadInfo) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007122 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung71742ab2023-07-07 13:47:37 -07007123}
7124
Andy Hung2cbc2722023-07-17 17:05:00 -07007125OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fenn56576722022-10-05 13:42:36 -07007126 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7127 const audio_offload_info_t& offloadInfo)
Andy Hung2cbc2722023-07-17 17:05:00 -07007128 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007129 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007130{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007131 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007132 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007133 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007134}
7135
Andy Hung71742ab2023-07-07 13:47:37 -07007136void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007137{
7138 if (mFlushPending || mHwPaused) {
7139 // If a flush is pending or track was paused, just discard buffered data
7140 flushHw_l();
7141 } else {
7142 mMixerStatus = MIXER_DRAIN_ALL;
7143 threadLoop_drain();
7144 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007145 if (mUseAsyncWrite) {
7146 ALOG_ASSERT(mCallbackThread != 0);
7147 mCallbackThread->exit();
7148 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007149 PlaybackThread::threadLoop_exit();
7150}
7151
Andy Hung71742ab2023-07-07 13:47:37 -07007152PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07007153 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007154)
7155{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007156 size_t count = mActiveTracks.size();
7157
7158 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007159 bool doHwPause = false;
7160 bool doHwResume = false;
7161
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007162 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007163
Eric Laurentbfb1b832013-01-07 09:53:42 -08007164 // find out which tracks need to be processed
Andy Hung3ff4b552023-06-26 19:20:57 -07007165 for (const sp<IAfTrack>& t : mActiveTracks) {
7166 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007167#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007168 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007169#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007170 // Only consider last track started for volume and mixer state control.
7171 // In theory an older track could underrun and restart after the new one starts
7172 // but as we only care about the transition phase between two tracks on a
7173 // direct output, it is not a problem to ignore the underrun case.
Andy Hung3ff4b552023-06-26 19:20:57 -07007174 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007175 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007176
Haynes Mathew George7844f672014-01-15 12:32:55 -08007177 if (track->isInvalid()) {
7178 ALOGW("An invalidated track shouldn't be in active list");
7179 tracksToRemove->add(track);
7180 continue;
7181 }
7182
Andy Hung3ff4b552023-06-26 19:20:57 -07007183 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007184 ALOGW("An idle track shouldn't be in active list");
7185 continue;
7186 }
7187
Kuowei Li23666472021-01-20 10:23:25 +08007188 if (track->isPausePending()) {
7189 track->pauseAck();
7190 // It is possible a track might have been flushed or stopped.
7191 // Other operations such as flush pending might occur on the next prepare.
7192 if (track->isPausing()) {
7193 track->setPaused();
7194 }
7195 // Always perform pause if last, as an immediate flush will change
7196 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007197 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007198 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007199 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007200 mHwPaused = true;
7201 }
7202 // If we were part way through writing the mixbuffer to
7203 // the HAL we must save this until we resume
7204 // BUG - this will be wrong if a different track is made active,
7205 // in that case we want to discard the pending data in the
7206 // mixbuffer and tell the client to present it again when the
7207 // track is resumed
7208 mPausedWriteLength = mCurrentWriteLength;
7209 mPausedBytesRemaining = mBytesRemaining;
7210 mBytesRemaining = 0; // stop writing
7211 }
7212 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007213 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007214 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007215 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007216 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07007217 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007218 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007219 track->flushAck();
7220 if (last) {
7221 mFlushPending = true;
7222 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007223 } else if (track->isResumePending()){
7224 track->resumeAck();
7225 if (last) {
7226 if (mPausedBytesRemaining) {
7227 // Need to continue write that was interrupted
7228 mCurrentWriteLength = mPausedWriteLength;
7229 mBytesRemaining = mPausedBytesRemaining;
7230 mPausedBytesRemaining = 0;
7231 }
7232 if (mHwPaused) {
7233 doHwResume = true;
7234 mHwPaused = false;
7235 // threadLoop_mix() will handle the case that we need to
7236 // resume an interrupted write
7237 }
7238 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007239 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007240
Eric Laurent3df841a2016-07-15 15:15:40 -07007241 mLeftVolFloat = mRightVolFloat = -1.0;
7242
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007243 // Do not handle new data in this iteration even if track->framesReady()
7244 mixerStatus = MIXER_TRACKS_ENABLED;
7245 }
7246 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007247 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007248 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung3ff4b552023-06-26 19:20:57 -07007249 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7250 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007251 if (last) {
7252 // make sure processVolume_l() will apply new volume even if 0
7253 mLeftVolFloat = mRightVolFloat = -1.0;
7254 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007255 }
7256
7257 if (last) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007258 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007259 if (previousTrack != 0) {
7260 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007261 // Flush any data still being written from last track
7262 mBytesRemaining = 0;
7263 if (mPausedBytesRemaining) {
7264 // Last track was paused so we also need to flush saved
7265 // mixbuffer state and invalidate track so that it will
7266 // re-submit that unwritten data when it is next resumed
7267 mPausedBytesRemaining = 0;
7268 // Invalidate is a bit drastic - would be more efficient
7269 // to have a flag to tell client that some of the
7270 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007271 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007272 }
7273 // flush data already sent to the DSP if changing audio session as audio
7274 // comes from a different source. Also invalidate previous track to force a
7275 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007276 if (previousTrack->sessionId() != track->sessionId()) {
7277 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007278 }
7279 }
7280 }
7281 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007282 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007283 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007284 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007285 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07007286 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007287 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007288 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007289 mixerStatus = MIXER_TRACKS_READY;
7290 }
7291 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007292 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007293 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007294 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007295 // Hardware buffer can hold a large amount of audio so we must
7296 // wait for all current track's data to drain before we say
7297 // that the track is stopped.
7298 if (mBytesRemaining == 0) {
7299 // Only start draining when all data in mixbuffer
7300 // has been written
7301 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung3ff4b552023-06-26 19:20:57 -07007302 track->setState(IAfTrackBase::STOPPING_2);
7303 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007304 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7305 if (last && !mStandby) {
7306 // do not modify drain sequence if we are already draining. This happens
7307 // when resuming from pause after drain.
7308 if ((mDrainSequence & 1) == 0) {
7309 mSleepTimeUs = 0;
7310 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7311 mixerStatus = MIXER_DRAIN_TRACK;
7312 mDrainSequence += 2;
7313 }
7314 if (mHwPaused) {
7315 // It is possible to move from PAUSED to STOPPING_1 without
7316 // a resume so we must ensure hardware is running
7317 doHwResume = true;
7318 mHwPaused = false;
7319 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007320 }
7321 }
Eric Laurente93cc032016-05-05 10:15:10 -07007322 } else if (last) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007323 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007324 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007325 }
7326 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007327 // Drain has completed or we are in standby, signal presentation complete
7328 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007329 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007330 mOutput->presentationComplete();
7331 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007332 track->reset();
7333 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007334 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007335 if (!mUseAsyncWrite) {
7336 // If we don't get explicit drain notification we must
7337 // register discontinuity regardless of whether this is
7338 // the previous (!last) or the upcoming (last) track
7339 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007340 mTimestampVerifier.discontinuity(
7341 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007342 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007343 }
7344 } else {
7345 // No buffers for this track. Give it a few chances to
7346 // fill a buffer, then remove it from active list.
Brian Lindahl9e661ad2022-07-27 18:01:07 +02007347 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07007348 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung3ff4b552023-06-26 19:20:57 -07007349 && --(track->retryCount()) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02007350 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung3ff4b552023-06-26 19:20:57 -07007351 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007352 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007353 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7354 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007355 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007356 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007357 // it will then automatically call start() when data is available
7358 track->disable();
7359 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007360 } else if (last){
7361 mixerStatus = MIXER_TRACKS_ENABLED;
7362 }
7363 }
7364 }
7365 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007366 if (track->isReady()) { // check ready to prevent premature start.
7367 processVolume_l(track, last);
7368 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007369 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007370
Eric Laurentea0fade2013-10-04 16:23:48 -07007371 // make sure the pause/flush/resume sequence is executed in the right order.
7372 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7373 // before flush and then resume HW. This can happen in case of pause/flush/resume
7374 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007375 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007376 status_t result = mOutput->stream->pause();
7377 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007378 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007379 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007380 if (mFlushPending) {
7381 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007382 }
Eric Laurentfd477972013-10-25 18:10:40 -07007383 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007384 status_t result = mOutput->stream->resume();
7385 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007386 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007387
Eric Laurentbfb1b832013-01-07 09:53:42 -08007388 // remove all the tracks that need to be...
7389 removeTracks_l(*tracksToRemove);
7390
7391 return mixerStatus;
7392}
7393
Eric Laurentbfb1b832013-01-07 09:53:42 -08007394// must be called with thread mutex locked
Andy Hung71742ab2023-07-07 13:47:37 -07007395bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007396{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007397 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7398 mWriteAckSequence, mDrainSequence);
7399 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007400 return true;
7401 }
7402 return false;
7403}
7404
Andy Hung71742ab2023-07-07 13:47:37 -07007405bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007406{
7407 Mutex::Autolock _l(mLock);
7408 return waitingAsyncCallback_l();
7409}
7410
Andy Hung71742ab2023-07-07 13:47:37 -07007411void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007412{
Eric Laurente659ef42014-09-29 13:06:46 -07007413 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007414 // Flush anything still waiting in the mixbuffer
7415 mCurrentWriteLength = 0;
7416 mBytesRemaining = 0;
7417 mPausedWriteLength = 0;
7418 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007419 // reset bytes written count to reflect that DSP buffers are empty after flush.
7420 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007421
Eric Laurentbfb1b832013-01-07 09:53:42 -08007422 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007423 // discard any pending drain or write ack by incrementing sequence
7424 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7425 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007426 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007427 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7428 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007429 }
7430}
7431
Andy Hung71742ab2023-07-07 13:47:37 -07007432void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007433{
7434 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007435 if (PlaybackThread::invalidateTracks_l(streamType)) {
7436 mFlushPending = true;
7437 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007438}
7439
Andy Hung71742ab2023-07-07 13:47:37 -07007440void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08007441 Mutex::Autolock _l(mLock);
7442 if (PlaybackThread::invalidateTracks_l(portIds)) {
7443 mFlushPending = true;
7444 }
7445}
7446
Eric Laurentbfb1b832013-01-07 09:53:42 -08007447// ----------------------------------------------------------------------------
7448
Andy Hung71742ab2023-07-07 13:47:37 -07007449/* static */
7450sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung2cbc2722023-07-17 17:05:00 -07007451 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07007452 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007453 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -07007454}
7455
Andy Hung2cbc2722023-07-17 17:05:00 -07007456DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung44f27182023-07-06 20:56:16 -07007457 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -07007458 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007459 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007460 mWaitTimeMs(UINT_MAX)
7461{
7462 addOutputTrack(mainThread);
7463}
7464
Andy Hung71742ab2023-07-07 13:47:37 -07007465DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007466{
7467 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7468 mOutputTracks[i]->destroy();
7469 }
7470}
7471
Andy Hung71742ab2023-07-07 13:47:37 -07007472void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007473{
7474 // mix buffers...
Andy Hung71ba4b32022-10-06 12:09:49 -07007475 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007476 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007477 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007478 if (mMixerBufferValid) {
7479 memset(mMixerBuffer, 0, mMixerBufferSize);
7480 } else {
7481 memset(mSinkBuffer, 0, mSinkBufferSize);
7482 }
Eric Laurent81784c32012-11-19 14:55:58 -08007483 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007484 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007485 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007486 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007487 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007488}
7489
Andy Hung71742ab2023-07-07 13:47:37 -07007490void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007491{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007492 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007493 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007494 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007495 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007496 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007497 }
7498 } else if (mBytesWritten != 0) {
7499 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7500 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007501 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007502 } else {
7503 // flush remaining overflow buffers in output tracks
7504 writeFrames = 0;
7505 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007506 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007507 }
7508}
7509
Andy Hung71742ab2023-07-07 13:47:37 -07007510ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007511{
7512 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007513 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7514
7515 // Consider the first OutputTrack for timestamp and frame counting.
7516
7517 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7518 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7519 // we always claim success.
7520 if (i == 0) {
7521 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7522 ALOGD_IF(correction != 0 && writeFrames != 0,
7523 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7524 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7525 mFramesWritten -= correction;
7526 }
7527
7528 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007529 }
Andy Hungcf10d742020-04-28 15:38:24 -07007530 if (mStandby) {
7531 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007532 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007533 mStandby = false;
7534 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007535 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007536}
7537
Andy Hung71742ab2023-07-07 13:47:37 -07007538void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007539{
7540 // DuplicatingThread implements standby by stopping all tracks
7541 for (size_t i = 0; i < outputTracks.size(); i++) {
7542 outputTracks[i]->stop();
7543 }
7544}
7545
Andy Hung71742ab2023-07-07 13:47:37 -07007546void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007547{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007548 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007549
7550 std::stringstream ss;
7551 const size_t numTracks = mOutputTracks.size();
7552 ss << " " << numTracks << " OutputTracks";
7553 if (numTracks > 0) {
7554 ss << ":";
7555 for (const auto &track : mOutputTracks) {
Andy Hung44f27182023-07-06 20:56:16 -07007556 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007557 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007558 if (thread.get() != nullptr) {
7559 ss << thread.get() << ", " << thread->id();
7560 } else {
7561 ss << "null";
7562 }
7563 ss << ")";
7564 }
7565 }
7566 ss << "\n";
7567 std::string result = ss.str();
7568 write(fd, result.c_str(), result.size());
7569}
7570
Andy Hung71742ab2023-07-07 13:47:37 -07007571void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007572{
7573 outputTracks = mOutputTracks;
7574}
7575
Andy Hung71742ab2023-07-07 13:47:37 -07007576void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007577{
7578 outputTracks.clear();
7579}
7580
Andy Hung71742ab2023-07-07 13:47:37 -07007581void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007582{
7583 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007584 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7585 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7586 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7587 const size_t frameCount =
7588 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7589 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7590 // from different OutputTracks and their associated MixerThreads (e.g. one may
7591 // nearly empty and the other may be dropping data).
7592
Svet Ganov33761132021-05-13 22:51:08 +00007593 // TODO b/182392769: use attribution source util, move to server edge
7594 AttributionSourceState attributionSource = AttributionSourceState();
7595 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007596 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007597 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007598 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007599 attributionSource.token = sp<BBinder>::make();
Andy Hung3ff4b552023-06-26 19:20:57 -07007600 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007601 this,
7602 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007603 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007604 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007605 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007606 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007607 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7608 if (status != NO_ERROR) {
7609 ALOGE("addOutputTrack() initCheck failed %d", status);
7610 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007611 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007612 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7613 mOutputTracks.add(outputTrack);
7614 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7615 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007616}
7617
Andy Hung71742ab2023-07-07 13:47:37 -07007618void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007619{
7620 Mutex::Autolock _l(mLock);
7621 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7622 if (mOutputTracks[i]->thread() == thread) {
7623 mOutputTracks[i]->destroy();
7624 mOutputTracks.removeAt(i);
7625 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007626 if (thread->getOutput() == mOutput) {
7627 mOutput = NULL;
7628 }
Eric Laurent81784c32012-11-19 14:55:58 -08007629 return;
7630 }
7631 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007632 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007633}
7634
7635// caller must hold mLock
Andy Hung71742ab2023-07-07 13:47:37 -07007636void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007637{
7638 mWaitTimeMs = UINT_MAX;
7639 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung44f27182023-07-06 20:56:16 -07007640 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007641 if (strong != 0) {
7642 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7643 if (waitTimeMs < mWaitTimeMs) {
7644 mWaitTimeMs = waitTimeMs;
7645 }
7646 }
7647 }
7648}
7649
Andy Hung71742ab2023-07-07 13:47:37 -07007650bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007651{
7652 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung44f27182023-07-06 20:56:16 -07007653 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007654 if (thread == 0) {
7655 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7656 outputTracks[i].get());
7657 return false;
7658 }
Andy Hung44f27182023-07-06 20:56:16 -07007659 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007660 // see note at standby() declaration
Andy Hung4989d312023-06-29 21:19:25 -07007661 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007662 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7663 thread.get());
7664 return false;
7665 }
7666 }
7667 return true;
7668}
7669
Andy Hung71742ab2023-07-07 13:47:37 -07007670void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007671 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007672{
Kevin Rocard12381092018-04-11 09:19:59 -07007673 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7674 outputTrack->setMetadatas(metadata.tracks);
7675 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007676}
7677
Andy Hung71742ab2023-07-07 13:47:37 -07007678uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007679{
7680 return (mWaitTimeMs * 1000) / 2;
7681}
7682
Andy Hung71742ab2023-07-07 13:47:37 -07007683void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007684{
7685 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7686 updateWaitTime_l();
7687
7688 MixerThread::cacheParameters_l();
7689}
7690
Eric Laurentb3f315a2021-07-13 15:09:05 +02007691// ----------------------------------------------------------------------------
7692
Andy Hung71742ab2023-07-07 13:47:37 -07007693/* static */
7694sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07007695 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07007696 AudioStreamOut* output,
7697 audio_io_handle_t id,
7698 bool systemReady,
7699 audio_config_base_t* mixerConfig) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007700 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hung71742ab2023-07-07 13:47:37 -07007701}
7702
Andy Hung2cbc2722023-07-17 17:05:00 -07007703SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007704 AudioStreamOut* output,
7705 audio_io_handle_t id,
7706 bool systemReady,
7707 audio_config_base_t *mixerConfig)
Andy Hung2cbc2722023-07-17 17:05:00 -07007708 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007709{
7710}
7711
Andy Hung71742ab2023-07-07 13:47:37 -07007712void SpatializerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01007713 MixerThread::onFirstRef();
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007714
Andy Hung41ccf7f2022-12-14 14:25:49 -08007715 const pid_t tid = getTid();
7716 if (tid == -1) {
7717 // Unusual: PlaybackThread::onFirstRef() should set the threadLoop running.
7718 ALOGW("%s: Cannot update Spatializer mixer thread priority, not running", __func__);
7719 } else {
7720 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
7721 if (priorityBoost > 0) {
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007722 stream()->setHalThreadPriority(priorityBoost);
7723 }
7724 }
Eric Laurent6f9534f2022-05-03 18:15:04 +02007725}
7726
Andy Hung71742ab2023-07-07 13:47:37 -07007727void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent6f9534f2022-05-03 18:15:04 +02007728 // if mSupportedLatencyModes is empty, the HAL stream does not support
7729 // latency mode control and we can exit.
7730 if (mSupportedLatencyModes.empty()) {
7731 return;
7732 }
7733 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7734 if (mSupportedLatencyModes.size() == 1) {
7735 // If the HAL only support one latency mode currently, confirm the choice
7736 latencyMode = mSupportedLatencyModes[0];
7737 } else if (mSupportedLatencyModes.size() > 1) {
7738 // Request low latency if:
7739 // - The low latency mode is requested by the spatializer controller
7740 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7741 // AND
7742 // - At least one active track is spatialized
7743 bool hasSpatializedActiveTrack = false;
7744 for (const auto& track : mActiveTracks) {
7745 if (track->isSpatialized()) {
7746 hasSpatializedActiveTrack = true;
7747 break;
7748 }
7749 }
7750 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7751 latencyMode = AUDIO_LATENCY_MODE_LOW;
7752 }
7753 }
7754
7755 if (latencyMode != mSetLatencyMode) {
7756 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007757 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7758 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent6f9534f2022-05-03 18:15:04 +02007759 if (status == NO_ERROR) {
7760 mSetLatencyMode = latencyMode;
7761 }
7762 }
7763}
7764
Andy Hung71742ab2023-07-07 13:47:37 -07007765status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent6f9534f2022-05-03 18:15:04 +02007766 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7767 return BAD_VALUE;
7768 }
7769 Mutex::Autolock _l(mLock);
7770 mRequestedLatencyMode = mode;
7771 return NO_ERROR;
7772}
7773
Andy Hung71742ab2023-07-07 13:47:37 -07007774void SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007775{
7776 bool hasVirtualizer = false;
7777 bool hasDownMixer = false;
Andy Hungbd72c542023-06-20 18:56:17 -07007778 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007779 {
7780 Mutex::Autolock _l(mLock);
Andy Hungbd72c542023-06-20 18:56:17 -07007781 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007782 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007783 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007784 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7785 }
7786
7787 finalDownMixer = mFinalDownMixer;
7788 mFinalDownMixer.clear();
7789 }
7790
7791 if (hasVirtualizer) {
7792 if (finalDownMixer != nullptr) {
7793 int32_t ret;
Andy Hungbd72c542023-06-20 18:56:17 -07007794 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007795 }
7796 finalDownMixer.clear();
7797 } else if (!hasDownMixer) {
7798 std::vector<effect_descriptor_t> descriptors;
Andy Hung2cbc2722023-07-17 17:05:00 -07007799 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007800 EFFECT_UIID_DOWNMIX, &descriptors);
7801 if (status != NO_ERROR) {
7802 return;
7803 }
7804 ALOG_ASSERT(!descriptors.empty(),
7805 "%s getDescriptors() returned no error but empty list", __func__);
7806
7807 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7808 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007809 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007810
7811 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7812 ALOGW("%s error creating downmixer %d", __func__, status);
7813 finalDownMixer.clear();
7814 } else {
7815 int32_t ret;
Andy Hungbd72c542023-06-20 18:56:17 -07007816 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007817 }
7818 }
7819
7820 {
7821 Mutex::Autolock _l(mLock);
7822 mFinalDownMixer = finalDownMixer;
7823 }
7824}
7825
Eric Laurent81784c32012-11-19 14:55:58 -08007826// ----------------------------------------------------------------------------
7827// Record
7828// ----------------------------------------------------------------------------
7829
Andy Hung2cbc2722023-07-17 17:05:00 -07007830sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung44f27182023-07-06 20:56:16 -07007831 AudioStreamIn* input,
7832 audio_io_handle_t id,
7833 bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007834 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung44f27182023-07-06 20:56:16 -07007835}
7836
Andy Hung2cbc2722023-07-17 17:05:00 -07007837RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007838 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007839 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007840 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007841 ) :
Andy Hung2cbc2722023-07-17 17:05:00 -07007842 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007843 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007844 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007845 mActiveTracks(&this->mLocalLog),
7846 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007847 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007848 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007849 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7850 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007851 // mFastCapture below
7852 , mFastCaptureFutex(0)
7853 // mInputSource
7854 // mPipeSink
7855 // mPipeSource
7856 , mPipeFramesP2(0)
7857 // mPipeMemory
7858 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007859 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007860 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007861{
Glenn Kastend7dca052015-03-05 16:05:54 -08007862 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung2cbc2722023-07-17 17:05:00 -07007863 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007864
George Burgess IVa8f90c12020-05-14 11:27:19 -07007865 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007866 mIsMsdDevice = strcmp(
7867 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7868 }
7869
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007870 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007871
Andy Hungc8fddf32018-08-08 18:32:37 -07007872 // TODO: We may also match on address as well as device type for
7873 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007874 // TODO: This property should be ensure that only contains one single device type.
7875 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7876 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007877 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7878 : AUDIO_DEVICE_NONE));
7879
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007880 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007881 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007882 size_t numCounterOffers = 0;
7883 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007884#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007885 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007886#else
7887 (void)
7888#endif
7889 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007890 ALOG_ASSERT(index == 0);
7891
7892 // initialize fast capture depending on configuration
7893 bool initFastCapture;
7894 switch (kUseFastCapture) {
7895 case FastCapture_Never:
7896 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007897 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007898 break;
7899 case FastCapture_Always:
7900 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007901 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007902 break;
7903 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007904 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
7905 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7906 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d "
7907 "mIsMsdDevice = %d", this, (long long)mFrameCount, mSampleRate,
7908 kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007909 break;
7910 // case FastCapture_Dynamic:
7911 }
7912
7913 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007914 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007915 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007916 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7917 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007918 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007919 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007920 const sp<MemoryDealer> roHeap(readOnlyHeap());
7921 sp<IMemory> pipeMemory;
7922 if ((roHeap == 0) ||
7923 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007924 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007925 ALOGE("not enough memory for pipe buffer size=%zu; "
7926 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7927 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7928 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007929 goto failed;
7930 }
7931 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7932 memset(pipeBuffer, 0, pipeSize);
7933 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07007934 const NBAIO_Format offersFast[1] = {format};
7935 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007936 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung71ba4b32022-10-06 12:09:49 -07007937 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007938 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007939 mPipeSink = pipe;
7940 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung71ba4b32022-10-06 12:09:49 -07007941 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007942 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung71ba4b32022-10-06 12:09:49 -07007943 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007944 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007945 mPipeSource = pipeReader;
7946 mPipeFramesP2 = pipeFramesP2;
7947 mPipeMemory = pipeMemory;
7948
7949 // create fast capture
7950 mFastCapture = new FastCapture();
7951 FastCaptureStateQueue *sq = mFastCapture->sq();
7952#ifdef STATE_QUEUE_DUMP
7953 // FIXME
7954#endif
7955 FastCaptureState *state = sq->begin();
7956 state->mCblk = NULL;
7957 state->mInputSource = mInputSource.get();
7958 state->mInputSourceGen++;
7959 state->mPipeSink = pipe;
7960 state->mPipeSinkGen++;
7961 state->mFrameCount = mFrameCount;
7962 state->mCommand = FastCaptureState::COLD_IDLE;
7963 // already done in constructor initialization list
7964 //mFastCaptureFutex = 0;
7965 state->mColdFutexAddr = &mFastCaptureFutex;
7966 state->mColdGen++;
7967 state->mDumpState = &mFastCaptureDumpState;
7968#ifdef TEE_SINK
7969 // FIXME
7970#endif
Andy Hung2cbc2722023-07-17 17:05:00 -07007971 mFastCaptureNBLogWriter =
7972 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007973 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7974 sq->end();
7975 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7976
7977 // start the fast capture
7978 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7979 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007980 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007981 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007982#ifdef AUDIO_WATCHDOG
7983 // FIXME
7984#endif
7985
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007986 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007987 }
Andy Hung8946a282018-04-19 20:04:56 -07007988#ifdef TEE_SINK
7989 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7990 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7991#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007992failed: ;
7993
7994 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007995}
7996
Andy Hung71742ab2023-07-07 13:47:37 -07007997RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007998{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007999 if (mFastCapture != 0) {
8000 FastCaptureStateQueue *sq = mFastCapture->sq();
8001 FastCaptureState *state = sq->begin();
8002 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8003 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8004 if (old == -1) {
8005 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8006 }
8007 }
8008 state->mCommand = FastCaptureState::EXIT;
8009 sq->end();
8010 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8011 mFastCapture->join();
8012 mFastCapture.clear();
8013 }
Andy Hung2cbc2722023-07-17 17:05:00 -07008014 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8015 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008016 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008017}
8018
Andy Hung71742ab2023-07-07 13:47:37 -07008019void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008020{
Glenn Kastend7dca052015-03-05 16:05:54 -08008021 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008022}
8023
Andy Hung71742ab2023-07-07 13:47:37 -07008024void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008025{
8026 ALOGV(" preExit()");
8027 Mutex::Autolock _l(mLock);
8028 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008029 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008030 track->invalidate();
8031 }
8032 mActiveTracks.clear();
8033 mStartStopCond.broadcast();
8034}
8035
Andy Hung71742ab2023-07-07 13:47:37 -07008036bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008037{
Eric Laurent81784c32012-11-19 14:55:58 -08008038 nsecs_t lastWarning = 0;
8039
8040 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008041
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008042reacquire_wakelock:
Andy Hung3ff4b552023-06-26 19:20:57 -07008043 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008044 {
8045 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07008046 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008047 }
8048
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008049 // used to request a deferred sleep, to be executed later while mutex is unlocked
8050 uint32_t sleepUs = 0;
8051
Andy Hung446f4df2019-02-21 12:26:41 -08008052 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8053
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008054 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008055 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hungbd72c542023-06-20 18:56:17 -07008056 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008057
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008058 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung3ff4b552023-06-26 19:20:57 -07008059 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008060
Glenn Kasten735f45f2014-08-18 15:51:59 -07008061 // reference to the (first and only) active fast track
Andy Hung3ff4b552023-06-26 19:20:57 -07008062 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008063
Glenn Kasten735f45f2014-08-18 15:51:59 -07008064 // reference to a fast track which is about to be removed
Andy Hung3ff4b552023-06-26 19:20:57 -07008065 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008066
Eric Laurent33403f02020-05-29 18:35:06 -07008067 bool silenceFastCapture = false;
8068
Eric Laurent81784c32012-11-19 14:55:58 -08008069 { // scope for mLock
8070 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08008071
Eric Laurent021cf962014-05-13 10:18:14 -07008072 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008073
Eric Laurent000a4192014-01-29 15:17:32 -08008074 // check exitPending here because checkForNewParameters_l() and
8075 // checkForNewParameters_l() can temporarily release mLock
8076 if (exitPending()) {
8077 break;
8078 }
8079
Eric Laurent5c25d562016-07-13 17:17:45 -07008080 // sleep with mutex unlocked
8081 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008082 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07008083 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
8084 ATRACE_END();
8085 sleepUs = 0;
8086 continue;
8087 }
8088
Glenn Kasten2b806402013-11-20 16:37:38 -08008089 // if no active track(s), then standby and release wakelock
8090 size_t size = mActiveTracks.size();
8091 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008092 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008093 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008094 releaseWakeLock_l();
8095 ALOGV("RecordThread: loop stopping");
8096 // go to sleep
8097 mWaitWorkCV.wait(mLock);
8098 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008099 goto reacquire_wakelock;
8100 }
8101
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008102 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008103 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008104 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008105
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008106 activeTrack = mActiveTracks[i];
8107 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008108 if (activeTrack->isFastTrack()) {
8109 ALOG_ASSERT(fastTrackToRemove == 0);
8110 fastTrackToRemove = activeTrack;
8111 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008112 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008113 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008114 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008115 continue;
8116 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008117
Andy Hung3ff4b552023-06-26 19:20:57 -07008118 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008119 switch (activeTrackState) {
8120
Andy Hung3ff4b552023-06-26 19:20:57 -07008121 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008122 mActiveTracks.remove(activeTrack);
Andy Hung3ff4b552023-06-26 19:20:57 -07008123 activeTrack->setState(IAfTrackBase::PAUSED);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008124 doBroadcast = true;
8125 size--;
8126 continue;
8127
Andy Hung3ff4b552023-06-26 19:20:57 -07008128 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008129 sleepUs = 10000;
8130 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008131 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008132 continue;
8133
Andy Hung3ff4b552023-06-26 19:20:57 -07008134 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008135 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008136 if (mStandby) {
8137 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008138 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008139 mStandby = false;
8140 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008141 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008142 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008143 break;
8144
Andy Hung3ff4b552023-06-26 19:20:57 -07008145 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008146 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008147 break;
8148
Andy Hung3ff4b552023-06-26 19:20:57 -07008149 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8150 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8151 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008152 default:
Andy Hungce685402018-10-05 17:23:27 -07008153 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8154 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008155 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008156
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008157 if (activeTrack->isFastTrack()) {
8158 ALOG_ASSERT(!mFastTrackAvail);
8159 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008160 // if the active fast track is silenced either:
8161 // 1) silence the whole capture from fast capture buffer if this is
8162 // the only active track
8163 // 2) invalidate this track: this will cause the client to reconnect and possibly
8164 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008165 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008166 if (activeTrack->isSilenced()) {
8167 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008168 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008169 } else {
8170 silenceFastCapture = true;
8171 }
8172 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008173 // Invalidate fast tracks if access to audio history is required as this is not
8174 // possible with fast tracks. Once the fast track has been invalidated, no new
8175 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8176 if (mMaxSharedAudioHistoryMs != 0) {
8177 invalidate = true;
8178 }
8179 if (invalidate) {
8180 activeTrack->invalidate();
8181 ALOG_ASSERT(fastTrackToRemove == 0);
8182 fastTrackToRemove = activeTrack;
8183 removeTrack_l(activeTrack);
8184 mActiveTracks.remove(activeTrack);
8185 size--;
8186 continue;
8187 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008188 fastTrack = activeTrack;
8189 }
Eric Laurent33403f02020-05-29 18:35:06 -07008190
8191 activeTracks.add(activeTrack);
8192 i++;
8193
Glenn Kasten9e982352013-08-14 14:39:50 -07008194 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008195
Andy Hungdae27702016-10-31 14:01:16 -07008196 mActiveTracks.updatePowerState(this);
8197
Kevin Rocard069c2712018-03-29 19:09:14 -07008198 updateMetadata_l();
8199
Eric Laurent5c25d562016-07-13 17:17:45 -07008200 if (allStopped) {
8201 standbyIfNotAlreadyInStandby();
8202 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008203 if (doBroadcast) {
8204 mStartStopCond.broadcast();
8205 }
8206
8207 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008208 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008209 if (sleepUs == 0) {
8210 sleepUs = kRecordThreadSleepUs;
8211 }
8212 continue;
8213 }
8214 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008215
Eric Laurent81784c32012-11-19 14:55:58 -08008216 lockEffectChains_l(effectChains);
8217 }
8218
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008219 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008220
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008221 size_t size = effectChains.size();
8222 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008223 // thread mutex is not locked, but effect chain is locked
8224 effectChains[i]->process_l();
8225 }
8226
Glenn Kasten735f45f2014-08-18 15:51:59 -07008227 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008228 if (mFastCapture != 0) {
8229 FastCaptureStateQueue *sq = mFastCapture->sq();
8230 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008231 bool didModify = false;
8232 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008233 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8234 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8235 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8236 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8237 if (old == -1) {
8238 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8239 }
8240 }
8241 state->mCommand = FastCaptureState::READ_WRITE;
8242#if 0 // FIXME
Andy Hung2cbc2722023-07-17 17:05:00 -07008243 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008244 FastThreadDumpState::kSamplingNforLowRamDevice :
8245 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008246#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008247 didModify = true;
8248 }
8249 audio_track_cblk_t *cblkOld = state->mCblk;
8250 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8251 if (cblkNew != cblkOld) {
8252 state->mCblk = cblkNew;
8253 // block until acked if removing a fast track
8254 if (cblkOld != NULL) {
8255 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8256 }
8257 didModify = true;
8258 }
jiabin01c8f562018-07-19 17:47:28 -07008259 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8260 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8261 if (state->mFastPatchRecordBufferProvider != abp) {
8262 state->mFastPatchRecordBufferProvider = abp;
8263 state->mFastPatchRecordFormat = fastTrack == 0 ?
8264 AUDIO_FORMAT_INVALID : fastTrack->format();
8265 didModify = true;
8266 }
Eric Laurent33403f02020-05-29 18:35:06 -07008267 if (state->mSilenceCapture != silenceFastCapture) {
8268 state->mSilenceCapture = silenceFastCapture;
8269 didModify = true;
8270 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008271 sq->end(didModify);
8272 if (didModify) {
8273 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008274#if 0
8275 if (kUseFastCapture == FastCapture_Dynamic) {
8276 mNormalSource = mPipeSource;
8277 }
8278#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008279 }
8280 }
8281
Glenn Kasten735f45f2014-08-18 15:51:59 -07008282 // now run the fast track destructor with thread mutex unlocked
8283 fastTrackToRemove.clear();
8284
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008285 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8286 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8287 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8288 // If destination is non-contiguous, first read past the nominal end of buffer, then
8289 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008290
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008291 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung71ba4b32022-10-06 12:09:49 -07008292 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008293 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008294
8295 // If an NBAIO source is present, use it to read the normal capture's data
8296 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008297 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008298
8299 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8300 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8301 // we immediately retry the read() to get data and prevent another overflow.
8302 for (int retries = 0; retries <= 2; ++retries) {
8303 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8304 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8305 framesToRead);
8306 if (framesRead != OVERRUN) break;
8307 }
8308
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008309 const ssize_t availableToRead = mPipeSource->availableToRead();
8310 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008311 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008312 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008313 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8314 "more frames to read than fifo size, %zd > %zu",
8315 availableToRead, mPipeFramesP2);
8316 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8317 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8318 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8319 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008320 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8321 }
8322 if (framesRead < 0) {
8323 status_t status = (status_t) framesRead;
8324 switch (status) {
8325 case OVERRUN:
8326 ALOGW("overrun on read from pipe");
8327 framesRead = 0;
8328 break;
8329 case NEGOTIATE:
8330 ALOGE("re-negotiation is needed");
8331 framesRead = -1; // Will cause an attempt to recover.
8332 break;
8333 default:
8334 ALOGE("unknown error %d on read from pipe", status);
8335 break;
8336 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008337 }
8338 // otherwise use the HAL / AudioStreamIn directly
8339 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008340 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008341 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008342 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008343 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008344 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008345 if (result < 0) {
8346 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008347 } else {
8348 framesRead = bytesRead / mFrameSize;
8349 }
8350 }
8351
Andy Hung446f4df2019-02-21 12:26:41 -08008352 const int64_t lastIoEndNs = systemTime(); // end IO timing
8353
Andy Hung3f0c9022016-01-15 17:49:46 -08008354 // Update server timestamp with server stats
8355 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008356 if (framesRead >= 0) {
8357 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8358 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8359 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008360
8361 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008362 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008363 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008364 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008365 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8366 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8367 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008368 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008369 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8370
8371 mTimestampVerifier.add(position, time, mSampleRate);
8372
8373 // Correct timestamps
8374 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008375 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008376 id(), (long long)time, (long long)position);
8377 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8378 position = correctedTimestamp.mFrames;
8379 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008380 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008381 id(), (long long)time, (long long)position);
8382 }
8383
Andy Hung3f0c9022016-01-15 17:49:46 -08008384 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8385 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8386 // Note: In general record buffers should tend to be empty in
8387 // a properly running pipeline.
8388 //
8389 // Also, it is not advantageous to call get_presentation_position during the read
8390 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008391 } else {
8392 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008393 }
8394 }
Andy Hunge6c37112019-02-26 17:38:10 -08008395
8396 // From the timestamp, input read latency is negative output write latency.
8397 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung3ff4b552023-06-26 19:20:57 -07008398 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008399 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8400 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8401 mLatencyMs.add(latencyMs);
8402 }
8403
Andy Hung3f0c9022016-01-15 17:49:46 -08008404 // Use this to track timestamp information
8405 // ALOGD("%s", mTimestamp.toString().c_str());
8406
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008407 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008408 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008409 // Force input into standby so that it tries to recover at next read attempt
8410 inputStandBy();
8411 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008412 }
8413 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008414 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008415 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008416 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008417 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008418
Andy Hung8946a282018-04-19 20:04:56 -07008419#ifdef TEE_SINK
8420 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8421#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008422 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008423 {
8424 size_t part1 = mRsmpInFramesP2 - rear;
8425 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008426 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008427 (framesRead - part1) * mFrameSize);
8428 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008429 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008430 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008431
8432 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008433
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008434 // loop over each active track
8435 for (size_t i = 0; i < size; i++) {
8436 activeTrack = activeTracks[i];
8437
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008438 // skip fast tracks, as those are handled directly by FastCapture
8439 if (activeTrack->isFastTrack()) {
8440 continue;
8441 }
8442
Andy Hung73c02e42015-03-29 01:13:58 -07008443 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008444 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8445
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008446 enum {
8447 OVERRUN_UNKNOWN,
8448 OVERRUN_TRUE,
8449 OVERRUN_FALSE
8450 } overrun = OVERRUN_UNKNOWN;
8451
8452 // loop over getNextBuffer to handle circular sink
8453 for (;;) {
8454
Andy Hung3ff4b552023-06-26 19:20:57 -07008455 activeTrack->sinkBuffer().frameCount = ~0;
8456 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8457 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008458 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8459
Andy Hung73c02e42015-03-29 01:13:58 -07008460 // check available frames and handle overrun conditions
8461 // if the record track isn't draining fast enough.
8462 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008463 size_t framesIn;
Andy Hung3ff4b552023-06-26 19:20:57 -07008464 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008465 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008466 overrun = OVERRUN_TRUE;
8467 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008468 if (framesOut == 0 || framesIn == 0) {
8469 break;
8470 }
8471
Andy Hung6770c6f2015-04-07 13:43:36 -07008472 // Don't allow framesOut to be larger than what is possible with resampling
8473 // from framesIn.
8474 // This isn't strictly necessary but helps limit buffer resizing in
8475 // RecordBufferConverter. TODO: remove when no longer needed.
8476 framesOut = min(framesOut,
8477 destinationFramesPossible(
Andy Hung3ff4b552023-06-26 19:20:57 -07008478 framesIn, mSampleRate, activeTrack->sampleRate()));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008479
8480 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008481 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008482 // straight from RecordThread buffer to RecordTrack buffer.
8483 AudioBufferProvider::Buffer buffer;
8484 buffer.frameCount = framesOut;
Andy Hung71ba4b32022-10-06 12:09:49 -07008485 const status_t getNextBufferStatus =
Andy Hung3ff4b552023-06-26 19:20:57 -07008486 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07008487 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008488 ALOGV_IF(buffer.frameCount != framesOut,
8489 "%s() read less than expected (%zu vs %zu)",
8490 __func__, buffer.frameCount, framesOut);
8491 framesOut = buffer.frameCount;
Andy Hung3ff4b552023-06-26 19:20:57 -07008492 memcpy(activeTrack->sinkBuffer().raw,
8493 buffer.raw, buffer.frameCount * mFrameSize);
8494 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008495 } else {
8496 framesOut = 0;
8497 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung71ba4b32022-10-06 12:09:49 -07008498 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008499 }
8500 } else {
8501 // process frames from the RecordThread buffer provider to the RecordTrack
8502 // buffer
Andy Hung3ff4b552023-06-26 19:20:57 -07008503 framesOut = activeTrack->recordBufferConverter()->convert(
8504 activeTrack->sinkBuffer().raw,
8505 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008506 framesOut);
8507 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008508
8509 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8510 overrun = OVERRUN_FALSE;
8511 }
8512
Andy Hung93bb5732023-05-04 21:16:34 -07008513 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8514 const ssize_t framesToDrop =
Andy Hung3ff4b552023-06-26 19:20:57 -07008515 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008516 if (framesToDrop == 0) {
8517 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008518 if (framesOut > 0) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008519 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008520 // Sanitize before releasing if the track has no access to the source data
8521 // An idle UID receives silence from non virtual devices until active
8522 if (activeTrack->isSilenced()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008523 memset(activeTrack->sinkBuffer().raw,
8524 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008525 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008526 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008527 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008528 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008529 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008530 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008531 }
8532 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008533
8534 switch (overrun) {
8535 case OVERRUN_TRUE:
8536 // client isn't retrieving buffers fast enough
8537 if (!activeTrack->setOverflow()) {
8538 nsecs_t now = systemTime();
8539 // FIXME should lastWarning per track?
8540 if ((now - lastWarning) > kWarningThrottleNs) {
8541 ALOGW("RecordThread: buffer overflow");
8542 lastWarning = now;
8543 }
8544 }
8545 break;
8546 case OVERRUN_FALSE:
8547 activeTrack->clearOverflow();
8548 break;
8549 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008550 break;
8551 }
8552
Andy Hung3f0c9022016-01-15 17:49:46 -08008553 // update frame information and push timestamp out
8554 activeTrack->updateTrackFrameInfo(
Andy Hung3ff4b552023-06-26 19:20:57 -07008555 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008556 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8557 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008558 }
8559
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008560unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008561 // enable changes in effect chain
8562 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008563 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008564 if (audio_has_proportional_frames(mFormat)
8565 && loopCount == lastLoopCountRead + 1) {
8566 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8567 const double jitterMs =
8568 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8569 {framesRead, readPeriodNs},
8570 {0, 0} /* lastTimestamp */, mSampleRate);
8571 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8572
8573 Mutex::Autolock _l(mLock);
8574 mIoJitterMs.add(jitterMs);
8575 mProcessTimeMs.add(processMs);
8576 }
8577 // update timing info.
8578 mLastIoBeginNs = lastIoBeginNs;
8579 mLastIoEndNs = lastIoEndNs;
8580 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008581 }
8582
Glenn Kasten93e471f2013-08-19 08:40:07 -07008583 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008584
8585 {
8586 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008587 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008588 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008589 track->invalidate();
8590 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008591 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008592 mStartStopCond.broadcast();
8593 }
8594
8595 releaseWakeLock();
8596
8597 ALOGV("RecordThread %p exiting", this);
8598 return false;
8599}
8600
Andy Hung71742ab2023-07-07 13:47:37 -07008601void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008602{
8603 if (!mStandby) {
8604 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008605 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008606 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008607 mStandby = true;
8608 }
8609}
8610
Andy Hung71742ab2023-07-07 13:47:37 -07008611void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008612{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008613 // Idle the fast capture if it's currently running
8614 if (mFastCapture != 0) {
8615 FastCaptureStateQueue *sq = mFastCapture->sq();
8616 FastCaptureState *state = sq->begin();
8617 if (!(state->mCommand & FastCaptureState::IDLE)) {
8618 state->mCommand = FastCaptureState::COLD_IDLE;
8619 state->mColdFutexAddr = &mFastCaptureFutex;
8620 state->mColdGen++;
8621 mFastCaptureFutex = 0;
8622 sq->end();
8623 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8624 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8625#if 0
8626 if (kUseFastCapture == FastCapture_Dynamic) {
8627 // FIXME
8628 }
8629#endif
8630#ifdef AUDIO_WATCHDOG
8631 // FIXME
8632#endif
8633 } else {
8634 sq->end(false /*didModify*/);
8635 }
8636 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008637 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008638 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008639
8640 // If going into standby, flush the pipe source.
8641 if (mPipeSource.get() != nullptr) {
8642 const ssize_t flushed = mPipeSource->flush();
8643 if (flushed > 0) {
8644 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8645 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8646 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8647 }
8648 }
Eric Laurent81784c32012-11-19 14:55:58 -08008649}
8650
Glenn Kasten05997e22014-03-13 15:08:33 -07008651// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07008652sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hungd65869f2023-06-27 17:05:02 -07008653 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008654 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008655 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008656 audio_format_t format,
8657 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008658 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008659 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008660 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008661 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008662 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008663 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008664 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008665 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008666 audio_port_handle_t portId,
8667 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008668{
Glenn Kasten74935e42013-12-19 08:56:45 -08008669 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008670 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung3ff4b552023-06-26 19:20:57 -07008671 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008672 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008673 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008674 audio_input_flags_t requestedFlags = *flags;
8675 uint32_t sampleRate;
8676
8677 lStatus = initCheck();
8678 if (lStatus != NO_ERROR) {
8679 ALOGE("createRecordTrack_l() audio driver not initialized");
8680 goto Exit;
8681 }
8682
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008683 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8684 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8685 lStatus = BAD_VALUE;
8686 goto Exit;
8687 }
8688
Eric Laurentec376dc2021-04-08 20:41:22 +02008689 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008690 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008691 lStatus = PERMISSION_DENIED;
8692 goto Exit;
8693 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008694 if (maxSharedAudioHistoryMs < 0
8695 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8696 lStatus = BAD_VALUE;
8697 goto Exit;
8698 }
8699 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008700 if (*pSampleRate == 0) {
8701 *pSampleRate = mSampleRate;
8702 }
8703 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008704
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008705 // special case for FAST flag considered OK if fast capture is present and access to
8706 // audio history is not required
8707 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008708 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8709 }
8710
Eric Laurentf14db3c2017-12-08 14:20:36 -08008711 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008712 if ((*flags & inputFlags) != *flags) {
8713 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8714 " input flags (%08x)",
8715 *flags, inputFlags);
8716 *flags = (audio_input_flags_t)(*flags & inputFlags);
8717 }
Eric Laurent81784c32012-11-19 14:55:58 -08008718
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008719 // client expresses a preference for FAST and no access to audio history,
8720 // but we get the final say
8721 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008722 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008723 // we formerly checked for a callback handler (non-0 tid),
8724 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008725 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008726 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008727 // Frame count is not specified (0), or is less than or equal the pipe depth.
8728 // It is OK to provide a higher capacity than requested.
8729 // We will force it to mPipeFramesP2 below.
8730 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008731 // PCM data
8732 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008733 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008734 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008735 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008736 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008737 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008738 hasFastCapture() &&
8739 // there are sufficient fast track slots available
8740 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008741 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008742 // check compatibility with audio effects.
8743 Mutex::Autolock _l(mLock);
8744 // Do not accept FAST flag if the session has software effects
Andy Hungbd72c542023-06-20 18:56:17 -07008745 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008746 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008747 audio_input_flags_t old = *flags;
8748 chain->checkInputFlagCompatibility(flags);
8749 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008750 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8751 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008752 }
8753 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008754 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008755 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8756 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008757 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008758 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8759 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008760 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008761 this, frameCount, mFrameCount, mPipeFramesP2,
8762 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008763 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008764 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008765 }
8766 }
8767
Eric Laurentf14db3c2017-12-08 14:20:36 -08008768 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8769 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8770 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8771 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8772 lStatus = BAD_TYPE;
8773 goto Exit;
8774 }
8775
Glenn Kasten74105912014-07-03 12:28:53 -07008776 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008777 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008778 // fast track: frame count is exactly the pipe depth
8779 frameCount = mPipeFramesP2;
8780 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008781 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008782 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008783 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8784 // or 20 ms if there is a fast capture
8785 // TODO This could be a roundupRatio inline, and const
8786 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8787 * sampleRate + mSampleRate - 1) / mSampleRate;
8788 // minimum number of notification periods is at least kMinNotifications,
8789 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8790 static const size_t kMinNotifications = 3;
8791 static const uint32_t kMinMs = 30;
8792 // TODO This could be a roundupRatio inline
8793 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8794 // TODO This could be a roundupRatio inline
8795 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8796 maxNotificationFrames;
8797 const size_t minFrameCount = maxNotificationFrames *
8798 max(kMinNotifications, minNotificationsByMs);
8799 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008800 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8801 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008802 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008803 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008804 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008805 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008806
8807 { // scope for mLock
8808 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008809 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008810 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008811 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008812 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008813 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008814 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008815 }
Eric Laurent81784c32012-11-19 14:55:58 -08008816
Andy Hung3ff4b552023-06-26 19:20:57 -07008817 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008818 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008819 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung3ff4b552023-06-26 19:20:57 -07008820 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008821 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008822
Glenn Kasten03003332013-08-06 15:40:54 -07008823 lStatus = track->initCheck();
8824 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008825 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008826 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008827 goto Exit;
8828 }
8829 mTracks.add(track);
8830
Eric Laurent05067782016-06-01 18:27:28 -07008831 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008832 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8833 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8834 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008835 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008836 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008837
8838 if (maxSharedAudioHistoryMs != 0) {
8839 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8840 }
Eric Laurent81784c32012-11-19 14:55:58 -08008841 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008842
Eric Laurent81784c32012-11-19 14:55:58 -08008843 lStatus = NO_ERROR;
8844
8845Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008846 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008847 return track;
8848}
8849
Andy Hung71742ab2023-07-07 13:47:37 -07008850status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08008851 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008852 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008853{
8854 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8855 sp<ThreadBase> strongMe = this;
8856 status_t status = NO_ERROR;
8857
8858 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008859 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008860 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008861 recordTrack->synchronizedRecordState().startRecording(
Andy Hung2cbc2722023-07-17 17:05:00 -07008862 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07008863 event, triggerSession,
8864 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08008865 }
8866
8867 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008868 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008869 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008870 if (recordTrack->isInvalid()) {
8871 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008872 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8873 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008874 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008875 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008876 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008877 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8878 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008879 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung3ff4b552023-06-26 19:20:57 -07008880 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008881 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07008882 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008883 }
8884 return status;
8885 }
8886
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008887 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8888 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8889 // or using a separate command thread
Andy Hung3ff4b552023-06-26 19:20:57 -07008890 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08008891 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008892 if (recordTrack->isExternalTrack()) {
8893 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008894 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008895 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008896 if (recordTrack->isInvalid()) {
8897 recordTrack->clearSyncStartEvent();
Andy Hung3ff4b552023-06-26 19:20:57 -07008898 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
8899 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07008900 // STARTING_2 forces destroy to call stopInput.
8901 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008902 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8903 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008904 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008905 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07008906 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung3ff4b552023-06-26 19:20:57 -07008907 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07008908 // Someone else has changed state, let them take over,
8909 // leave mState in the new state.
8910 recordTrack->clearSyncStartEvent();
8911 return INVALID_OPERATION;
8912 }
8913 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008914 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008915 ALOGW("%s(%d): startInput failed, status %d",
8916 __func__, recordTrack->id(), status);
8917 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8918 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008919 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008920 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008921 return status;
8922 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008923 sendIoConfigEvent_l(
8924 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008925 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008926
8927 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8928
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008929 // Catch up with current buffer indices if thread is already running.
8930 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8931 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8932 // see previously buffered data before it called start(), but with greater risk of overrun.
8933
Andy Hung3ff4b552023-06-26 19:20:57 -07008934 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008935 if (!recordTrack->isDirect()) {
8936 // clear any converter state as new data will be discontinuous
Andy Hung3ff4b552023-06-26 19:20:57 -07008937 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008938 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008939 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08008940 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008941 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008942 return status;
8943 }
Eric Laurent81784c32012-11-19 14:55:58 -08008944}
8945
Andy Hung71742ab2023-07-07 13:47:37 -07008946void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08008947{
Andy Hung71742ab2023-07-07 13:47:37 -07008948 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08008949
8950 if (strongEvent != 0) {
Andy Hung02a6c4e2023-06-23 19:27:19 -07008951 sp<IAfTrackBase> ptr =
8952 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
8953 if (ptr != nullptr) {
Andy Hung56126702023-07-14 11:00:08 -07008954 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hung02a6c4e2023-06-23 19:27:19 -07008955 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08008956 }
Eric Laurent81784c32012-11-19 14:55:58 -08008957 }
8958}
8959
Andy Hung71742ab2023-07-07 13:47:37 -07008960bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008961 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008962 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008963 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung3ff4b552023-06-26 19:20:57 -07008964 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008965 return false;
8966 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008967 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung3ff4b552023-06-26 19:20:57 -07008968 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07008969
Andy Hungabfab202019-03-07 19:45:54 -08008970 // NOTE: Waiting here is important to keep stop synchronous.
8971 // This is needed for proper patchRecord peer release.
Andy Hung3ff4b552023-06-26 19:20:57 -07008972 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungce685402018-10-05 17:23:27 -07008973 mWaitWorkCV.broadcast(); // signal thread to stop
8974 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008975 }
Andy Hungce685402018-10-05 17:23:27 -07008976
Andy Hung3ff4b552023-06-26 19:20:57 -07008977 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008978 ALOGV("Record stopped OK");
8979 return true;
8980 }
Andy Hungce685402018-10-05 17:23:27 -07008981
8982 // don't handle anything - we've been invalidated or restarted and in a different state
8983 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung3ff4b552023-06-26 19:20:57 -07008984 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008985 return false;
8986}
8987
Andy Hung71742ab2023-07-07 13:47:37 -07008988bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08008989{
8990 return false;
8991}
8992
Andy Hung71742ab2023-07-07 13:47:37 -07008993status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08008994{
8995#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8996 if (!isValidSyncEvent(event)) {
8997 return BAD_VALUE;
8998 }
8999
Glenn Kastend848eb42016-03-08 13:42:11 -08009000 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009001 status_t ret = NAME_NOT_FOUND;
9002
9003 Mutex::Autolock _l(mLock);
9004
9005 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009006 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009007 if (eventSession == track->sessionId()) {
9008 (void) track->setSyncEvent(event);
9009 ret = NO_ERROR;
9010 }
9011 }
9012 return ret;
9013#else
9014 return BAD_VALUE;
9015#endif
9016}
9017
Andy Hung71742ab2023-07-07 13:47:37 -07009018status_t RecordThread::getActiveMicrophones(
Andy Hung44f27182023-07-06 20:56:16 -07009019 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009020{
9021 ALOGV("RecordThread::getActiveMicrophones");
9022 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 }
jiabin9ff780e2018-03-19 18:19:52 -07009026 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9027 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009028}
9029
Andy Hung71742ab2023-07-07 13:47:37 -07009030status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009031 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009032{
Paul McLean12340082019-03-19 09:35:05 -06009033 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009034 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009035 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009036 return NO_INIT;
9037 }
Paul McLean12340082019-03-19 09:35:05 -06009038 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009039}
9040
Andy Hung71742ab2023-07-07 13:47:37 -07009041status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009042{
Paul McLean12340082019-03-19 09:35:05 -06009043 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009044 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009045 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009046 return NO_INIT;
9047 }
Paul McLean12340082019-03-19 09:35:05 -06009048 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009049}
9050
Andy Hung71742ab2023-07-07 13:47:37 -07009051status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009052 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9053 int64_t sharedAudioStartMs) {
9054 AutoMutex _l(mLock);
9055 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9056}
9057
Andy Hung71742ab2023-07-07 13:47:37 -07009058status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009059 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9060 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009061
Eric Laurentec376dc2021-04-08 20:41:22 +02009062 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9063 return BAD_VALUE;
9064 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009065
9066 if (sharedAudioStartMs < 0
9067 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009068 return BAD_VALUE;
9069 }
9070
Eric Laurent2407ce32021-04-26 14:56:03 +02009071 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9072 // As we cannot detect more than one wraparound, only accept values up current write position
9073 // after one wraparound
9074 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9075 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009076 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009077 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9078 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009079 // Bring the start frame position within the input buffer to match the documented
9080 // "best effort" behavior of the API.
9081 if (sharedOffset < 0) {
9082 sharedAudioStartFrames = mRsmpInRear;
Andy Hung71ba4b32022-10-06 12:09:49 -07009083 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009084 sharedAudioStartFrames =
9085 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009086 }
9087
Eric Laurentec376dc2021-04-08 20:41:22 +02009088 mSharedAudioPackageName = sharedAudioPackageName;
9089 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009090 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009091 } else {
9092 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009093 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009094 }
9095 return NO_ERROR;
9096}
9097
Andy Hung71742ab2023-07-07 13:47:37 -07009098void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009099 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9100 mSharedAudioStartFrames = -1;
9101 mSharedAudioPackageName = "";
9102}
9103
Andy Hung71742ab2023-07-07 13:47:37 -07009104ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009105{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009106 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009107 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009108 }
9109 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009110 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung3ff4b552023-06-26 19:20:57 -07009111 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009112 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009113 }
9114 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009115 MetadataUpdate change;
9116 change.recordMetadataUpdate = metadata.tracks;
9117 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009118}
9119
Eric Laurent81784c32012-11-19 14:55:58 -08009120// destroyTrack_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07009121void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009122{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009123 track->terminate();
Andy Hung3ff4b552023-06-26 19:20:57 -07009124 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009125
Eric Laurent81784c32012-11-19 14:55:58 -08009126 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009127 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009128 removeTrack_l(track);
9129 }
9130}
9131
Andy Hung71742ab2023-07-07 13:47:37 -07009132void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009133{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009134 String8 result;
9135 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00009136 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009137
Eric Laurent81784c32012-11-19 14:55:58 -08009138 mTracks.remove(track);
9139 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009140 if (track->isFastTrack()) {
9141 ALOG_ASSERT(!mFastTrackAvail);
9142 mFastTrackAvail = true;
9143 }
Eric Laurent81784c32012-11-19 14:55:58 -08009144}
9145
Andy Hung71742ab2023-07-07 13:47:37 -07009146void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009147{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009148 AudioStreamIn *input = mInput;
9149 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9150 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009151 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009152 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009153 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009154 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009155 }
Andy Hungbfa64962017-06-12 14:43:19 -07009156
9157 if (input != nullptr) {
9158 dprintf(fd, " Hal stream dump:\n");
9159 (void)input->stream->dump(fd);
9160 }
9161
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009162 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009163 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009164
Glenn Kasten2f90c512015-12-02 11:40:09 -08009165 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9166 // while we are dumping it. It may be inconsistent, but it won't mutate!
9167 // This is a large object so we place it on the heap.
9168 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009169 const std::unique_ptr<FastCaptureDumpState> copy =
9170 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009171 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009172}
9173
Andy Hung71742ab2023-07-07 13:47:37 -07009174void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009175{
Eric Laurent81784c32012-11-19 14:55:58 -08009176 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009177 size_t numtracks = mTracks.size();
9178 size_t numactive = mActiveTracks.size();
9179 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009180 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009181 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009182 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009183 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009184 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009185 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009186 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009187 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009188 if (track != 0) {
9189 bool active = mActiveTracks.indexOf(track) >= 0;
9190 if (active) {
9191 numactiveseen++;
9192 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009193 result.append(prefix);
9194 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009195 }
Eric Laurent81784c32012-11-19 14:55:58 -08009196 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009197 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009198 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009199 }
9200
Marco Nelissenb2208842014-02-07 14:00:50 -08009201 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009202 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009203 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009204 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009205 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009206 for (size_t i = 0; i < numactive; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009207 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009208 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009209 result.append(prefix);
9210 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009211 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009212 }
Eric Laurent81784c32012-11-19 14:55:58 -08009213
9214 }
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00009215 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009216}
9217
Andy Hung71742ab2023-07-07 13:47:37 -07009218void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009219{
9220 Mutex::Autolock _l(mLock);
9221 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009222 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009223 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009224 track->setSilenced(silenced);
9225 }
9226 }
9227}
Andy Hung73c02e42015-03-29 01:13:58 -07009228
Andy Hung3ff4b552023-06-26 19:20:57 -07009229void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009230{
Andy Hung44f27182023-07-06 20:56:16 -07009231 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung71742ab2023-07-07 13:47:37 -07009232 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009233 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009234 const int32_t rear = recordThread->mRsmpInRear;
9235 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009236 if (mRecordTrack->startFrames() >= 0) {
9237 int32_t startFrames = mRecordTrack->startFrames();
9238 // Accept a recent wraparound of mRsmpInRear
9239 if (startFrames <= rear) {
9240 deltaFrames = rear - startFrames;
9241 } else {
9242 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009243 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009244 // start frame cannot be further in the past than start of resampling buffer
9245 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9246 deltaFrames = recordThread->mRsmpInFrames;
9247 }
9248 }
9249 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009250}
9251
Andy Hung3ff4b552023-06-26 19:20:57 -07009252void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009253 size_t *framesAvailable, bool *hasOverrun)
9254{
Andy Hung44f27182023-07-06 20:56:16 -07009255 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung71742ab2023-07-07 13:47:37 -07009256 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009257 const int32_t rear = recordThread->mRsmpInRear;
9258 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009259 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009260
9261 size_t framesIn;
9262 bool overrun = false;
9263 if (filled < 0) {
9264 // should not happen, but treat like a massive overrun and re-sync
9265 framesIn = 0;
9266 mRsmpInFront = rear;
9267 overrun = true;
9268 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9269 framesIn = (size_t) filled;
9270 } else {
9271 // client is not keeping up with server, but give it latest data
9272 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009273 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9274 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009275 overrun = true;
9276 }
9277 if (framesAvailable != NULL) {
9278 *framesAvailable = framesIn;
9279 }
9280 if (hasOverrun != NULL) {
9281 *hasOverrun = overrun;
9282 }
9283}
9284
Eric Laurent81784c32012-11-19 14:55:58 -08009285// AudioBufferProvider interface
Andy Hung3ff4b552023-06-26 19:20:57 -07009286status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009287 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009288{
Andy Hung44f27182023-07-06 20:56:16 -07009289 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009290 if (threadBase == 0) {
9291 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009292 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009293 return NOT_ENOUGH_DATA;
9294 }
Andy Hung71742ab2023-07-07 13:47:37 -07009295 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009296 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009297 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009298 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009299 // FIXME should not be P2 (don't want to increase latency)
9300 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009301 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009302 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009303
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009304 front &= recordThread->mRsmpInFramesP2 - 1;
9305 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009306 if (part1 > (size_t) filled) {
9307 part1 = filled;
9308 }
9309 size_t ask = buffer->frameCount;
9310 ALOG_ASSERT(ask > 0);
9311 if (part1 > ask) {
9312 part1 = ask;
9313 }
9314 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009315 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009316 buffer->raw = NULL;
9317 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009318 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009319 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009320 }
9321
Andy Hung57446612015-04-19 23:56:46 -07009322 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009323 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009324 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009325 return NO_ERROR;
9326}
9327
9328// AudioBufferProvider interface
Andy Hung3ff4b552023-06-26 19:20:57 -07009329void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009330 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009331{
Hongwei Wang95e37682019-04-12 11:13:36 -07009332 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009333 if (stepCount == 0) {
9334 return;
9335 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009336 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009337 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009338 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009339 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009340 buffer->frameCount = 0;
9341}
9342
Andy Hung71742ab2023-07-07 13:47:37 -07009343void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009344{
9345 Mutex::Autolock _l(mLock);
9346 checkBtNrec_l();
9347}
9348
Andy Hung71742ab2023-07-07 13:47:37 -07009349void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009350{
9351 // disable AEC and NS if the device is a BT SCO headset supporting those
9352 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009353 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Andy Hung2cbc2722023-07-17 17:05:00 -07009354 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009355 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9356 for (size_t i = 0; i < mEffectChains.size(); i++) {
9357 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9358 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9359 }
9360 }
9361}
9362
Andy Hung97a893e2015-03-29 01:03:07 -07009363
Andy Hung71742ab2023-07-07 13:47:37 -07009364bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009365 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009366{
9367 bool reconfig = false;
9368
Eric Laurent10351942014-05-08 18:49:52 -07009369 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009370
Eric Laurent10351942014-05-08 18:49:52 -07009371 audio_format_t reqFormat = mFormat;
9372 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009373 // 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 +08009374 [[maybe_unused]] audio_channel_mask_t channelMask =
9375 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009376
9377 AudioParameter param = AudioParameter(keyValuePair);
9378 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009379
9380 // scope for AutoPark extends to end of method
9381 AutoPark<FastCapture> park(mFastCapture);
9382
Eric Laurent10351942014-05-08 18:49:52 -07009383 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9384 // channel count change can be requested. Do we mandate the first client defines the
9385 // HAL sampling rate and channel count or do we allow changes on the fly?
9386 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9387 samplingRate = value;
9388 reconfig = true;
9389 }
9390 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009391 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009392 status = BAD_VALUE;
9393 } else {
9394 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009395 reconfig = true;
9396 }
Eric Laurent10351942014-05-08 18:49:52 -07009397 }
9398 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9399 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009400 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009401 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009402 status = BAD_VALUE;
9403 } else {
9404 channelMask = mask;
9405 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009406 }
Eric Laurent10351942014-05-08 18:49:52 -07009407 }
9408 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9409 // do not accept frame count changes if tracks are open as the track buffer
9410 // size depends on frame count and correct behavior would not be guaranteed
9411 // if frame count is changed after track creation
9412 if (mActiveTracks.size() > 0) {
9413 status = INVALID_OPERATION;
9414 } else {
9415 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009416 }
Eric Laurent10351942014-05-08 18:49:52 -07009417 }
9418 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009419 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009420 }
9421 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9422 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009423 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009424 }
Glenn Kastene198c362013-08-13 09:13:36 -07009425
Eric Laurent10351942014-05-08 18:49:52 -07009426 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009427 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009428 if (status == INVALID_OPERATION) {
9429 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009430 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009431 }
9432 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009433 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009434 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9435 if (mInput->stream->getAudioProperties(&config) == OK &&
9436 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9437 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009438 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009439 status = NO_ERROR;
9440 }
Eric Laurent81784c32012-11-19 14:55:58 -08009441 }
Eric Laurent10351942014-05-08 18:49:52 -07009442 if (status == NO_ERROR) {
9443 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009444 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009445 }
9446 }
Eric Laurent81784c32012-11-19 14:55:58 -08009447 }
Eric Laurent10351942014-05-08 18:49:52 -07009448
Eric Laurent81784c32012-11-19 14:55:58 -08009449 return reconfig;
9450}
9451
Andy Hung71742ab2023-07-07 13:47:37 -07009452String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009453{
Eric Laurent81784c32012-11-19 14:55:58 -08009454 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009455 if (initCheck() == NO_ERROR) {
9456 String8 out_s8;
9457 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9458 return out_s8;
9459 }
Eric Laurent81784c32012-11-19 14:55:58 -08009460 }
Andy Hung71ba4b32022-10-06 12:09:49 -07009461 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009462}
9463
Andy Hung71742ab2023-07-07 13:47:37 -07009464void RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009465 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009466 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009467 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009468 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009469 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009470 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009471 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9472 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009473 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009474 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009475 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009476 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009477 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009478 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009479 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009480 break;
9481 }
Andy Hung2cbc2722023-07-17 17:05:00 -07009482 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009483}
9484
Andy Hung71742ab2023-07-07 13:47:37 -07009485void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009486{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009487 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9488 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009489 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009490 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9491 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009492 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9493 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009494 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009495 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009496 ALOGI("HAL format %#x is not linear pcm", mFormat);
9497 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009498 result = mInput->stream->getFrameSize(&mFrameSize);
9499 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009500 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9501 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009502 result = mInput->stream->getBufferSize(&mBufferSize);
9503 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009504 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009505 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9506 "mBufferSize=%zu, mFrameCount=%zu",
9507 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009508
Eric Laurentec376dc2021-04-08 20:41:22 +02009509 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9510 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009511 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009512
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009513 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9514 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009515
9516 audio_input_flags_t flags = mInput->flags;
9517 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9518 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9519 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9520 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9521 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9522 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9523 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9524 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9525 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009526}
9527
Andy Hung71742ab2023-07-07 13:47:37 -07009528uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009529{
9530 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009531 uint32_t result;
9532 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9533 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009534 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009535 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009536}
9537
Andy Hung71742ab2023-07-07 13:47:37 -07009538KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009539{
Glenn Kastend848eb42016-03-08 13:42:11 -08009540 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009541 Mutex::Autolock _l(mLock);
9542 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009543 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009544 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009545 if (ids.indexOfKey(sessionId) < 0) {
9546 ids.add(sessionId, true);
9547 }
9548 }
9549 return ids;
9550}
9551
Andy Hung71742ab2023-07-07 13:47:37 -07009552AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009553{
9554 Mutex::Autolock _l(mLock);
9555 AudioStreamIn *input = mInput;
9556 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009557 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009558 return input;
9559}
9560
9561// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hung71742ab2023-07-07 13:47:37 -07009562sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009563{
9564 if (mInput == NULL) {
9565 return NULL;
9566 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009567 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009568}
9569
Andy Hung71742ab2023-07-07 13:47:37 -07009570status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009571{
Eric Laurent81784c32012-11-19 14:55:58 -08009572 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009573 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009574 chain->setInBuffer(NULL);
9575 chain->setOutBuffer(NULL);
9576
9577 checkSuspendOnAddEffectChain_l(chain);
9578
Eric Laurent1b928682014-10-02 19:41:47 -07009579 // make sure enabled pre processing effects state is communicated to the HAL as we
9580 // just moved them to a new input stream.
9581 chain->syncHalEffectsState();
9582
Eric Laurent81784c32012-11-19 14:55:58 -08009583 mEffectChains.add(chain);
9584
9585 return NO_ERROR;
9586}
9587
Andy Hung71742ab2023-07-07 13:47:37 -07009588size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009589{
9590 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009591
9592 for (size_t i = 0; i < mEffectChains.size(); i++) {
9593 if (chain == mEffectChains[i]) {
9594 mEffectChains.removeAt(i);
9595 break;
9596 }
Eric Laurent81784c32012-11-19 14:55:58 -08009597 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009598 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009599}
9600
Andy Hung71742ab2023-07-07 13:47:37 -07009601status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009602 audio_patch_handle_t *handle)
9603{
9604 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009605
9606 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009607 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009608 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009609 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009610 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009611 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009612 }
9613
Eric Laurentd8365c52017-07-16 15:27:05 -07009614 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009615
9616 // store new source and send to effects
9617 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9618 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009619 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009620 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009621 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009622 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009623
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009624 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009625 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9626 status = hwDevice->createAudioPatch(patch->num_sources,
9627 patch->sources,
9628 patch->num_sinks,
9629 patch->sinks,
9630 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009631 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009632 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9633 patch->sinks[0].ext.mix.usecase.source,
9634 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009635 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009636 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009637
jiabinc52b1ff2019-10-31 17:20:42 -07009638 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009639 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009640 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009641 }
Eric Laurent296fb132015-05-01 11:38:42 -07009642
Andy Hungc2b11cb2020-04-22 09:04:01 -07009643 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009644 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009645 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009646 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009647 // also dispatch to active AudioRecords
9648 for (const auto &track : mActiveTracks) {
9649 track->logEndInterval();
9650 track->logBeginInterval(pathSourcesAsString);
9651 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009652 // Force meteadata update after a route change
9653 mActiveTracks.setHasChanged();
9654
Eric Laurent1c333e22014-05-20 10:48:17 -07009655 return status;
9656}
9657
Andy Hung71742ab2023-07-07 13:47:37 -07009658status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009659{
9660 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009661
jiabinc52b1ff2019-10-31 17:20:42 -07009662 mPatch = audio_patch{};
9663 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009664
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009665 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009666 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9667 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009668 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009669 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009670 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009671 // Force meteadata update after a route change
9672 mActiveTracks.setHasChanged();
9673
Eric Laurent1c333e22014-05-20 10:48:17 -07009674 return status;
9675}
9676
Andy Hung71742ab2023-07-07 13:47:37 -07009677void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009678{
wendy lin56aa82b2020-12-02 15:19:55 +08009679 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009680 mOutDevices = outDevices;
9681 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9682 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009683 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009684 }
9685}
9686
Andy Hung71742ab2023-07-07 13:47:37 -07009687int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009688{
9689 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009690 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009691 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009692 int32_t oldestFront = mRsmpInRear;
9693 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009694 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009695 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009696 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009697 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009698 if (filled > maxFilled) {
9699 oldestFront = front;
9700 maxFilled = filled;
9701 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009702 }
Andy Hung71ba4b32022-10-06 12:09:49 -07009703 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009704 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9705 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009706 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009707}
9708
Andy Hung71742ab2023-07-07 13:47:37 -07009709void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009710{
9711 if (offset == 0) {
9712 return;
9713 }
9714 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009715 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009716 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung3ff4b552023-06-26 19:20:57 -07009717 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009718 }
9719}
9720
Andy Hung71742ab2023-07-07 13:47:37 -07009721void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009722{
9723 // This is the formula for calculating the temporary buffer size.
9724 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9725 // 1 full output buffer, regardless of the alignment of the available input.
9726 // The value is somewhat arbitrary, and could probably be even larger.
9727 // A larger value should allow more old data to be read after a track calls start(),
9728 // without increasing latency.
9729 //
9730 // Note this is independent of the maximum downsampling ratio permitted for capture.
9731 size_t minRsmpInFrames = mFrameCount * 7;
9732
9733 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9734 // capture history available to another client using the same session ID:
9735 // dimension the resampler input buffer accordingly.
9736
9737 // Get oldest client read position: getOldestFront_l() must be called before altering
9738 // mRsmpInRear, or mRsmpInFrames
9739 int32_t previousFront = getOldestFront_l();
9740 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9741 int32_t previousRear = mRsmpInRear;
9742 mRsmpInRear = 0;
9743
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009744 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hung71742ab2023-07-07 13:47:37 -07009745 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009746 "resizeInputBuffer_l() called with invalid max shared history %d",
9747 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009748 if (maxSharedAudioHistoryMs != 0) {
9749 // resizeInputBuffer_l should never be called with a non zero shared history if the
9750 // buffer was not already allocated
9751 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9752 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9753 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9754 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009755 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009756 return;
9757 }
9758 mRsmpInFrames = rsmpInFrames;
9759 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009760 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009761 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9762 // initialized
9763 if (mRsmpInFrames < minRsmpInFrames) {
9764 mRsmpInFrames = minRsmpInFrames;
9765 }
9766 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9767
9768 // TODO optimize audio capture buffer sizes ...
9769 // Here we calculate the size of the sliding buffer used as a source
9770 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9771 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9772 // be better to have it derived from the pipe depth in the long term.
9773 // The current value is higher than necessary. However it should not add to latency.
9774
9775 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9776 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9777
9778 void *rsmpInBuffer;
9779 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9780 // if posix_memalign fails, will segv here.
9781 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9782
9783 // Copy audio history if any from old buffer before freeing it
9784 if (previousRear != 0) {
9785 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9786 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9787
9788 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9789 previousFront &= previousRsmpInFramesP2 - 1;
9790 size_t part1 = previousRsmpInFramesP2 - previousFront;
9791 if (part1 > (size_t) unread) {
9792 part1 = unread;
9793 }
9794 if (part1 != 0) {
9795 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9796 part1 * mFrameSize);
9797 mRsmpInRear = part1;
9798 part1 = unread - part1;
9799 if (part1 != 0) {
9800 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9801 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9802 mRsmpInRear += part1;
9803 }
9804 }
9805 // Update front for all clients according to new rear
9806 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9807 } else {
9808 mRsmpInRear = 0;
9809 }
9810 free(mRsmpInBuffer);
9811 mRsmpInBuffer = rsmpInBuffer;
9812}
9813
Andy Hung71742ab2023-07-07 13:47:37 -07009814void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009815{
9816 Mutex::Autolock _l(mLock);
9817 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009818 if (record->getSource()) {
9819 mSource = record->getSource();
9820 }
Eric Laurent83b88082014-06-20 18:31:16 -07009821}
9822
Andy Hung71742ab2023-07-07 13:47:37 -07009823void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009824{
9825 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009826 if (mSource == record->getSource()) {
9827 mSource = mInput;
9828 }
Eric Laurent83b88082014-06-20 18:31:16 -07009829 destroyTrack_l(record);
9830}
9831
Andy Hung71742ab2023-07-07 13:47:37 -07009832void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07009833{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009834 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009835 config->role = AUDIO_PORT_ROLE_SINK;
9836 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9837 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009838 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9839 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9840 config->flags.input = mInput->flags;
9841 }
Eric Laurent83b88082014-06-20 18:31:16 -07009842}
Eric Laurent1c333e22014-05-20 10:48:17 -07009843
Eric Laurent6acd1d42017-01-04 14:23:29 -08009844// ----------------------------------------------------------------------------
9845// Mmap
9846// ----------------------------------------------------------------------------
9847
Andy Hung667dec42023-07-07 15:58:48 -07009848// Mmap stream control interface implementation. Each MmapThreadHandle controls one
9849// MmapPlaybackThread or MmapCaptureThread instance.
9850class MmapThreadHandle : public MmapStreamInterface {
9851public:
9852 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
9853 ~MmapThreadHandle() override;
9854
9855 // MmapStreamInterface virtuals
9856 status_t createMmapBuffer(int32_t minSizeFrames,
9857 struct audio_mmap_buffer_info* info) final;
9858 status_t getMmapPosition(struct audio_mmap_position* position) final;
9859 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
9860 status_t start(const AudioClient& client,
9861 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
9862 status_t stop(audio_port_handle_t handle) final;
9863 status_t standby() final;
9864 status_t reportData(const void* buffer, size_t frameCount) final;
9865private:
9866 const sp<IAfMmapThread> mThread;
9867};
9868
9869/* static */
9870sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
9871 const sp<IAfMmapThread>& mmapThread) {
9872 return sp<MmapThreadHandle>::make(mmapThread);
9873}
9874
9875MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009876 : mThread(thread)
9877{
Phil Burk9fabbf82017-08-03 12:02:00 -07009878 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009879}
9880
Andy Hung667dec42023-07-07 15:58:48 -07009881// MmapStreamInterface could be directly implemented by MmapThread excepting this
9882// special handling on adapter dtor.
9883MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009884{
Phil Burk9fabbf82017-08-03 12:02:00 -07009885 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009886}
9887
Andy Hung667dec42023-07-07 15:58:48 -07009888status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009889 struct audio_mmap_buffer_info *info)
9890{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009891 return mThread->createMmapBuffer(minSizeFrames, info);
9892}
9893
Andy Hung667dec42023-07-07 15:58:48 -07009894status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009895{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009896 return mThread->getMmapPosition(position);
9897}
9898
Andy Hung667dec42023-07-07 15:58:48 -07009899status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -07009900 int64_t *timeNanos) {
9901 return mThread->getExternalPosition(position, timeNanos);
9902}
9903
Andy Hung667dec42023-07-07 15:58:48 -07009904status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009905 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009906{
jiabind1f1cb62020-03-24 11:57:57 -07009907 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009908}
9909
Andy Hung667dec42023-07-07 15:58:48 -07009910status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009911{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009912 return mThread->stop(handle);
9913}
9914
Andy Hung667dec42023-07-07 15:58:48 -07009915status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -08009916{
Eric Laurent18b57012017-02-13 16:23:52 -08009917 return mThread->standby();
9918}
9919
Andy Hung667dec42023-07-07 15:58:48 -07009920status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
9921{
jiabinfc791ee2023-02-15 19:43:40 +00009922 return mThread->reportData(buffer, frameCount);
9923}
9924
Eric Laurent6acd1d42017-01-04 14:23:29 -08009925
Andy Hung71742ab2023-07-07 13:47:37 -07009926MmapThread::MmapThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07009927 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung71ba4b32022-10-06 12:09:49 -07009928 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung2cbc2722023-07-17 17:05:00 -07009929 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009930 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009931 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009932 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009933 mActiveTracks(&this->mLocalLog),
9934 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9935 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009936{
Eric Laurent18b57012017-02-13 16:23:52 -08009937 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009938 readHalParameters_l();
9939}
9940
Andy Hung71742ab2023-07-07 13:47:37 -07009941void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009942{
9943 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9944}
9945
Andy Hung71742ab2023-07-07 13:47:37 -07009946void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009947{
Andy Hung3ff4b552023-06-26 19:20:57 -07009948 ActiveTracks<IAfMmapTrack> activeTracks;
Eric Laurent331679c2018-04-16 17:03:16 -07009949 {
9950 Mutex::Autolock _l(mLock);
Andy Hung3ff4b552023-06-26 19:20:57 -07009951 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -07009952 activeTracks.add(t);
9953 }
9954 }
Andy Hung3ff4b552023-06-26 19:20:57 -07009955 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009956 stop(t->portId());
9957 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009958 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009959 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009960 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009961 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009962 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009963 }
9964}
9965
9966
Andy Hung71742ab2023-07-07 13:47:37 -07009967void MmapThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009968 audio_stream_type_t streamType __unused,
9969 audio_session_t sessionId,
9970 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009971 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009972 audio_port_handle_t portId)
9973{
9974 mAttr = *attr;
9975 mSessionId = sessionId;
9976 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009977 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009978 mPortId = portId;
9979}
9980
Andy Hung71742ab2023-07-07 13:47:37 -07009981status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009982 struct audio_mmap_buffer_info *info)
9983{
9984 if (mHalStream == 0) {
9985 return NO_INIT;
9986 }
Eric Laurent18b57012017-02-13 16:23:52 -08009987 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009988 return mHalStream->createMmapBuffer(minSizeFrames, info);
9989}
9990
Andy Hung71742ab2023-07-07 13:47:37 -07009991status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -08009992{
9993 if (mHalStream == 0) {
9994 return NO_INIT;
9995 }
9996 return mHalStream->getMmapPosition(position);
9997}
9998
Andy Hung71742ab2023-07-07 13:47:37 -07009999status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010000{
Eric Laurentdda206a2022-07-08 17:28:35 +020010001 // The HAL must receive track metadata before starting the stream
10002 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010003 status_t ret = mHalStream->start();
10004 if (ret != NO_ERROR) {
10005 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10006 return ret;
10007 }
Andy Hungcf10d742020-04-28 15:38:24 -070010008 if (mStandby) {
10009 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010010 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010011 mStandby = false;
10012 }
Eric Laurent331679c2018-04-16 17:03:16 -070010013 return NO_ERROR;
10014}
10015
Andy Hung71742ab2023-07-07 13:47:37 -070010016status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010017 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010018 audio_port_handle_t *handle)
10019{
Eric Laurenta54f1282017-07-01 19:39:32 -070010020 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010021 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010022 if (mHalStream == 0) {
10023 return NO_INIT;
10024 }
10025
10026 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010027
Eric Laurentdda206a2022-07-08 17:28:35 +020010028 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010029 if (*handle == mPortId) {
Eric Laurentdda206a2022-07-08 17:28:35 +020010030 acquireWakeLock();
10031 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010032 }
10033
10034 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10035
10036 audio_io_handle_t io = mId;
Andy Hungc5106312023-07-19 16:56:19 -070010037 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010038 client.attributionSource);
10039
Eric Laurenta54f1282017-07-01 19:39:32 -070010040 if (isOutput()) {
10041 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10042 config.sample_rate = mSampleRate;
10043 config.channel_mask = mChannelMask;
10044 config.format = mFormat;
10045 audio_stream_type_t stream = streamType();
10046 audio_output_flags_t flags =
10047 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010048 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010049 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010050 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010051 bool isBitPerfect;
Eric Laurenta54f1282017-07-01 19:39:32 -070010052 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
10053 mSessionId,
10054 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010055 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010056 &config,
10057 flags,
10058 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010059 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010060 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010061 &isSpatialized,
10062 &isBitPerfect);
Kevin Rocard153f92d2018-12-18 18:33:28 -080010063 ALOGD_IF(!secondaryOutputs.empty(),
10064 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010065 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010066 audio_config_base_t config;
10067 config.sample_rate = mSampleRate;
10068 config.channel_mask = mChannelMask;
10069 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010070 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -070010071 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010072 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -070010073 mSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010074 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010075 &config,
10076 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10077 &deviceId,
10078 &portId);
10079 }
10080 // APM should not chose a different input or output stream for the same set of attributes
10081 // and audo configuration
10082 if (ret != NO_ERROR || io != mId) {
10083 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10084 __FUNCTION__, ret, io, mId);
10085 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010086 }
10087
10088 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010089 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010090 } else {
jiabincfc10a42022-06-15 19:26:01 +000010091 {
10092 // Add the track record before starting input so that the silent status for the
10093 // client can be cached.
10094 Mutex::Autolock _l(mLock);
10095 setClientSilencedState_l(portId, false /*silenced*/);
10096 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010097 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010098 }
10099
Eric Laurent331679c2018-04-16 17:03:16 -070010100 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010101 // abort if start is rejected by audio policy manager
10102 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010103 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010104 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -070010105 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010106 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010107 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010108 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010109 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010110 }
Eric Laurent331679c2018-04-16 17:03:16 -070010111 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010112 } else {
10113 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010114 }
jiabincfc10a42022-06-15 19:26:01 +000010115 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010116 return PERMISSION_DENIED;
10117 }
10118
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010119 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung3ff4b552023-06-26 19:20:57 -070010120 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10121 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010122 mChannelMask, mSessionId, isOutput(),
10123 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010124 IPCThreadState::self()->getCallingPid(), portId);
jiabincfc10a42022-06-15 19:26:01 +000010125 if (!isOutput()) {
10126 track->setSilenced_l(isClientSilenced_l(portId));
10127 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010128
Eric Laurent4eb58f12018-12-07 16:41:02 -080010129 if (isOutput()) {
10130 // force volume update when a new track is added
10131 mHalVolFloat = -1.0f;
10132 } else if (!track->isSilenced_l()) {
Andy Hung3ff4b552023-06-26 19:20:57 -070010133 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung71ba4b32022-10-06 12:09:49 -070010134 if (t->isSilenced_l()
10135 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010136 t->invalidate();
Andy Hung71ba4b32022-10-06 12:09:49 -070010137 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010138 }
10139 }
10140
Eric Laurent6acd1d42017-01-04 14:23:29 -080010141 mActiveTracks.add(track);
Andy Hungbd72c542023-06-20 18:56:17 -070010142 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010143 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +020010144 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010145 chain->incTrackCnt();
10146 chain->incActiveTrackCnt();
10147 }
10148
Andy Hungc2b11cb2020-04-22 09:04:01 -070010149 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010150 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010151
10152 if (mActiveTracks.size() == 1) {
10153 ret = exitStandby_l();
10154 }
10155
Eric Laurent6acd1d42017-01-04 14:23:29 -080010156 broadcast_l();
10157
Eric Laurentdda206a2022-07-08 17:28:35 +020010158 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010159
Eric Laurentdda206a2022-07-08 17:28:35 +020010160 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010161}
10162
Andy Hung71742ab2023-07-07 13:47:37 -070010163status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010164{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010165 ALOGV("%s handle %d", __FUNCTION__, handle);
10166
10167 if (mHalStream == 0) {
10168 return NO_INIT;
10169 }
10170
Eric Laurenta54f1282017-07-01 19:39:32 -070010171 if (handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +000010172 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -070010173 return NO_ERROR;
10174 }
10175
Eric Laurent331679c2018-04-16 17:03:16 -070010176 Mutex::Autolock _l(mLock);
10177
Andy Hung3ff4b552023-06-26 19:20:57 -070010178 sp<IAfMmapTrack> track;
10179 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010180 if (handle == t->portId()) {
10181 track = t;
10182 break;
10183 }
10184 }
10185 if (track == 0) {
10186 return BAD_VALUE;
10187 }
10188
10189 mActiveTracks.remove(track);
jiabincfc10a42022-06-15 19:26:01 +000010190 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010191
Eric Laurent331679c2018-04-16 17:03:16 -070010192 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010193 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010194 AudioSystem::stopOutput(track->portId());
10195 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010196 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010197 AudioSystem::stopInput(track->portId());
10198 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010199 }
Eric Laurent331679c2018-04-16 17:03:16 -070010200 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010201
Andy Hungbd72c542023-06-20 18:56:17 -070010202 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010203 if (chain != 0) {
10204 chain->decActiveTrackCnt();
10205 chain->decTrackCnt();
10206 }
10207
Eric Laurentdda206a2022-07-08 17:28:35 +020010208 if (mActiveTracks.isEmpty()) {
10209 mHalStream->stop();
10210 }
10211
Eric Laurent6acd1d42017-01-04 14:23:29 -080010212 broadcast_l();
10213
Eric Laurent6acd1d42017-01-04 14:23:29 -080010214 return NO_ERROR;
10215}
10216
Andy Hung71742ab2023-07-07 13:47:37 -070010217status_t MmapThread::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010218{
10219 ALOGV("%s", __FUNCTION__);
10220
10221 if (mHalStream == 0) {
10222 return NO_INIT;
10223 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010224 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010225 return INVALID_OPERATION;
10226 }
10227 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010228 if (!mStandby) {
10229 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010230 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010231 mStandby = true;
10232 }
Eric Laurent18b57012017-02-13 16:23:52 -080010233 releaseWakeLock();
10234 return NO_ERROR;
10235}
10236
Andy Hung71742ab2023-07-07 13:47:37 -070010237status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010238 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10239 return INVALID_OPERATION;
10240}
Eric Laurent6acd1d42017-01-04 14:23:29 -080010241
Andy Hung71742ab2023-07-07 13:47:37 -070010242void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010243{
10244 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10245 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10246 mFormat = mHALFormat;
10247 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10248 result = mHalStream->getFrameSize(&mFrameSize);
10249 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010250 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10251 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010252 result = mHalStream->getBufferSize(&mBufferSize);
10253 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10254 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010255
Andy Hungcf10d742020-04-28 15:38:24 -070010256 // TODO: make a readHalParameters call?
10257 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010258 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
10259 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
10260 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10261 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10262 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10263 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10264 /*
10265 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10266 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10267 (int32_t)mHapticChannelMask)
10268 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10269 (int32_t)mHapticChannelCount)
10270 */
10271 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
10272 formatToString(mHALFormat).c_str())
10273 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10274 (int32_t)mFrameCount) // sic - added HAL
10275 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010276}
10277
Andy Hung71742ab2023-07-07 13:47:37 -070010278bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010279{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010280 checkSilentMode_l();
10281
10282 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10283
10284 while (!exitPending())
10285 {
Andy Hungbd72c542023-06-20 18:56:17 -070010286 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010287
Andy Hung13850be2019-03-14 11:33:09 -070010288 { // under Thread lock
10289 Mutex::Autolock _l(mLock);
10290
Eric Laurent6acd1d42017-01-04 14:23:29 -080010291 if (mSignalPending) {
10292 // A signal was raised while we were unlocked
10293 mSignalPending = false;
10294 } else {
10295 if (mConfigEvents.isEmpty()) {
10296 // we're about to wait, flush the binder command buffer
10297 IPCThreadState::self()->flushCommands();
10298
10299 if (exitPending()) {
10300 break;
10301 }
10302
Eric Laurent6acd1d42017-01-04 14:23:29 -080010303 // wait until we have something to do...
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010304 ALOGV("%s going to sleep", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010305 mWaitWorkCV.wait(mLock);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010306 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010307
10308 checkSilentMode_l();
10309
10310 continue;
10311 }
10312 }
10313
10314 processConfigEvents_l();
10315
10316 processVolume_l();
10317
10318 checkInvalidTracks_l();
10319
10320 mActiveTracks.updatePowerState(this);
10321
Kevin Rocard069c2712018-03-29 19:09:14 -070010322 updateMetadata_l();
10323
Eric Laurent6acd1d42017-01-04 14:23:29 -080010324 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010325 } // release Thread lock
10326
Eric Laurent6acd1d42017-01-04 14:23:29 -080010327 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010328 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010329 }
Andy Hung13850be2019-03-14 11:33:09 -070010330
10331 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010332 unlockEffectChains(effectChains);
10333 // Effect chains will be actually deleted here if they were removed from
10334 // mEffectChains list during mixing or effects processing
10335 }
10336
10337 threadLoop_exit();
10338
10339 if (!mStandby) {
10340 threadLoop_standby();
10341 mStandby = true;
10342 }
10343
Eric Laurent6acd1d42017-01-04 14:23:29 -080010344 ALOGV("Thread %p type %d exiting", this, mType);
10345 return false;
10346}
10347
10348// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -070010349bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010350 status_t& status)
10351{
10352 AudioParameter param = AudioParameter(keyValuePair);
10353 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010354 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010355 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010356 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010357 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010358 if (sendToHal) {
10359 status = mHalStream->setParameters(keyValuePair);
10360 } else {
10361 status = NO_ERROR;
10362 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010363
10364 return false;
10365}
10366
Andy Hung71742ab2023-07-07 13:47:37 -070010367String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010368{
10369 Mutex::Autolock _l(mLock);
10370 String8 out_s8;
10371 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10372 return out_s8;
10373 }
Andy Hung71ba4b32022-10-06 12:09:49 -070010374 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010375}
10376
Andy Hung71742ab2023-07-07 13:47:37 -070010377void MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010378 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010379 sp<AudioIoDescriptor> desc;
10380 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010381 switch (event) {
10382 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010383 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010384 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010385 isInput = true;
10386 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010387 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010388 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010389 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010390 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10391 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010392 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010393 case AUDIO_INPUT_CLOSED:
10394 case AUDIO_OUTPUT_CLOSED:
10395 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010396 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010397 break;
10398 }
Andy Hung2cbc2722023-07-17 17:05:00 -070010399 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010400}
10401
Andy Hung71742ab2023-07-07 13:47:37 -070010402status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010403 audio_patch_handle_t *handle)
Andy Hung71ba4b32022-10-06 12:09:49 -070010404NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010405{
10406 status_t status = NO_ERROR;
10407
10408 // store new device and send to effects
10409 audio_devices_t type = AUDIO_DEVICE_NONE;
10410 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010411 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10412 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10413 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010414 if (isOutput()) {
10415 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010416 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10417 && !mAudioHwDev->supportsAudioPatches(),
10418 "Enumerated device type(%#x) must not be used "
10419 "as it does not support audio patches",
10420 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010421 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung71ba4b32022-10-06 12:09:49 -070010422 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10423 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010424 }
10425 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010426 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010427 } else {
10428 type = patch->sources[0].ext.device.type;
10429 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010430 numDevices = mPatch.num_sources;
10431 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010432 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010433 }
10434
10435 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010436 if (isOutput()) {
10437 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10438 } else {
10439 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10440 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010441 }
10442
jiabinc52b1ff2019-10-31 17:20:42 -070010443 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010444 // store new source and send to effects
10445 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10446 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10447 for (size_t i = 0; i < mEffectChains.size(); i++) {
10448 mEffectChains[i]->setAudioSource_l(mAudioSource);
10449 }
10450 }
10451 }
10452
10453 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010454 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10455 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010456 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010457 audio_port_config port;
10458 std::optional<audio_source_t> source;
10459 if (isOutput()) {
10460 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010461 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010462 port = patch->sources[0];
10463 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010464 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010465 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010466 *handle = AUDIO_PATCH_HANDLE_NONE;
10467 }
10468
jiabinc52b1ff2019-10-31 17:20:42 -070010469 if (numDevices == 0 || mDeviceId != deviceId) {
10470 if (isOutput()) {
10471 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10472 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010473 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010474 } else {
10475 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10476 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10477 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010478 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010479 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010480 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010481 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -070010482 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010483 }
jiabinc52b1ff2019-10-31 17:20:42 -070010484 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010485 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010486 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010487 // Force meteadata update after a route change
10488 mActiveTracks.setHasChanged();
10489
Eric Laurent6acd1d42017-01-04 14:23:29 -080010490 return status;
10491}
10492
Andy Hung71742ab2023-07-07 13:47:37 -070010493status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010494{
10495 status_t status = NO_ERROR;
10496
jiabinc52b1ff2019-10-31 17:20:42 -070010497 mPatch = audio_patch{};
10498 mOutDeviceTypeAddrs.clear();
10499 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010500
10501 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10502 supportsAudioPatches : false;
10503
10504 if (supportsAudioPatches) {
10505 status = mHalDevice->releaseAudioPatch(handle);
10506 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010507 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010508 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010509 // Force meteadata update after a route change
10510 mActiveTracks.setHasChanged();
10511
Eric Laurent6acd1d42017-01-04 14:23:29 -080010512 return status;
10513}
10514
Andy Hung71742ab2023-07-07 13:47:37 -070010515void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010516{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010517 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010518 if (isOutput()) {
10519 config->role = AUDIO_PORT_ROLE_SOURCE;
10520 config->ext.mix.hw_module = mAudioHwDev->handle();
10521 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10522 } else {
10523 config->role = AUDIO_PORT_ROLE_SINK;
10524 config->ext.mix.hw_module = mAudioHwDev->handle();
10525 config->ext.mix.usecase.source = mAudioSource;
10526 }
10527}
10528
Andy Hung71742ab2023-07-07 13:47:37 -070010529status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010530{
10531 audio_session_t session = chain->sessionId();
10532
10533 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10534 // Attach all tracks with same session ID to this chain.
10535 // indicate all active tracks in the chain
Andy Hung3ff4b552023-06-26 19:20:57 -070010536 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010537 if (session == track->sessionId()) {
10538 chain->incTrackCnt();
10539 chain->incActiveTrackCnt();
10540 }
10541 }
10542
10543 chain->setThread(this);
10544 chain->setInBuffer(nullptr);
10545 chain->setOutBuffer(nullptr);
10546 chain->syncHalEffectsState();
10547
10548 mEffectChains.add(chain);
10549 checkSuspendOnAddEffectChain_l(chain);
10550 return NO_ERROR;
10551}
10552
Andy Hung71742ab2023-07-07 13:47:37 -070010553size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010554{
10555 audio_session_t session = chain->sessionId();
10556
10557 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10558
10559 for (size_t i = 0; i < mEffectChains.size(); i++) {
10560 if (chain == mEffectChains[i]) {
10561 mEffectChains.removeAt(i);
10562 // detach all active tracks from the chain
10563 // detach all tracks with same session ID from this chain
Andy Hung3ff4b552023-06-26 19:20:57 -070010564 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010565 if (session == track->sessionId()) {
10566 chain->decActiveTrackCnt();
10567 chain->decTrackCnt();
10568 }
10569 }
10570 break;
10571 }
10572 }
10573 return mEffectChains.size();
10574}
10575
Andy Hung71742ab2023-07-07 13:47:37 -070010576void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010577{
10578 mHalStream->standby();
10579}
10580
Andy Hung71742ab2023-07-07 13:47:37 -070010581void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010582{
Phil Burk7dce7282017-09-27 13:51:41 -070010583 // Do not call callback->onTearDown() because it is redundant for thread exit
10584 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010585}
10586
Andy Hung71742ab2023-07-07 13:47:37 -070010587status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010588{
10589 return BAD_VALUE;
10590}
10591
Andy Hung71742ab2023-07-07 13:47:37 -070010592bool MmapThread::isValidSyncEvent(
10593 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010594{
10595 return false;
10596}
10597
Andy Hung71742ab2023-07-07 13:47:37 -070010598status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010599 const effect_descriptor_t *desc, audio_session_t sessionId)
10600{
10601 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010602 if (audio_is_global_session(sessionId)) {
10603 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010604 desc->name, mThreadName);
10605 return BAD_VALUE;
10606 }
10607
10608 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10609 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10610 desc->name);
10611 return BAD_VALUE;
10612 }
10613 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010614 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10615 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010616 return BAD_VALUE;
10617 }
10618
10619 // Only allow effects without processing load or latency
10620 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10621 return BAD_VALUE;
10622 }
10623
Andy Hungbd72c542023-06-20 18:56:17 -070010624 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010625 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10626 return BAD_VALUE;
10627 }
10628
Eric Laurent6acd1d42017-01-04 14:23:29 -080010629 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010630}
10631
Andy Hung71742ab2023-07-07 13:47:37 -070010632void MmapThread::checkInvalidTracks_l()
Andy Hung71ba4b32022-10-06 12:09:49 -070010633NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010634{
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010635 sp<MmapStreamCallback> callback;
Andy Hung3ff4b552023-06-26 19:20:57 -070010636 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010637 if (track->isInvalid()) {
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010638 callback = mCallback.promote();
10639 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10640 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
Eric Laurent331679c2018-04-16 17:03:16 -070010641 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010642 }
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010643 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010644 }
10645 }
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010646 if (callback != 0) {
10647 mLock.unlock();
10648 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10649 mLock.lock();
10650 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010651}
10652
Andy Hung71742ab2023-07-07 13:47:37 -070010653void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010654{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010655 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10656 mAttr.content_type, mAttr.usage, mAttr.source);
10657 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010658 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010659 dprintf(fd, " No active clients\n");
10660 }
10661}
10662
Andy Hung71742ab2023-07-07 13:47:37 -070010663void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010664{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010665 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010666 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010667 dprintf(fd, " %zu Tracks\n", numtracks);
10668 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010669 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010670 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010671 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010672 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -070010673 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010674 result.append(prefix);
10675 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010676 }
10677 } else {
10678 dprintf(fd, "\n");
10679 }
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010680 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010681}
10682
Andy Hung71742ab2023-07-07 13:47:37 -070010683/* static */
10684sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung2cbc2722023-07-17 17:05:00 -070010685 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung71742ab2023-07-07 13:47:37 -070010686 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -070010687 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -070010688}
10689
10690MmapPlaybackThread::MmapPlaybackThread(
Andy Hung2cbc2722023-07-17 17:05:00 -070010691 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010692 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -070010693 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010694 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010695 mStreamVolume(1.0),
10696 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010697 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010698{
10699 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10700 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung2cbc2722023-07-17 17:05:00 -070010701 mMasterVolume = afThreadCallback->masterVolume_l();
10702 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010703 if (mAudioHwDev) {
10704 if (mAudioHwDev->canSetMasterVolume()) {
10705 mMasterVolume = 1.0;
10706 }
10707
10708 if (mAudioHwDev->canSetMasterMute()) {
10709 mMasterMute = false;
10710 }
10711 }
10712}
10713
Andy Hung71742ab2023-07-07 13:47:37 -070010714void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010715 audio_stream_type_t streamType,
10716 audio_session_t sessionId,
10717 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010718 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010719 audio_port_handle_t portId)
10720{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010721 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010722 mStreamType = streamType;
10723}
10724
Andy Hung71742ab2023-07-07 13:47:37 -070010725AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010726{
10727 Mutex::Autolock _l(mLock);
10728 AudioStreamOut *output = mOutput;
10729 mOutput = NULL;
10730 return output;
10731}
10732
Andy Hung71742ab2023-07-07 13:47:37 -070010733void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010734{
10735 Mutex::Autolock _l(mLock);
10736 // Don't apply master volume in SW if our HAL can do it for us.
10737 if (mAudioHwDev &&
10738 mAudioHwDev->canSetMasterVolume()) {
10739 mMasterVolume = 1.0;
10740 } else {
10741 mMasterVolume = value;
10742 }
10743}
10744
Andy Hung71742ab2023-07-07 13:47:37 -070010745void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010746{
10747 Mutex::Autolock _l(mLock);
10748 // Don't apply master mute in SW if our HAL can do it for us.
10749 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10750 mMasterMute = false;
10751 } else {
10752 mMasterMute = muted;
10753 }
10754}
10755
Andy Hung71742ab2023-07-07 13:47:37 -070010756void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010757{
10758 Mutex::Autolock _l(mLock);
10759 if (stream == mStreamType) {
10760 mStreamVolume = value;
10761 broadcast_l();
10762 }
10763}
10764
Andy Hung71742ab2023-07-07 13:47:37 -070010765float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010766{
10767 Mutex::Autolock _l(mLock);
10768 if (stream == mStreamType) {
10769 return mStreamVolume;
10770 }
10771 return 0.0f;
10772}
10773
Andy Hung71742ab2023-07-07 13:47:37 -070010774void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010775{
10776 Mutex::Autolock _l(mLock);
10777 if (stream == mStreamType) {
10778 mStreamMute= muted;
10779 broadcast_l();
10780 }
10781}
10782
Andy Hung71742ab2023-07-07 13:47:37 -070010783void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010784{
10785 Mutex::Autolock _l(mLock);
10786 if (streamType == mStreamType) {
Andy Hung3ff4b552023-06-26 19:20:57 -070010787 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010788 track->invalidate();
10789 }
10790 broadcast_l();
10791 }
10792}
10793
Andy Hung71742ab2023-07-07 13:47:37 -070010794void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010795{
10796 Mutex::Autolock _l(mLock);
10797 bool trackMatch = false;
Andy Hung3ff4b552023-06-26 19:20:57 -070010798 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010799 if (portIds.find(track->portId()) != portIds.end()) {
10800 track->invalidate();
10801 trackMatch = true;
10802 portIds.erase(track->portId());
10803 }
10804 if (portIds.empty()) {
10805 break;
10806 }
10807 }
10808 if (trackMatch) {
10809 broadcast_l();
10810 }
10811}
10812
Andy Hung71742ab2023-07-07 13:47:37 -070010813void MmapPlaybackThread::processVolume_l()
Andy Hung71ba4b32022-10-06 12:09:49 -070010814NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080010815{
10816 float volume;
10817
10818 if (mMasterMute || mStreamMute) {
10819 volume = 0;
10820 } else {
10821 volume = mMasterVolume * mStreamVolume;
10822 }
10823
10824 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010825
10826 // Convert volumes from float to 8.24
10827 uint32_t vol = (uint32_t)(volume * (1 << 24));
10828
10829 // Delegate volume control to effect in track effect chain if needed
10830 // only one effect chain can be present on DirectOutputThread, so if
10831 // there is one, the track is connected to it
10832 if (!mEffectChains.isEmpty()) {
10833 mEffectChains[0]->setVolume_l(&vol, &vol);
10834 volume = (float)vol / (1 << 24);
10835 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010836 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010837 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10838 mHalVolFloat = volume; // HW volume control worked, so update value.
10839 mNoCallbackWarningCount = 0;
10840 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010841 sp<MmapStreamCallback> callback = mCallback.promote();
10842 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010843 mHalVolFloat = volume; // SW volume control worked, so update value.
10844 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010845 mLock.unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010846 callback->onVolumeChanged(volume);
Eric Laurent734046e2018-04-16 14:50:52 -070010847 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010848 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010849 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10850 ALOGW("Could not set MMAP stream volume: no volume callback!");
10851 mNoCallbackWarningCount++;
10852 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010853 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010854 }
Andy Hung3ff4b552023-06-26 19:20:57 -070010855 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010856 track->setMetadataHasChanged();
Andy Hung2cbc2722023-07-17 17:05:00 -070010857 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010858 /*muteState=*/{mMasterMute,
10859 mStreamVolume == 0.f,
10860 mStreamMute,
10861 // TODO(b/241533526): adjust logic to include mute from AppOps
10862 false /*muteFromPlaybackRestricted*/,
10863 false /*muteFromClientVolume*/,
10864 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010865 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010866 }
10867}
10868
Andy Hung71742ab2023-07-07 13:47:37 -070010869ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070010870{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010871 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010010872 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010873 }
10874 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung3ff4b552023-06-26 19:20:57 -070010875 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070010876 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010877 playback_track_metadata_v7_t trackMetadata;
10878 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010879 .usage = track->attributes().usage,
10880 .content_type = track->attributes().content_type,
10881 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010882 };
10883 trackMetadata.channel_mask = track->channelMask(),
10884 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10885 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010886 }
10887 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010010888
10889 MetadataUpdate change;
10890 change.playbackMetadataUpdate = metadata.tracks;
10891 return change;
10892};
Kevin Rocard069c2712018-03-29 19:09:14 -070010893
Andy Hung71742ab2023-07-07 13:47:37 -070010894void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010895{
10896 if (!mMasterMute) {
10897 char value[PROPERTY_VALUE_MAX];
10898 if (property_get("ro.audio.silent", value, "0") > 0) {
10899 char *endptr;
10900 unsigned long ul = strtoul(value, &endptr, 0);
10901 if (*endptr == '\0' && ul != 0) {
10902 ALOGD("Silence is golden");
10903 // The setprop command will not allow a property to be changed after
10904 // the first time it is set, so we don't have to worry about un-muting.
10905 setMasterMute_l(true);
10906 }
10907 }
10908 }
10909}
10910
Andy Hung71742ab2023-07-07 13:47:37 -070010911void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010912{
10913 MmapThread::toAudioPortConfig(config);
10914 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10915 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10916 config->flags.output = mOutput->flags;
10917 }
10918}
10919
Andy Hung71742ab2023-07-07 13:47:37 -070010920status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung4989d312023-06-29 21:19:25 -070010921 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070010922{
10923 if (mOutput == nullptr) {
10924 return NO_INIT;
10925 }
10926 struct timespec timestamp;
10927 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10928 if (status == NO_ERROR) {
10929 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10930 }
10931 return status;
10932}
10933
Andy Hung71742ab2023-07-07 13:47:37 -070010934status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010935 // Send to MelProcessor for sound dose measurement.
10936 auto processor = mMelProcessor.load();
10937 if (processor) {
10938 processor->process(buffer, frameCount * mFrameSize);
10939 }
10940
jiabinfc791ee2023-02-15 19:43:40 +000010941 return NO_ERROR;
10942}
10943
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010944// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -070010945void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010946 const sp<audio_utils::MelProcessor>& processor)
10947{
10948 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010949 mMelProcessor.store(processor);
10950 if (processor) {
10951 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010952 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010953
10954 // no need to update output format for MMapPlaybackThread since it is
10955 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010956}
10957
10958// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -070010959void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010960{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010961 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
10962 auto melProcessor = mMelProcessor.load();
10963 if (melProcessor != nullptr) {
10964 melProcessor->pause();
10965 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010966}
10967
Andy Hung71742ab2023-07-07 13:47:37 -070010968void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010969{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010970 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010971
Glenn Kastend3bb6452016-12-05 18:14:37 -080010972 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10973 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010974 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10975}
10976
Andy Hung71742ab2023-07-07 13:47:37 -070010977/* static */
10978sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung2cbc2722023-07-17 17:05:00 -070010979 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung71742ab2023-07-07 13:47:37 -070010980 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -070010981 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -070010982}
10983
10984MmapCaptureThread::MmapCaptureThread(
Andy Hung2cbc2722023-07-17 17:05:00 -070010985 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010986 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -070010987 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010988 mInput(input)
10989{
10990 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10991 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10992}
10993
Andy Hung71742ab2023-07-07 13:47:37 -070010994status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010995{
Phil Burkf054fc32018-12-06 09:45:59 -080010996 {
10997 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080010998 if (mInput != nullptr && mInput->stream != nullptr) {
10999 mInput->stream->setGain(1.0f);
11000 }
11001 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011002 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011003}
11004
Andy Hung71742ab2023-07-07 13:47:37 -070011005AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011006{
11007 Mutex::Autolock _l(mLock);
11008 AudioStreamIn *input = mInput;
11009 mInput = NULL;
11010 return input;
11011}
Kevin Rocard069c2712018-03-29 19:09:14 -070011012
Andy Hung71742ab2023-07-07 13:47:37 -070011013void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011014{
11015 bool changed = false;
11016 bool silenced = false;
11017
11018 sp<MmapStreamCallback> callback = mCallback.promote();
11019 if (callback == 0) {
11020 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11021 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11022 mNoCallbackWarningCount++;
11023 }
11024 }
11025
11026 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11027 // track is silenced and unmute otherwise
11028 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11029 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11030 changed = true;
11031 silenced = mActiveTracks[i]->isSilenced_l();
11032 }
11033 }
11034
11035 if (changed) {
11036 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11037 }
11038}
11039
Andy Hung71742ab2023-07-07 13:47:37 -070011040ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011041{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011042 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011043 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011044 }
11045 StreamInHalInterface::SinkMetadata metadata;
Andy Hung3ff4b552023-06-26 19:20:57 -070011046 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011047 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011048 record_track_metadata_v7_t trackMetadata;
11049 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011050 .source = track->attributes().source,
11051 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011052 };
11053 trackMetadata.channel_mask = track->channelMask(),
11054 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11055 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011056 }
11057 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011058 MetadataUpdate change;
11059 change.recordMetadataUpdate = metadata.tracks;
11060 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011061}
11062
Andy Hung71742ab2023-07-07 13:47:37 -070011063void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011064{
11065 Mutex::Autolock _l(mLock);
11066 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011067 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011068 mActiveTracks[i]->setSilenced_l(silenced);
11069 broadcast_l();
11070 }
11071 }
jiabincfc10a42022-06-15 19:26:01 +000011072 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011073}
11074
Andy Hung71742ab2023-07-07 13:47:37 -070011075void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011076{
11077 MmapThread::toAudioPortConfig(config);
11078 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11079 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11080 config->flags.input = mInput->flags;
11081 }
11082}
11083
Andy Hung71742ab2023-07-07 13:47:37 -070011084status_t MmapCaptureThread::getExternalPosition(
Andy Hung4989d312023-06-29 21:19:25 -070011085 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011086{
11087 if (mInput == nullptr) {
11088 return NO_INIT;
11089 }
11090 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11091}
11092
jiabinc658e452022-10-21 20:52:21 +000011093// ----------------------------------------------------------------------------
11094
Andy Hung71742ab2023-07-07 13:47:37 -070011095/* static */
11096sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung2cbc2722023-07-17 17:05:00 -070011097 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -070011098 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -070011099 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -070011100}
11101
Andy Hung2cbc2722023-07-17 17:05:00 -070011102BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011103 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -070011104 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011105
Andy Hung71742ab2023-07-07 13:47:37 -070011106PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -070011107 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011108 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11109 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011110 float volumeLeft = 1.0f;
11111 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011112 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11113 const int trackId = mActiveTracks[0]->id();
11114 mAudioMixer->setParameter(
11115 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11116 mAudioMixer->setParameter(
11117 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11118 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011119 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011120 mIsBitPerfect = true;
11121 } else {
11122 mIsBitPerfect = false;
11123 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11124 // active.
11125 for (const auto& track : mActiveTracks) {
11126 const int trackId = track->id();
11127 mAudioMixer->setParameter(
11128 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11129 }
11130 }
jiabin76d94692022-12-15 21:51:21 +000011131 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11132 mVolumeLeft = volumeLeft;
11133 mVolumeRight = volumeRight;
11134 setVolumeForOutput_l(volumeLeft, volumeRight);
11135 }
jiabinc658e452022-10-21 20:52:21 +000011136 return result;
11137}
11138
Andy Hung71742ab2023-07-07 13:47:37 -070011139void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011140 MixerThread::threadLoop_mix();
11141 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11142}
11143
Glenn Kasten63238ef2015-03-02 15:50:29 -080011144} // namespace android