blob: 8d78ba47b5c8002f9aef0caeac4a91cfa86f0804 [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 Hungee58e4a2023-07-07 13:47:37 -070079#include "Threads.h"
80
Andy Hungab7ef302018-05-15 19:35:29 -070081#include <mediautils/SchedulingPolicyService.h>
82#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080083
Eric Laurent81784c32012-11-19 14:55:58 -080084#ifdef ADD_BATTERY_DATA
85#include <media/IMediaPlayerService.h>
86#include <media/IMediaDeathNotifier.h>
87#endif
88
Eric Laurent81784c32012-11-19 14:55:58 -080089#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070090#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080091#include <cpustats/ThreadCpuUsage.h>
92#endif
93
Andy Hungd69d9f12023-05-23 17:36:46 -070094#include <fastpath/AutoPark.h>
Glenn Kastenc05b8d72016-03-24 09:48:17 -070095
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080096#include <pthread.h>
Andy Hung0a51b5c2023-07-18 20:54:44 -070097#include <afutils/DumpTryLock.h>
Andy Hung6cd79802023-07-19 16:56:19 -070098#include <afutils/Permission.h>
Andy Hung0077d8c2023-05-24 11:53:47 -070099#include <afutils/TypedLogger.h>
Andy Hung7fb97e12023-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 Hungee58e4a2023-07-07 13:47:37 -0700128using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700129using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000130using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700131
Eric Laurent81784c32012-11-19 14:55:58 -0800132// retry counts for buffer fill timeout
133// 50 * ~20msecs = 1 second
134static const int8_t kMaxTrackRetries = 50;
135static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700136
Eric Laurent81784c32012-11-19 14:55:58 -0800137// allow less retry attempts on direct output thread.
138// direct outputs can be a scarce resource in audio hardware and should
139// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700140// Notes:
141// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
142// in case the data write is bursty for the AudioTrack. The application
143// should endeavor to write at least once every kMaxTrackRetriesDirectMs
144// to prevent an underrun situation. If the data is bursty, then
145// the application can also throttle the data sent to be even.
146// 2) For compressed audio data, any data present in the AudioTrack buffer
147// will be sent and reset the retry count. This delivers data as
148// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
149// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
150// of data to be available, then any remaining data is delivered.
151// This is required to ensure the last bit of data is delivered before underrun.
152//
153// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
154// or the size of the HAL period for proportional / linear PCM tracks.
155static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800156
157// don't warn about blocked writes or record buffer overflows more often than this
158static const nsecs_t kWarningThrottleNs = seconds(5);
159
160// RecordThread loop sleep time upon application overrun or audio HAL read error
161static const int kRecordThreadSleepUs = 5000;
162
Eric Laurent10351942014-05-08 18:49:52 -0700163// maximum time to wait in sendConfigEvent_l() for a status to be received
164static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800165
166// minimum sleep time for the mixer thread loop when tracks are active but in underrun
167static const uint32_t kMinThreadSleepTimeUs = 5000;
168// maximum divider applied to the active sleep time in the mixer thread loop
169static const uint32_t kMaxThreadSleepTimeShift = 2;
170
Andy Hung09a50072014-02-27 14:30:47 -0800171// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700172// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800173static const uint32_t kMinNormalSinkBufferSizeMs = 20;
174// maximum normal sink buffer size
175static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800176
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700177// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
178// FIXME This should be based on experimentally observed scheduling jitter
179static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
180
Eric Laurent972a1732013-09-04 09:42:59 -0700181// Offloaded output thread standby delay: allows track transition without going to standby
182static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
183
Eric Laurent51716182016-02-29 18:00:56 -0800184// Direct output thread minimum sleep time in idle or active(underrun) state
185static const nsecs_t kDirectMinSleepTimeUs = 10000;
186
Brian Lindahl65e90012022-07-27 18:01:07 +0200187// Minimum amount of time between checking to see if the timestamp is advancing
188// for underrun detection. If we check too frequently, we may not detect a
189// timestamp update and will falsely detect underrun.
190static const nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1000;
191
Glenn Kasten1b291842016-07-18 14:55:21 -0700192// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
193// balance between power consumption and latency, and allows threads to be scheduled reliably
194// by the CFS scheduler.
195// FIXME Express other hardcoded references to 20ms with references to this constant and move
196// it appropriately.
197#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800198
Eric Laurent81784c32012-11-19 14:55:58 -0800199// Whether to use fast mixer
200static const enum {
201 FastMixer_Never, // never initialize or use: for debugging only
202 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
203 // normal mixer multiplier is 1
204 FastMixer_Static, // initialize if needed, then use all the time if initialized,
205 // multiplier is calculated based on min & max normal mixer buffer size
206 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
207 // multiplier is calculated based on min & max normal mixer buffer size
208 // FIXME for FastMixer_Dynamic:
209 // Supporting this option will require fixing HALs that can't handle large writes.
210 // For example, one HAL implementation returns an error from a large write,
211 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
212 // We could either fix the HAL implementations, or provide a wrapper that breaks
213 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
214} kUseFastMixer = FastMixer_Static;
215
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700216// Whether to use fast capture
217static const enum {
218 FastCapture_Never, // never initialize or use: for debugging only
219 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
220 FastCapture_Static, // initialize if needed, then use all the time if initialized
221} kUseFastCapture = FastCapture_Static;
222
Eric Laurent81784c32012-11-19 14:55:58 -0800223// Priorities for requestPriority
224static const int kPriorityAudioApp = 2;
225static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700226static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800227
Glenn Kastenea38ee72016-04-18 11:08:01 -0700228// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
229// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
230// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700231
232// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800233static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800234
Glenn Kasten03490092014-05-27 12:30:54 -0700235// The minimum and maximum allowed values
236static const int kFastTrackMultiplierMin = 1;
237static const int kFastTrackMultiplierMax = 2;
238
239// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
240static int sFastTrackMultiplier = kFastTrackMultiplier;
241
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700242// See Thread::readOnlyHeap().
243// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
244// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
245// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700246static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700247
Andy Hung8fe87eb2023-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 Naganovf53e1822022-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 Hung920f6572022-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",
511 title.string(),
512 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 Hungee58e4a2023-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 Hung583043b2023-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 Hung583043b2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-07-07 13:47:37 -0700635status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800636{
Eric Laurent81784c32012-11-19 14:55:58 -0800637 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
638 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 Hungee58e4a2023-07-07 13:47:37 -0700645status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-07-07 13:47:37 -0700787void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-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 Hungee58e4a2023-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",
822 data->mKeyValuePairs.string());
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 Laurent68a40a82022-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 Hungee58e4a2023-07-07 13:47:37 -0700961void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-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 Hung0a51b5c2023-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 Hungee58e4a2023-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,
Marco Nelissenb2208842014-02-07 14:00:50 -08001009 channelMaskToString(mChannelMask, mType != RECORD).string());
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 Hungee58e4a2023-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 Hung116bc262023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hung116bc262023-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 Hungee58e4a2023-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 Hung116bc262023-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 Hungee58e4a2023-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 Hung116bc262023-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 Hungee58e4a2023-07-07 13:47:37 -07001329void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001330 audio_session_t sessionId,
Andy Hung920f6572022-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 Hungee58e4a2023-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 Hung116bc262023-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 Hungee58e4a2023-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 Hung116bc262023-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 Hungee58e4a2023-07-07 13:47:37 -07001554sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-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 Hung116bc262023-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 Hung116bc262023-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 Hung116bc262023-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 Hung583043b2023-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 Hung583043b2023-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 Hung583043b2023-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 Hung116bc262023-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 Hungee58e4a2023-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 Hung116bc262023-06-20 18:56:17 -07001663 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001664 {
1665 Mutex::Autolock _l(mLock);
Andy Hung116bc262023-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 Hung583043b2023-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 Hungee58e4a2023-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 Hung583043b2023-07-17 17:05:00 -07001700 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001701 }
1702 }
1703}
1704
Andy Hungee58e4a2023-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 Hungee58e4a2023-07-07 13:47:37 -07001712sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-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 Hungee58e4a2023-07-07 13:47:37 -07001719sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001720 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001721{
Andy Hung116bc262023-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 Hungee58e4a2023-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 Hung116bc262023-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 Hungee58e4a2023-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 Hung116bc262023-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 Hung116bc262023-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 Hung583043b2023-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 Hungee58e4a2023-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 Hung116bc262023-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 Hungee58e4a2023-07-07 13:47:37 -07001798void ThreadBase::lockEffectChains_l(
Andy Hung116bc262023-06-20 18:56:17 -07001799 Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-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 Hungee58e4a2023-07-07 13:47:37 -07001808void ThreadBase::unlockEffectChains(
Andy Hung116bc262023-06-20 18:56:17 -07001809 const Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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 Hungee58e4a2023-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;
1849 config->format = mFormat;
1850 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 Hungee58e4a2023-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 Hungee58e4a2023-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;
Atneya Nair166663a2023-06-27 19:16:24 -07001879 track->beginBatteryAttribution();
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 Hungee58e4a2023-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++;
Atneya Nair166663a2023-06-27 19:16:24 -07001893 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001894 // 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 Hungee58e4a2023-07-07 13:47:37 -07001904void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001905 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001906 track->endBatteryAttribution();
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();
Andy Hungdae27702016-10-31 14:01:16 -07001913}
1914
1915template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001916void ThreadBase::ActiveTracks<T>::updatePowerState(
Andy Hung920f6572022-10-06 12:09:49 -07001917 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001918 // Updates ActiveTracks client uids to the thread wakelock.
1919 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1920 thread->updateWakeLockUids_l(getWakeLockUids());
1921 mLastActiveTracksGeneration = mActiveTracksGeneration;
1922 }
Andy Hungdae27702016-10-31 14:01:16 -07001923}
Eric Laurent83b88082014-06-20 18:31:16 -07001924
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001925template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001926bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001927 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001928 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001929
1930 for (const sp<T> &track : mActiveTracks) {
1931 // Do not short-circuit as all hasChanged states must be reset
1932 // as all the metadata are going to be sent
1933 hasChanged |= track->readAndClearHasChanged();
1934 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001935 return hasChanged;
1936}
1937
1938template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001939void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001940 const char *funcName, const sp<T> &track) const {
1941 if (mLocalLog != nullptr) {
1942 String8 result;
1943 track->appendDump(result, false /* active */);
1944 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1945 }
1946}
1947
Andy Hungee58e4a2023-07-07 13:47:37 -07001948void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08001949{
1950 // Thread could be blocked waiting for async
1951 // so signal it to handle state changes immediately
1952 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1953 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1954 mSignalPending = true;
1955 mWaitWorkCV.broadcast();
1956}
1957
Andy Hungd0979812019-02-21 15:51:44 -08001958// Call only from threadLoop() or when it is idle.
1959// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07001960void ThreadBase::sendStatistics(bool force)
Andy Hungd0979812019-02-21 15:51:44 -08001961{
1962 // Do not log if we have no stats.
1963 // We choose the timestamp verifier because it is the most likely item to be present.
1964 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1965 if (nstats == 0) {
1966 return;
1967 }
1968
1969 // Don't log more frequently than once per 12 hours.
1970 // We use BOOTTIME to include suspend time.
1971 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1972 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1973 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1974 return;
1975 }
1976
1977 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1978 mLastRecordedTimeNs = timeNs;
1979
Ray Essickf27e9872019-12-07 06:28:46 -08001980 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001981
1982#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1983
1984 // thread configuration
1985 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1986 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1987 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1988 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1989 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1990 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1991 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001992 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1993 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001994
1995 // thread statistics
1996 if (mIoJitterMs.getN() > 0) {
1997 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1998 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1999 }
2000 if (mProcessTimeMs.getN() > 0) {
2001 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2002 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2003 }
2004 const auto tsjitter = mTimestampVerifier.getJitterMs();
2005 if (tsjitter.getN() > 0) {
2006 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2007 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2008 }
2009 if (mLatencyMs.getN() > 0) {
2010 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2011 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2012 }
Robert Wu06db0a32021-08-10 19:05:34 +00002013 if (mMonopipePipeDepthStats.getN() > 0) {
2014 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2015 mMonopipePipeDepthStats.getMean());
2016 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2017 mMonopipePipeDepthStats.getStdDev());
2018 }
Andy Hungd0979812019-02-21 15:51:44 -08002019
2020 item->selfrecord();
2021}
2022
Andy Hungee58e4a2023-07-07 13:47:37 -07002023product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002024{
Andy Hung583043b2023-07-17 17:05:00 -07002025 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002026 return PRODUCT_STRATEGY_NONE;
2027 }
2028 return AudioSystem::getStrategyForStream(stream);
2029}
2030
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002031// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07002032void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002033 const sp<audio_utils::MelProcessor>& /*processor*/)
2034{
2035 // Do nothing
2036 ALOGW("%s: ThreadBase does not support CSD", __func__);
2037}
2038
2039// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07002040void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002041{
2042 // Do nothing
2043 ALOGW("%s: ThreadBase does not support CSD", __func__);
2044}
2045
Eric Laurent81784c32012-11-19 14:55:58 -08002046// ----------------------------------------------------------------------------
2047// Playback
2048// ----------------------------------------------------------------------------
2049
Andy Hung583043b2023-07-17 17:05:00 -07002050PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002051 AudioStreamOut* output,
2052 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002053 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002054 bool systemReady,
2055 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002056 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002057 mNormalFrameCount(0), mSinkBuffer(NULL),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002058 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002059 mMixerBuffer(NULL),
2060 mMixerBufferSize(0),
2061 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2062 mMixerBufferValid(false),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002063 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002064 mEffectBuffer(NULL),
2065 mEffectBufferSize(0),
2066 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2067 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002068 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002069 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002070 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002071 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002072 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002073 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002074 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002075 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002076 mMixerStatus(MIXER_IDLE),
2077 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung8fe87eb2023-07-20 21:31:38 -07002078 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002079 mBytesRemaining(0),
2080 mCurrentWriteLength(0),
2081 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002082 mWriteAckSequence(0),
2083 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002084 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002085 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002086 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002087 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002088 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002089 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002090 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002091{
Glenn Kastend7dca052015-03-05 16:05:54 -08002092 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002093 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002094
2095 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2096 // it would be safer to explicitly pass initial masterVolume/masterMute as
2097 // parameter.
2098 //
2099 // If the HAL we are using has support for master volume or master mute,
2100 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2101 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002102 mMasterVolume = afThreadCallback->masterVolume_l();
2103 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002104 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002105 if (mOutput->audioHwDev->canSetMasterVolume()) {
2106 mMasterVolume = 1.0;
2107 }
2108
2109 if (mOutput->audioHwDev->canSetMasterMute()) {
2110 mMasterMute = false;
2111 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002112 mIsMsdDevice = strcmp(
2113 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002114 }
2115
Eric Laurentf1f22e72021-07-13 14:04:14 +02002116 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2117 mMixerChannelMask = mixerConfig->channel_mask;
2118 }
2119
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002120 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002121
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002122 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002123 && mMixerChannelMask != mChannelMask) {
2124 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2125 mChannelMask, mMixerChannelMask);
2126 }
2127
Andy Hungc8fddf32018-08-08 18:32:37 -07002128 // TODO: We may also match on address as well as device type for
2129 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002130 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002131 // TODO: This property should be ensure that only contains one single device type.
2132 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2133 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002134 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2135 : AUDIO_DEVICE_NONE));
2136 }
2137
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002138 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2139 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002140 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -07002141 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002142 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002143 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002144 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2145 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002146 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2147 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002148}
2149
Andy Hungee58e4a2023-07-07 13:47:37 -07002150PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002151{
Andy Hung583043b2023-07-17 17:05:00 -07002152 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002153 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002154 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002155 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002156 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002157}
2158
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002159// Thread virtuals
2160
Andy Hungee58e4a2023-07-07 13:47:37 -07002161void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002162{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002163 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002164 ALOGE("The stream is not open yet"); // This should not happen.
2165 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002166 // Callbacks take strong or weak pointers as a parameter.
2167 // Since PlaybackThread passes itself as a callback handler, it can only
2168 // be done outside of the constructor. Creating weak and especially strong
2169 // pointers to a refcounted object in its own constructor is strongly
2170 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2171 // Even if a function takes a weak pointer, it is possible that it will
2172 // need to convert it to a strong pointer down the line.
2173 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2174 mOutput->stream->setCallback(this) == OK) {
2175 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002176 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002177 }
2178
jiabinf6eb4c32020-02-25 14:06:25 -08002179 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002180 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002181 }
2182 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002183 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002184 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002185}
2186
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002187// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002188void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002189{
2190 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002191 status_t result = mOutput->stream->exit();
2192 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002193}
2194
Andy Hungee58e4a2023-07-07 13:47:37 -07002195void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002196{
Eric Laurent81784c32012-11-19 14:55:58 -08002197 String8 result;
2198
Marco Nelissenb2208842014-02-07 14:00:50 -08002199 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002200 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2201 const stream_type_t *st = &mStreamTypes[i];
2202 if (i > 0) {
2203 result.appendFormat(", ");
2204 }
2205 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2206 if (st->mute) {
2207 result.append("M");
2208 }
2209 }
2210 result.append("\n");
2211 write(fd, result.string(), result.length());
2212 result.clear();
2213
Eric Laurent81784c32012-11-19 14:55:58 -08002214 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2215 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002216 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002217 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002218
2219 size_t numtracks = mTracks.size();
2220 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002221 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002222 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002223 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002224 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002225 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002226 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002227 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002228 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002229 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002230 if (track != 0) {
2231 bool active = mActiveTracks.indexOf(track) >= 0;
2232 if (active) {
2233 numactiveseen++;
2234 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002235 result.append(prefix);
2236 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002237 }
2238 }
2239 } else {
2240 result.append("\n");
2241 }
2242 if (numactiveseen != numactive) {
2243 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002244 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002245 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002246 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002247 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002248 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002249 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002250 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002251 result.append(prefix);
2252 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002253 }
2254 }
2255 }
2256
2257 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002258}
2259
Andy Hungee58e4a2023-07-07 13:47:37 -07002260void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002261{
Andy Hung04cb8f72020-03-20 13:44:33 -07002262 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002263 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002264 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2265 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002266 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2267 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2268 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2269 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002270 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002271 dprintf(fd, " Total writes: %d\n", mNumWrites);
2272 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2273 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2274 dprintf(fd, " Suspend count: %d\n", mSuspended);
2275 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2276 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2277 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2278 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002279 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002280 AudioStreamOut *output = mOutput;
2281 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002282 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002283 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002284 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2285 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2286 if (mPipeSink.get() != nullptr) {
2287 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2288 }
2289 if (output != nullptr) {
2290 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002291 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002292 }
Eric Laurent81784c32012-11-19 14:55:58 -08002293}
2294
Eric Laurent81784c32012-11-19 14:55:58 -08002295// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07002296sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002297 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002298 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002299 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002300 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002301 audio_format_t format,
2302 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002303 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002304 size_t *pNotificationFrameCount,
2305 uint32_t notificationsPerBuffer,
2306 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002307 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002308 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002309 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002310 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002311 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002312 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002313 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002314 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002315 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002316 bool isSpatialized,
2317 bool isBitPerfect)
Eric Laurent81784c32012-11-19 14:55:58 -08002318{
Glenn Kasten74935e42013-12-19 08:56:45 -08002319 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002320 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002321 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002322 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002323 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002324 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002325 uint32_t sampleRate;
2326
2327 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2328 lStatus = BAD_VALUE;
2329 goto Exit;
2330 }
Eric Laurent21da6472017-11-09 16:29:26 -08002331
2332 if (*pSampleRate == 0) {
2333 *pSampleRate = mSampleRate;
2334 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002335 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002336
2337 // special case for FAST flag considered OK if fast mixer is present
2338 if (hasFastMixer()) {
2339 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2340 }
2341
2342 // Check if requested flags are compatible with output stream flags
2343 if ((*flags & outputFlags) != *flags) {
2344 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2345 *flags, outputFlags);
2346 *flags = (audio_output_flags_t)(*flags & outputFlags);
2347 }
Eric Laurent81784c32012-11-19 14:55:58 -08002348
jiabinc658e452022-10-21 20:52:21 +00002349 if (isBitPerfect) {
Andy Hung116bc262023-06-20 18:56:17 -07002350 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002351 if (chain.get() != nullptr) {
2352 // Bit-perfect is required according to the configuration and preferred mixer
2353 // attributes, but it is not in the output flag from the client's request. Explicitly
2354 // adding bit-perfect flag to check the compatibility
2355 audio_output_flags_t flagsToCheck =
2356 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2357 chain->checkOutputFlagCompatibility(&flagsToCheck);
2358 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2359 ALOGE("%s cannot create track as there is data-processing effect attached to "
2360 "given session id(%d)", __func__, sessionId);
2361 lStatus = BAD_VALUE;
2362 goto Exit;
2363 }
2364 *flags = flagsToCheck;
2365 }
2366 }
2367
Eric Laurent81784c32012-11-19 14:55:58 -08002368 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002369 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002370 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002371 // PCM data
2372 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002373 // TODO: extract as a data library function that checks that a computationally
2374 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002375 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002376 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2377 (channelMask == AUDIO_CHANNEL_OUT_MONO
2378 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002379 // hardware sample rate
2380 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002381 // normal mixer has an associated fast mixer
2382 hasFastMixer() &&
2383 // there are sufficient fast track slots available
2384 (mFastTrackAvailMask != 0)
2385 // FIXME test that MixerThread for this fast track has a capable output HAL
2386 // FIXME add a permission test also?
2387 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002388 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2389 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002390 // read the fast track multiplier property the first time it is needed
2391 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2392 if (ok != 0) {
2393 ALOGE("%s pthread_once failed: %d", __func__, ok);
2394 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002395 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002396 }
Eric Laurent4c415062016-06-17 16:14:16 -07002397
2398 // check compatibility with audio effects.
2399 { // scope for mLock
2400 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002401 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002402 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002403 AUDIO_SESSION_OUTPUT_STAGE,
2404 AUDIO_SESSION_OUTPUT_MIX,
2405 sessionId,
2406 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002407 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002408 if (chain.get() != nullptr) {
2409 audio_output_flags_t old = *flags;
2410 chain->checkOutputFlagCompatibility(flags);
2411 if (old != *flags) {
2412 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2413 (int)session, (int)old, (int)*flags);
2414 }
Eric Laurent4c415062016-06-17 16:14:16 -07002415 }
2416 }
2417 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002418 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002419 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2420 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002421 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002422 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002423 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002424 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002425 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002426 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002427 audio_is_linear_pcm(format), channelMask, sampleRate,
2428 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002429 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002430 }
2431 }
Eric Laurent21da6472017-11-09 16:29:26 -08002432
2433 if (!audio_has_proportional_frames(format)) {
2434 if (sharedBuffer != 0) {
2435 // Same comment as below about ignoring frameCount parameter for set()
2436 frameCount = sharedBuffer->size();
2437 } else if (frameCount == 0) {
2438 frameCount = mNormalFrameCount;
2439 }
2440 if (notificationFrameCount != frameCount) {
2441 notificationFrameCount = frameCount;
2442 }
2443 } else if (sharedBuffer != 0) {
2444 // FIXME: Ensure client side memory buffers need
2445 // not have additional alignment beyond sample
2446 // (e.g. 16 bit stereo accessed as 32 bit frame).
2447 size_t alignment = audio_bytes_per_sample(format);
2448 if (alignment & 1) {
2449 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2450 alignment = 1;
2451 }
2452 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2453 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2454 if (channelCount > 1) {
2455 // More than 2 channels does not require stronger alignment than stereo
2456 alignment <<= 1;
2457 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002458 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002459 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002460 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002461 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002462 goto Exit;
2463 }
Eric Laurent21da6472017-11-09 16:29:26 -08002464
2465 // When initializing a shared buffer AudioTrack via constructors,
2466 // there's no frameCount parameter.
2467 // But when initializing a shared buffer AudioTrack via set(),
2468 // there _is_ a frameCount parameter. We silently ignore it.
2469 frameCount = sharedBuffer->size() / frameSize;
2470 } else {
2471 size_t minFrameCount = 0;
2472 // For fast tracks we try to respect the application's request for notifications per buffer.
2473 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2474 if (notificationsPerBuffer > 0) {
2475 // Avoid possible arithmetic overflow during multiplication.
2476 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2477 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2478 notificationsPerBuffer, mFrameCount);
2479 } else {
2480 minFrameCount = mFrameCount * notificationsPerBuffer;
2481 }
2482 }
2483 } else {
2484 // For normal PCM streaming tracks, update minimum frame count.
2485 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2486 // cover audio hardware latency.
2487 // This is probably too conservative, but legacy application code may depend on it.
2488 // If you change this calculation, also review the start threshold which is related.
2489 uint32_t latencyMs = latency_l();
2490 if (latencyMs == 0) {
2491 ALOGE("Error when retrieving output stream latency");
2492 lStatus = UNKNOWN_ERROR;
2493 goto Exit;
2494 }
2495
2496 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2497 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2498
Eric Laurent81784c32012-11-19 14:55:58 -08002499 }
Eric Laurent21da6472017-11-09 16:29:26 -08002500 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002501 frameCount = minFrameCount;
2502 }
Eric Laurent81784c32012-11-19 14:55:58 -08002503 }
Eric Laurent21da6472017-11-09 16:29:26 -08002504
2505 // Make sure that application is notified with sufficient margin before underrun.
2506 // The client can divide the AudioTrack buffer into sub-buffers,
2507 // and expresses its desire to server as the notification frame count.
2508 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2509 size_t maxNotificationFrames;
2510 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2511 // notify every HAL buffer, regardless of the size of the track buffer
2512 maxNotificationFrames = mFrameCount;
2513 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002514 // Triple buffer the notification period for a triple buffered mixer period;
2515 // otherwise, double buffering for the notification period is fine.
2516 //
2517 // TODO: This should be moved to AudioTrack to modify the notification period
2518 // on AudioTrack::setBufferSizeInFrames() changes.
2519 const int nBuffering =
2520 (uint64_t{frameCount} * mSampleRate)
2521 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2522
Eric Laurent21da6472017-11-09 16:29:26 -08002523 maxNotificationFrames = frameCount / nBuffering;
2524 // If client requested a fast track but this was denied, then use the smaller maximum.
2525 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2526 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2527 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2528 maxNotificationFrames = maxNotificationFramesFastDenied;
2529 }
2530 }
2531 }
2532 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2533 if (notificationFrameCount == 0) {
2534 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2535 maxNotificationFrames, frameCount);
2536 } else {
2537 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2538 notificationFrameCount, maxNotificationFrames, frameCount);
2539 }
2540 notificationFrameCount = maxNotificationFrames;
2541 }
2542 }
2543
Glenn Kasten74935e42013-12-19 08:56:45 -08002544 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002545 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002546
Glenn Kastenc3df8382014-03-13 15:05:25 -07002547 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002548 case BIT_PERFECT:
2549 if (isBitPerfect) {
2550 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2551 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2552 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2553 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2554 mChannelMask);
2555 lStatus = BAD_VALUE;
2556 goto Exit;
2557 }
2558 }
2559 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002560
2561 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002562 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002563 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002564 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2565 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002566 sampleRate, format, channelMask, mOutput, mFormat);
2567 lStatus = BAD_VALUE;
2568 goto Exit;
2569 }
2570 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002571 break;
2572
2573 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002574 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002575 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2576 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002577 sampleRate, format, channelMask, mOutput, mFormat);
2578 lStatus = BAD_VALUE;
2579 goto Exit;
2580 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002581 break;
2582
2583 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002584 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002585 ALOGE("createTrack_l() Bad parameter: format %#x \""
2586 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002587 format, mOutput, mFormat);
2588 lStatus = BAD_VALUE;
2589 goto Exit;
2590 }
Andy Hungcd044842014-08-07 11:04:34 -07002591 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002592 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2593 lStatus = BAD_VALUE;
2594 goto Exit;
2595 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002596 break;
2597
Eric Laurent81784c32012-11-19 14:55:58 -08002598 }
2599
2600 lStatus = initCheck();
2601 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002602 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002603 goto Exit;
2604 }
2605
2606 { // scope for mLock
2607 Mutex::Autolock _l(mLock);
2608
2609 // all tracks in same audio session must share the same routing strategy otherwise
2610 // conflicts will happen when tracks are moved from one output to another by audio policy
2611 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002612 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002613 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002614 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002615 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002616 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002617 if (sessionId == t->sessionId() && strategy != actual) {
2618 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2619 strategy, actual);
2620 lStatus = BAD_VALUE;
2621 goto Exit;
2622 }
2623 }
2624 }
2625
yucliuc9c49cd2020-07-13 16:25:21 -07002626 // Set DIRECT flag if current thread is DirectOutputThread. This can
2627 // happen when the playback is rerouted to direct output thread by
2628 // dynamic audio policy.
2629 // Do NOT report the flag changes back to client, since the client
2630 // doesn't explicitly request a direct flag.
2631 audio_output_flags_t trackFlags = *flags;
2632 if (mType == DIRECT) {
2633 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2634 }
2635
Andy Hung8d31fd22023-06-26 19:20:57 -07002636 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002637 channelMask, frameCount,
2638 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002639 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002640 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002641 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002642
Glenn Kasten03003332013-08-06 15:40:54 -07002643 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2644 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002645 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002646 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002647 goto Exit;
2648 }
2649 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002650 {
2651 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2652 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002653 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002654 }
2655 }
Eric Laurent81784c32012-11-19 14:55:58 -08002656
Andy Hung116bc262023-06-20 18:56:17 -07002657 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002658 if (chain != 0) {
2659 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2660 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002661 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002662 chain->incTrackCnt();
2663 }
2664
Eric Laurent05067782016-06-01 18:27:28 -07002665 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002666 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2667 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2668 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002669 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002670 }
2671 }
2672
2673 lStatus = NO_ERROR;
2674
2675Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002676 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002677 return track;
2678}
2679
Andy Hung1bc088a2018-02-09 15:57:31 -08002680template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002681ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002682{
Andy Hungc0691382018-09-12 18:01:57 -07002683 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002684 const ssize_t index = mTracks.remove(track);
2685 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002686 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002687 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002688 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002689 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002690 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002691 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002692 }
2693 return index;
2694}
2695
Andy Hungee58e4a2023-07-07 13:47:37 -07002696uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002697{
2698 return latency;
2699}
2700
Andy Hungee58e4a2023-07-07 13:47:37 -07002701uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002702{
2703 Mutex::Autolock _l(mLock);
2704 return latency_l();
2705}
Andy Hungee58e4a2023-07-07 13:47:37 -07002706uint32_t PlaybackThread::latency_l() const
Eric Laurent81784c32012-11-19 14:55:58 -08002707{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002708 uint32_t latency;
2709 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2710 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002711 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002712 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002713}
2714
Andy Hungee58e4a2023-07-07 13:47:37 -07002715void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002716{
2717 Mutex::Autolock _l(mLock);
2718 // Don't apply master volume in SW if our HAL can do it for us.
2719 if (mOutput && mOutput->audioHwDev &&
2720 mOutput->audioHwDev->canSetMasterVolume()) {
2721 mMasterVolume = 1.0;
2722 } else {
2723 mMasterVolume = value;
2724 }
2725}
2726
Andy Hungee58e4a2023-07-07 13:47:37 -07002727void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002728{
2729 mMasterBalance.store(balance);
2730}
2731
Andy Hungee58e4a2023-07-07 13:47:37 -07002732void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002733{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002734 if (isDuplicating()) {
2735 return;
2736 }
Eric Laurent81784c32012-11-19 14:55:58 -08002737 Mutex::Autolock _l(mLock);
2738 // Don't apply master mute in SW if our HAL can do it for us.
2739 if (mOutput && mOutput->audioHwDev &&
2740 mOutput->audioHwDev->canSetMasterMute()) {
2741 mMasterMute = false;
2742 } else {
2743 mMasterMute = muted;
2744 }
2745}
2746
Andy Hungee58e4a2023-07-07 13:47:37 -07002747void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002748{
2749 Mutex::Autolock _l(mLock);
2750 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002751 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002752}
2753
Andy Hungee58e4a2023-07-07 13:47:37 -07002754void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002755{
2756 Mutex::Autolock _l(mLock);
2757 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002758 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002759}
2760
Andy Hungee58e4a2023-07-07 13:47:37 -07002761float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002762{
2763 Mutex::Autolock _l(mLock);
2764 return mStreamTypes[stream].volume;
2765}
2766
Andy Hungee58e4a2023-07-07 13:47:37 -07002767void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002768{
2769 mOutput->stream->setVolume(left, right);
2770}
2771
Eric Laurent81784c32012-11-19 14:55:58 -08002772// addTrack_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07002773status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Andy Hung920f6572022-10-06 12:09:49 -07002774NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent81784c32012-11-19 14:55:58 -08002775{
2776 status_t status = ALREADY_EXISTS;
2777
Eric Laurent81784c32012-11-19 14:55:58 -08002778 if (mActiveTracks.indexOf(track) < 0) {
2779 // the track is newly added, make sure it fills up all its
2780 // buffers before playing. This is to ensure the client will
2781 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002782 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002783 IAfTrackBase::track_state state = track->state();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002784 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002785 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002786 mLock.lock();
2787 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002788 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002789 if (status == NO_ERROR) {
2790 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002791 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002792 mLock.lock();
2793 }
2794 return INVALID_OPERATION;
2795 }
2796 // abort if start is rejected by audio policy manager
2797 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002798 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2799 // current playback thread is reopened, which may happen when clients set preferred
2800 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2801 // immediately.
2802 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002803 }
2804#ifdef ADD_BATTERY_DATA
2805 // to track the speaker usage
2806 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2807#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002808 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002809 }
2810
Eric Laurent51716182016-02-29 18:00:56 -08002811 // set retry count for buffer fill
2812 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002813 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002814 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002815 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002816 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002817 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002818 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002819 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002820 track->retryCount() = kMaxTrackStartupRetries;
2821 track->fillingStatus() =
2822 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002823 }
2824
Andy Hung116bc262023-06-20 18:56:17 -07002825 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002826 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2827 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2828 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002829 // Unlock due to VibratorService will lock for this call and will
2830 // call Tracks.mute/unmute which also require thread's lock.
2831 mLock.unlock();
Andy Hung7fb97e12023-07-20 21:23:42 -07002832 const os::HapticScale intensity = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002833 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002834 std::optional<media::AudioVibratorInfo> vibratorInfo;
2835 {
2836 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2837 // used to play this track.
Andy Hung583043b2023-07-17 17:05:00 -07002838 Mutex::Autolock _l(mAfThreadCallback->mutex());
2839 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002840 }
jiabin57303cc2018-12-18 15:45:57 -08002841 mLock.lock();
Simon Bowden62823412022-10-17 14:52:26 +00002842 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002843 if (vibratorInfo) {
2844 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2845 }
2846
jiabin57303cc2018-12-18 15:45:57 -08002847 // Haptic playback should be enabled by vibrator service.
2848 if (track->getHapticPlaybackEnabled()) {
2849 // Disable haptic playback of all active track to ensure only
2850 // one track playing haptic if current track should play haptic.
2851 for (const auto &t : mActiveTracks) {
2852 t->setHapticPlaybackEnabled(false);
2853 }
jiabin245cdd92018-12-07 17:55:15 -08002854 }
jiabine70bc7f2020-06-30 22:07:55 -07002855
2856 // Set haptic intensity for effect
2857 if (chain != nullptr) {
2858 chain->setHapticIntensity_l(track->id(), intensity);
2859 }
jiabin245cdd92018-12-07 17:55:15 -08002860 }
2861
Andy Hung8d31fd22023-06-26 19:20:57 -07002862 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002863 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002864 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002865 if (chain != 0) {
2866 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2867 track->sessionId());
2868 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002869 }
2870
Andy Hungc2b11cb2020-04-22 09:04:01 -07002871 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002872 status = NO_ERROR;
2873 }
2874
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002875 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002876 return status;
2877}
2878
Andy Hungee58e4a2023-07-07 13:47:37 -07002879bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002880{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002881 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002882 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002883 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07002884 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002885 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002886 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002887 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002888 if (track->isPausePending()) {
2889 track->pauseAck();
2890 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002891 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002892 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002893
2894 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002895}
2896
Andy Hungee58e4a2023-07-07 13:47:37 -07002897void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002898{
2899 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002900
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002901 String8 result;
2902 track->appendDump(result, false /* active */);
2903 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002904
Eric Laurent81784c32012-11-19 14:55:58 -08002905 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002906 {
2907 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2908 mAudioTrackCallbacks.erase(track);
2909 }
Eric Laurent81784c32012-11-19 14:55:58 -08002910 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002911 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002912 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002913 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2914 mFastTrackAvailMask |= 1 << index;
2915 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07002916 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002917 }
Andy Hung116bc262023-06-20 18:56:17 -07002918 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002919 if (chain != 0) {
2920 chain->decTrackCnt();
2921 }
2922}
2923
Andy Hungee58e4a2023-07-07 13:47:37 -07002924String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08002925{
Eric Laurent81784c32012-11-19 14:55:58 -08002926 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002927 String8 out_s8;
2928 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2929 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002930 }
Andy Hung920f6572022-10-06 12:09:49 -07002931 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08002932}
2933
Andy Hungee58e4a2023-07-07 13:47:37 -07002934status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002935 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002936 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002937 return NO_INIT;
2938 }
2939 return mOutput->stream->selectPresentation(presentationId, programId);
2940}
2941
Andy Hungee58e4a2023-07-07 13:47:37 -07002942void PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002943 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002944 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07002945 sp<AudioIoDescriptor> desc;
2946 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002947 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002948 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002949 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002950 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002951 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
2952 mSampleRate, mFormat, mChannelMask,
2953 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
2954 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08002955 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002956 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002957 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07002958 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002959 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002960 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002961 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08002962 break;
2963 }
Andy Hung583043b2023-07-17 17:05:00 -07002964 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002965}
2966
Andy Hungee58e4a2023-07-07 13:47:37 -07002967void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002968{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002969 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002970}
2971
Andy Hungee58e4a2023-07-07 13:47:37 -07002972void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002973{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002974 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002975}
2976
Andy Hungee58e4a2023-07-07 13:47:37 -07002977void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002978{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002979 mCallbackThread->setAsyncError();
2980}
2981
Andy Hungee58e4a2023-07-07 13:47:37 -07002982void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08002983 const std::basic_string<uint8_t>& metadataBs)
2984{
Andy Hungee58e4a2023-07-07 13:47:37 -07002985 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08002986 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07002987 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08002988 if (playbackThread == nullptr) {
2989 ALOGW("PlaybackThread was destroyed, skip codec format change event");
2990 return;
2991 }
2992
jiabinf6eb4c32020-02-25 14:06:25 -08002993 audio_utils::metadata::Data metadata =
2994 audio_utils::metadata::dataFromByteString(metadataBs);
2995 if (metadata.empty()) {
2996 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2997 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2998 (int)metadataBs.size());
2999 return;
3000 }
3001
3002 audio_utils::metadata::ByteString metaDataStr =
3003 audio_utils::metadata::byteStringFromData(metadata);
3004 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
3005 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07003006 for (const auto& callbackPair : mAudioTrackCallbacks) {
3007 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003008 }
3009 }).detach();
3010}
3011
Andy Hungee58e4a2023-07-07 13:47:37 -07003012void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003013{
3014 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003015 // reject out of sequence requests
3016 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3017 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003018 mWaitWorkCV.signal();
3019 }
3020}
3021
Andy Hungee58e4a2023-07-07 13:47:37 -07003022void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003023{
3024 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003025 // reject out of sequence requests
3026 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003027 // Register discontinuity when HW drain is completed because that can cause
3028 // the timestamp frame position to reset to 0 for direct and offload threads.
3029 // (Out of sequence requests are ignored, since the discontinuity would be handled
3030 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003031 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003032 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003033 mWaitWorkCV.signal();
3034 }
3035}
3036
Andy Hungee58e4a2023-07-07 13:47:37 -07003037void PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003038{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003039 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003040 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3041 mSampleRate = audioConfig.sample_rate;
3042 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003043 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003044 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003045 }
Andy Hungee58e4a2023-07-07 13:47:37 -07003046 if (hasMixer() && !AudioFlinger::isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003047 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3048 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003049 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003050
3051 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3052 mMixerChannelMask = mChannelMask;
3053 }
3054
Andy Hunge5412692014-05-16 11:25:07 -07003055 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003056 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003057
Eric Laurentf1f22e72021-07-13 14:04:14 +02003058 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3059
Phil Burkca5e6142015-07-14 09:42:29 -07003060 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003061 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003062 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003063 // Get format from the shim, which will be different than the HAL format
3064 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003065 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003066 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003067 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003068 }
Andy Hungee58e4a2023-07-07 13:47:37 -07003069 if (hasMixer() && !AudioFlinger::isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003070 LOG_FATAL("HAL format %#x not supported for mixed output",
3071 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003072 }
Phil Burk062e67a2015-02-11 13:40:50 -08003073 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003074 result = mOutput->stream->getBufferSize(&mBufferSize);
3075 LOG_ALWAYS_FATAL_IF(result != OK,
3076 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003077 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003078 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003079 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003080 mFrameCount);
3081 }
3082
Eric Laurentd1f69b02014-12-15 14:33:13 -08003083 mHwSupportsPause = false;
3084 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003085 bool supportsPause = false, supportsResume = false;
3086 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3087 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003088 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003089 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003090 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003091 } else if (supportsResume) {
3092 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003093 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003094 }
3095 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003096 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3097 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3098 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003099
Andy Hungfbfc3952015-01-15 13:33:51 -08003100 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3101 // For best precision, we use float instead of the associated output
3102 // device format (typically PCM 16 bit).
3103
3104 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3105 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3106 mBufferSize = mFrameSize * mFrameCount;
3107
3108 // TODO: We currently use the associated output device channel mask and sample rate.
3109 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3110 // (if a valid mask) to avoid premature downmix.
3111 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3112 // instead of the output device sample rate to avoid loss of high frequency information.
3113 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3114 }
3115
Andy Hung09a50072014-02-27 14:30:47 -08003116 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003117 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003118 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003119 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3120 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003121 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3122 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003123
Eric Laurent81784c32012-11-19 14:55:58 -08003124 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3125 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3126 maxNormalFrameCount = maxNormalFrameCount & ~15;
3127 if (maxNormalFrameCount < minNormalFrameCount) {
3128 maxNormalFrameCount = minNormalFrameCount;
3129 }
3130 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3131 if (multiplier <= 1.0) {
3132 multiplier = 1.0;
3133 } else if (multiplier <= 2.0) {
3134 if (2 * mFrameCount <= maxNormalFrameCount) {
3135 multiplier = 2.0;
3136 } else {
3137 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3138 }
3139 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003140 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003141 }
3142 }
3143 mNormalFrameCount = multiplier * mFrameCount;
3144 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003145 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003146 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3147 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003148 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003149 mNormalFrameCount);
3150
Andy Hung08fb1742015-05-31 23:22:10 -07003151 // Check if we want to throttle the processing to no more than 2x normal rate
3152 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003153 mThreadThrottleTimeMs = 0;
3154 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003155 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3156
Andy Hung010a1a12014-03-13 13:57:33 -07003157 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3158 // Originally this was int16_t[] array, need to remove legacy implications.
3159 free(mSinkBuffer);
3160 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003161
Andy Hung5b10a202014-03-13 13:59:29 -07003162 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3163 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3164 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003165 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003166
Andy Hung69aed5f2014-02-25 17:24:40 -08003167 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3168 // drives the output.
3169 free(mMixerBuffer);
3170 mMixerBuffer = NULL;
3171 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003172 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003173 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003174 * audio_bytes_per_sample(mMixerBufferFormat);
3175 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3176 }
Andy Hung98ef9782014-03-04 14:46:50 -08003177 free(mEffectBuffer);
3178 mEffectBuffer = NULL;
3179 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003180 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003181 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003182 * audio_bytes_per_sample(mEffectBufferFormat);
3183 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3184 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003185
Eric Laurentb62d0362021-10-26 17:40:18 +02003186 if (mType == SPATIALIZER) {
3187 free(mPostSpatializerBuffer);
3188 mPostSpatializerBuffer = nullptr;
3189 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3190 * audio_bytes_per_sample(mEffectBufferFormat);
3191 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3192 }
3193
Mikhail Naganov55773032020-10-01 15:08:13 -07003194 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3195 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003196 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3197 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003198 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003199
Eric Laurent81784c32012-11-19 14:55:58 -08003200 // force reconfiguration of effect chains and engines to take new buffer size and audio
3201 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003202 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003203 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3204 // matter.
3205 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003206 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003207 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung583043b2023-07-17 17:05:00 -07003208 mAfThreadCallback->moveEffectChain_l(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003209 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003210 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003211
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003212 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003213 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003214 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3215 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3216 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3217 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3218 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3219 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3220 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3221 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3222 (int32_t)mHapticChannelMask)
3223 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3224 (int32_t)mHapticChannelCount)
3225 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3226 formatToString(mHALFormat).c_str())
3227 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3228 (int32_t)mFrameCount) // sic - added HAL
3229 ;
3230 uint32_t latencyMs;
3231 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3232 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3233 }
3234 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003235}
3236
Andy Hungee58e4a2023-07-07 13:47:37 -07003237ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003238{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003239 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003240 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003241 }
3242 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003243 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07003244 for (const sp<IAfTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -07003245 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003246 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003247 }
Kevin Rocard12381092018-04-11 09:19:59 -07003248 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003249 MetadataUpdate change;
3250 change.playbackMetadataUpdate = metadata.tracks;
3251 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003252}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003253
Andy Hungee58e4a2023-07-07 13:47:37 -07003254void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003255 const StreamOutHalInterface::SourceMetadata& metadata)
3256{
3257 mOutput->stream->updateSourceMetadata(metadata);
3258};
3259
Andy Hungee58e4a2023-07-07 13:47:37 -07003260status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003261 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003262{
3263 if (halFrames == NULL || dspFrames == NULL) {
3264 return BAD_VALUE;
3265 }
3266 Mutex::Autolock _l(mLock);
3267 if (initCheck() != NO_ERROR) {
3268 return INVALID_OPERATION;
3269 }
Andy Hung818e7a32016-02-16 18:08:07 -08003270 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003271 *halFrames = framesWritten;
3272
3273 if (isSuspended()) {
3274 // return an estimation of rendered frames when the output is suspended
3275 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003276 *dspFrames = (uint32_t)
3277 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003278 return NO_ERROR;
3279 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003280 status_t status;
3281 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003282 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003283 *dspFrames = (size_t)frames;
3284 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003285 }
3286}
3287
Andy Hungee58e4a2023-07-07 13:47:37 -07003288product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003289{
3290 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3291 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3292 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003293 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003294 }
3295 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003296 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003297 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003298 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003299 }
3300 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003301 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003302}
3303
3304
Andy Hungee58e4a2023-07-07 13:47:37 -07003305AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003306{
3307 Mutex::Autolock _l(mLock);
3308 return mOutput;
3309}
3310
Andy Hungee58e4a2023-07-07 13:47:37 -07003311AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003312{
3313 Mutex::Autolock _l(mLock);
3314 AudioStreamOut *output = mOutput;
3315 mOutput = NULL;
3316 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3317 // must push a NULL and wait for ack
3318 mOutputSink.clear();
3319 mPipeSink.clear();
3320 mNormalSink.clear();
3321 return output;
3322}
3323
3324// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003325sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003326{
3327 if (mOutput == NULL) {
3328 return NULL;
3329 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003330 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003331}
3332
Andy Hungee58e4a2023-07-07 13:47:37 -07003333uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003334{
3335 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3336}
3337
Andy Hungee58e4a2023-07-07 13:47:37 -07003338status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003339{
3340 if (!isValidSyncEvent(event)) {
3341 return BAD_VALUE;
3342 }
3343
3344 Mutex::Autolock _l(mLock);
3345
3346 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003347 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003348 if (event->triggerSession() == track->sessionId()) {
3349 (void) track->setSyncEvent(event);
3350 return NO_ERROR;
3351 }
3352 }
3353
3354 return NAME_NOT_FOUND;
3355}
3356
Andy Hungee58e4a2023-07-07 13:47:37 -07003357bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003358{
3359 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3360}
3361
Andy Hungee58e4a2023-07-07 13:47:37 -07003362void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003363 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003364{
Andy Hungfe726a62018-09-27 15:17:25 -07003365 // Miscellaneous track cleanup when removed from the active list,
3366 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003367#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003368 for (const auto& track : tracksToRemove) {
3369 if (track->isExternalTrack()) {
3370 // to track the speaker usage
3371 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003372 }
3373 }
Andy Hungfe726a62018-09-27 15:17:25 -07003374#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003375}
3376
Andy Hungee58e4a2023-07-07 13:47:37 -07003377void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003378{
3379 if (!mMasterMute) {
3380 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003381 if (mOutDeviceTypeAddrs.empty()) {
3382 ALOGD("ro.audio.silent is ignored since no output device is set");
3383 return;
3384 }
jiabinc52b1ff2019-10-31 17:20:42 -07003385 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003386 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3387 return;
3388 }
Eric Laurent81784c32012-11-19 14:55:58 -08003389 if (property_get("ro.audio.silent", value, "0") > 0) {
3390 char *endptr;
3391 unsigned long ul = strtoul(value, &endptr, 0);
3392 if (*endptr == '\0' && ul != 0) {
3393 ALOGD("Silence is golden");
3394 // The setprop command will not allow a property to be changed after
3395 // the first time it is set, so we don't have to worry about un-muting.
3396 setMasterMute_l(true);
3397 }
3398 }
3399 }
3400}
3401
3402// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003403ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003404{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003405 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003406 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003407 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003408 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003409
3410 // If an NBAIO sink is present, use it to write the normal mixer's submix
3411 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003412
Andy Hung010a1a12014-03-13 13:57:33 -07003413 const size_t count = mBytesRemaining / mFrameSize;
3414
Simon Wilson2d590962012-11-29 15:18:50 -08003415 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003416 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003417 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003418 if (screenState != mScreenState) {
3419 mScreenState = screenState;
3420 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3421 if (pipe != NULL) {
3422 pipe->setAvgFrames((mScreenState & 1) ?
3423 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3424 }
3425 }
Andy Hung010a1a12014-03-13 13:57:33 -07003426 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003427 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003428
Eric Laurent81784c32012-11-19 14:55:58 -08003429 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003430 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003431
Andy Hung8946a282018-04-19 20:04:56 -07003432#ifdef TEE_SINK
3433 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3434#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003435 } else {
3436 bytesWritten = framesWritten;
3437 }
3438 // otherwise use the HAL / AudioStreamOut directly
3439 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003440 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003441
Eric Laurentbfb1b832013-01-07 09:53:42 -08003442 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003443 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3444 mWriteAckSequence += 2;
3445 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003446 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003447 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003448 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003449 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003450 // FIXME We should have an implementation of timestamps for direct output threads.
3451 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003452 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003453 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003454
Eric Laurentbfb1b832013-01-07 09:53:42 -08003455 if (mUseAsyncWrite &&
3456 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3457 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003458 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003459 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003460 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003461 }
Eric Laurent81784c32012-11-19 14:55:58 -08003462 }
3463
Eric Laurent81784c32012-11-19 14:55:58 -08003464 mNumWrites++;
3465 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003466 if (mStandby) {
3467 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003468 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003469 mStandby = false;
3470 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003471 return bytesWritten;
3472}
3473
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003474// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07003475void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003476 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003477{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003478 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003479 if (outputSink != nullptr) {
3480 outputSink->startMelComputation(processor);
3481 }
Vlad Popab042ee62022-10-20 18:05:00 +02003482}
3483
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003484// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07003485void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003486{
3487 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003488 if (outputSink != nullptr) {
3489 outputSink->stopMelComputation();
3490 }
Vlad Popab042ee62022-10-20 18:05:00 +02003491}
3492
Andy Hungee58e4a2023-07-07 13:47:37 -07003493void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003494{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003495 bool supportsDrain = false;
3496 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003497 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3498 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003499 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3500 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003501 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003502 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003503 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003504 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003505 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003506 }
3507}
3508
Andy Hungee58e4a2023-07-07 13:47:37 -07003509void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003510{
Eric Laurent275e8e92014-11-30 15:14:47 -08003511 {
3512 Mutex::Autolock _l(mLock);
3513 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003514 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003515 track->invalidate();
3516 }
Andy Hungdae27702016-10-31 14:01:16 -07003517 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3518 // After we exit there are no more track changes sent to BatteryNotifier
3519 // because that requires an active threadLoop.
3520 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3521 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003522 }
Eric Laurent81784c32012-11-19 14:55:58 -08003523}
3524
3525/*
3526The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003527 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003528 - mActiveSleepTimeUs from activeSleepTimeUs()
3529 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003530 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3531 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003532 - maxPeriod from frame count and sample rate (MIXER only)
3533
3534The parameters that affect these derived values are:
3535 - frame count
3536 - frame size
3537 - sample rate
3538 - device type: A2DP or not
3539 - device latency
3540 - format: PCM or not
3541 - active sleep time
3542 - idle sleep time
3543*/
3544
Andy Hungee58e4a2023-07-07 13:47:37 -07003545void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003546{
Andy Hung25c2dac2014-02-27 14:56:00 -08003547 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003548 mActiveSleepTimeUs = activeSleepTimeUs();
3549 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003550
Andy Hung8fe87eb2023-07-20 21:31:38 -07003551 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003552
Eric Laurent42537be2016-01-08 17:16:42 -08003553 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3554 // truncating audio when going to standby.
jiabinc52b1ff2019-10-31 17:20:42 -07003555 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003556 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3557 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3558 }
3559 }
Eric Laurent81784c32012-11-19 14:55:58 -08003560}
3561
Andy Hungee58e4a2023-07-07 13:47:37 -07003562bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003563{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003564 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003565 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003566 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003567 size_t size = mTracks.size();
3568 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003569 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003570 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003571 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003572 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003573 }
3574 }
Eric Laurent13084622016-05-17 10:51:49 -07003575 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003576}
3577
Andy Hungee58e4a2023-07-07 13:47:37 -07003578void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003579{
3580 Mutex::Autolock _l(mLock);
3581 invalidateTracks_l(streamType);
3582}
3583
Andy Hungee58e4a2023-07-07 13:47:37 -07003584void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003585 Mutex::Autolock _l(mLock);
3586 invalidateTracks_l(portIds);
3587}
3588
Andy Hungee58e4a2023-07-07 13:47:37 -07003589bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003590 bool trackMatch = false;
3591 const size_t size = mTracks.size();
3592 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003593 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003594 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3595 t->invalidate();
3596 portIds.erase(t->portId());
3597 trackMatch = true;
3598 }
3599 if (portIds.empty()) {
3600 break;
3601 }
3602 }
3603 return trackMatch;
3604}
3605
jiabinf042b9b2021-05-07 23:46:28 +00003606// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003607IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003608 audio_port_handle_t trackPortId) {
3609 for (size_t i = 0; i < mTracks.size(); i++) {
3610 if (mTracks[i]->portId() == trackPortId) {
3611 return mTracks[i].get();
3612 }
3613 }
3614 return nullptr;
3615}
3616
Andy Hungee58e4a2023-07-07 13:47:37 -07003617status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003618{
Glenn Kastend848eb42016-03-08 13:42:11 -08003619 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003620 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003621 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003622
Andy Hungd3639922022-04-28 18:00:49 -07003623 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003624 if (!audio_is_global_session(session)) {
3625 // player sessions on a spatializer output will use a dedicated input buffer and
3626 // will either output multi channel to mEffectBuffer if the track is spatilaized
3627 // or stereo to mPostSpatializerBuffer if not spatialized.
3628 uint32_t channelMask;
3629 bool isSessionSpatialized =
3630 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3631 if (isSessionSpatialized) {
3632 channelMask = mMixerChannelMask;
3633 } else {
3634 channelMask = mChannelMask;
3635 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003636 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003637 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003638 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003639 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003640 &halInBuffer);
3641 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003642
Andy Hung583043b2023-07-17 17:05:00 -07003643 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003644 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3645 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3646 &halOutBuffer);
3647 if (result != OK) return result;
3648
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003649 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003650
Mikhail Naganov022b9952017-01-04 16:36:51 -08003651 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3652 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003653 } else {
3654 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3655 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3656 // mPostSpatializerBuffer as output buffer
3657 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung583043b2023-07-17 17:05:00 -07003658 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003659 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3660 if (result != OK) return result;
Andy Hung583043b2023-07-17 17:05:00 -07003661 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003662 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3663 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003664
Eric Laurentb62d0362021-10-26 17:40:18 +02003665 if (session == AUDIO_SESSION_DEVICE) {
3666 halInBuffer = halOutBuffer;
3667 }
3668 }
3669 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003670 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003671 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3672 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3673 &halInBuffer);
3674 if (result != OK) return result;
3675 halOutBuffer = halInBuffer;
3676 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3677 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003678 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003679 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003680 // Only one effect chain can be present in direct output thread and it uses
3681 // the sink buffer as input
3682 if (mType != DIRECT) {
3683 size_t numSamples = mNormalFrameCount
3684 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3685 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003686 const status_t allocateStatus =
3687 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003688 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003689 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003690 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003691
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003692 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003693 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3694 buffer, session);
3695 }
3696 }
3697 }
3698
3699 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003700 // Attach all tracks with same session ID to this chain.
3701 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003702 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003703 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003704 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3705 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003706 track->setMainBuffer(buffer);
3707 chain->incTrackCnt();
3708 }
3709 }
3710
3711 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003712 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003713 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003714 ALOGV("addEffectChain_l() activating track %p on session %d",
3715 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003716 chain->incActiveTrackCnt();
3717 }
3718 }
3719 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003720
Eric Laurentaaa44472014-09-12 17:41:50 -07003721 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003722 chain->setInBuffer(halInBuffer);
3723 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003724 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3725 // chains list in order to be processed last as it contains output device effects.
3726 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3727 // processing effects specific to an output stream before effects applied to all streams
3728 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003729 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3730 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003731 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003732 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003733 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003734 // Effect chain for other sessions are inserted at beginning of effect
3735 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003736 // sessions is not important.
3737 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003738 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3739 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003740 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003741 size_t size = mEffectChains.size();
3742 size_t i = 0;
3743 for (i = 0; i < size; i++) {
3744 if (mEffectChains[i]->sessionId() < session) {
3745 break;
3746 }
3747 }
3748 mEffectChains.insertAt(chain, i);
3749 checkSuspendOnAddEffectChain_l(chain);
3750
3751 return NO_ERROR;
3752}
3753
Andy Hungee58e4a2023-07-07 13:47:37 -07003754size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003755{
Glenn Kastend848eb42016-03-08 13:42:11 -08003756 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003757
3758 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3759
3760 for (size_t i = 0; i < mEffectChains.size(); i++) {
3761 if (chain == mEffectChains[i]) {
3762 mEffectChains.removeAt(i);
3763 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003764 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003765 if (session == track->sessionId()) {
3766 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3767 chain.get(), session);
3768 chain->decActiveTrackCnt();
3769 }
3770 }
3771
3772 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003773 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003774 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003775 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003776 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003777 chain->decTrackCnt();
3778 }
3779 }
3780 break;
3781 }
3782 }
3783 return mEffectChains.size();
3784}
3785
Andy Hungee58e4a2023-07-07 13:47:37 -07003786status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003787 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003788{
3789 Mutex::Autolock _l(mLock);
3790 return attachAuxEffect_l(track, EffectId);
3791}
3792
Andy Hungee58e4a2023-07-07 13:47:37 -07003793status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003794 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003795{
3796 status_t status = NO_ERROR;
3797
3798 if (EffectId == 0) {
3799 track->setAuxBuffer(0, NULL);
3800 } else {
3801 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003802 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003803 if (effect != 0) {
3804 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3805 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3806 } else {
3807 status = INVALID_OPERATION;
3808 }
3809 } else {
3810 status = BAD_VALUE;
3811 }
3812 }
3813 return status;
3814}
3815
Andy Hungee58e4a2023-07-07 13:47:37 -07003816void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003817{
3818 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003819 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003820 if (track->auxEffectId() == effectId) {
3821 attachAuxEffect_l(track, 0);
3822 }
3823 }
3824}
3825
Andy Hungee58e4a2023-07-07 13:47:37 -07003826bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003827NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003828{
Andy Hung78d8d952023-05-30 18:10:23 -07003829 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003830
Andy Hung8d31fd22023-06-26 19:20:57 -07003831 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003832
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003833 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003834 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003835
3836 // MIXER
3837 nsecs_t lastWarning = 0;
3838
3839 // DUPLICATING
3840 // FIXME could this be made local to while loop?
3841 writeFrames = 0;
3842
3843 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003844 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003845
Andy Hungd3639922022-04-28 18:00:49 -07003846 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003847 sleepTimeShift = 0;
3848 }
3849
3850 CpuStats cpuStats;
3851 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3852
3853 acquireWakeLock();
3854
Glenn Kasteneef598c2017-04-03 14:41:13 -07003855 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3856 // thread associated with this PlaybackThread.
3857 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3858 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003859 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3860 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003861 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003862 const char *logString = NULL;
3863
rago1bb90822017-05-02 18:31:48 -07003864 // Estimated time for next buffer to be written to hal. This is used only on
3865 // suspended mode (for now) to help schedule the wait time until next iteration.
3866 nsecs_t timeLoopNextNs = 0;
3867
Eric Laurent664539d2013-09-23 18:24:31 -07003868 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003869
Andy Hung2dbffc22018-08-08 18:50:41 -07003870 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003871
Eric Laurentb3f315a2021-07-13 15:09:05 +02003872 sendCheckOutputStageEffectsEvent();
3873
Andy Hung446f4df2019-02-21 12:26:41 -08003874 // loopCount is used for statistics and diagnostics.
3875 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003876 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003877 // Log merge requests are performed during AudioFlinger binder transactions, but
3878 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07003879 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003880
Eric Laurent81784c32012-11-19 14:55:58 -08003881 cpuStats.sample(myName);
3882
Andy Hung116bc262023-06-20 18:56:17 -07003883 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003884 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003885 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07003886 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003887
Andy Hung2dbffc22018-08-08 18:50:41 -07003888 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3889 //
jiabinc52b1ff2019-10-31 17:20:42 -07003890 // Note: we access outDeviceTypes() outside of mLock.
3891 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003892 // Here, we try for the AF lock, but do not block on it as the latency
3893 // is more informational.
Andy Hung583043b2023-07-17 17:05:00 -07003894 if (mAfThreadCallback->mutex().tryLock() == NO_ERROR) {
Andy Hungb6692eb2023-07-13 16:52:46 -07003895 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07003896 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07003897 status_t status = INVALID_OPERATION;
3898 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07003899 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07003900 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07003901 && swPatches.size() > 0) {
3902 status = swPatches[0].getLatencyMs_l(&latencyMs);
3903 downstreamPatchHandle = swPatches[0].getPatchHandle();
3904 }
3905 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003906 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003907 lastDownstreamPatchHandle = downstreamPatchHandle;
3908 }
3909 if (status == OK) {
3910 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003911 // latency of 5 seconds).
3912 const double minLatency = 0., maxLatency = 5000.;
3913 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003914 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003915 } else {
3916 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07003917 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07003918 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003919 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003920 }
Andy Hung583043b2023-07-17 17:05:00 -07003921 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07003922 }
3923 } else {
3924 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3925 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003926 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003927 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3928 }
3929 }
3930
Eric Laurentb3f315a2021-07-13 15:09:05 +02003931 if (mCheckOutputStageEffects.exchange(false)) {
3932 checkOutputStageEffects();
3933 }
3934
Vlad Popa7e81cea2023-01-19 16:34:16 +01003935 MetadataUpdate metadataUpdate;
Eric Laurent81784c32012-11-19 14:55:58 -08003936 { // scope for mLock
3937
3938 Mutex::Autolock _l(mLock);
3939
Eric Laurent021cf962014-05-13 10:18:14 -07003940 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003941 if (mCheckOutputStageEffects.load()) {
3942 continue;
3943 }
Eric Laurent10351942014-05-08 18:49:52 -07003944
Glenn Kasteneef598c2017-04-03 14:41:13 -07003945 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003946 if (logString != NULL) {
3947 mNBLogWriter->logTimestamp();
3948 mNBLogWriter->log(logString);
3949 logString = NULL;
3950 }
3951
Dean Wheatley12473e92021-03-18 23:00:55 +11003952 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003953
Eric Laurent81784c32012-11-19 14:55:58 -08003954 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003955 if (mSignalPending) {
3956 // A signal was raised while we were unlocked
3957 mSignalPending = false;
3958 } else if (waitingAsyncCallback_l()) {
3959 if (exitPending()) {
3960 break;
3961 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003962 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003963 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003964 releaseWakeLock_l();
3965 released = true;
3966 }
Andy Hung10cbff12017-02-21 17:30:14 -08003967
3968 const int64_t waitNs = computeWaitTimeNs_l();
3969 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3970 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3971 if (status == TIMED_OUT) {
3972 mSignalPending = true; // if timeout recheck everything
3973 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003974 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003975 if (released) {
3976 acquireWakeLock_l();
3977 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003978 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3979 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003980
3981 continue;
3982 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003983 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003984 isSuspended()) {
3985 // put audio hardware into standby after short delay
3986 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003987
3988 threadLoop_standby();
3989
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003990 // This is where we go into standby
3991 if (!mStandby) {
3992 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003993 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003994 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02003995 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003996 }
Andy Hungd0979812019-02-21 15:51:44 -08003997 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003998 }
3999
Eric Tan39ec8d62018-07-24 09:49:29 -07004000 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004001 // we're about to wait, flush the binder command buffer
4002 IPCThreadState::self()->flushCommands();
4003
4004 clearOutputTracks();
4005
4006 if (exitPending()) {
4007 break;
4008 }
4009
4010 releaseWakeLock_l();
4011 // wait until we have something to do...
4012 ALOGV("%s going to sleep", myName.string());
4013 mWaitWorkCV.wait(mLock);
4014 ALOGV("%s waking up", myName.string());
4015 acquireWakeLock_l();
4016
4017 mMixerStatus = MIXER_IDLE;
4018 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4019 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004020 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004021 checkSilentMode_l();
4022
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004023 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4024 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004025 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004026 sleepTimeShift = 0;
4027 }
4028
4029 continue;
4030 }
4031 }
Eric Laurent81784c32012-11-19 14:55:58 -08004032 // mMixerStatusIgnoringFastTracks is also updated internally
4033 mMixerStatus = prepareTracks_l(&tracksToRemove);
4034
Andy Hungdae27702016-10-31 14:01:16 -07004035 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004036
Vlad Popa7e81cea2023-01-19 16:34:16 +01004037 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004038
Eric Laurent81784c32012-11-19 14:55:58 -08004039 // prevent any changes in effect chain list and in each effect chain
4040 // during mixing and effect process as the audio buffers could be deleted
4041 // or modified if an effect is created or deleted
4042 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004043
4044 // Determine which session to pick up haptic data.
4045 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004046 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004047 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004048 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004049 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004050 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004051 if (effectChain != nullptr
4052 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004053 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004054 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004055 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004056 break;
4057 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004058 if (activeHapticSessionId == AUDIO_SESSION_NONE
4059 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004060 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004061 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004062 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004063 }
4064 }
4065 }
4066
Andy Hungc1646382019-04-30 16:12:10 -07004067 // Acquire a local copy of active tracks with lock (release w/o lock).
4068 //
4069 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4070 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4071 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4072 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent68a40a82022-05-03 18:15:04 +02004073
4074 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004075
Jiabin Huangfb476842022-12-06 03:18:10 +00004076 for (const auto &track : mActiveTracks ) {
jiabin7434e812023-06-27 18:22:35 +00004077 track->updateTeePatches_l();
Jiabin Huangfb476842022-12-06 03:18:10 +00004078 }
4079
Eric Laurent19952e12023-04-20 10:08:29 +02004080 // signal actual start of output stream when the render position reported by the kernel
4081 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004082 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4083 && (mKernelPositionOnStandby
4084 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004085 mHalStarted = true;
4086 mWaitHalStartCV.broadcast();
4087 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004088 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004089
Eric Laurentbfb1b832013-01-07 09:53:42 -08004090 if (mBytesRemaining == 0) {
4091 mCurrentWriteLength = 0;
4092 if (mMixerStatus == MIXER_TRACKS_READY) {
4093 // threadLoop_mix() sets mCurrentWriteLength
4094 threadLoop_mix();
4095 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4096 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004097 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004098 // must be written to HAL
4099 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004100 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004101 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004102
4103 // Tally underrun frames as we are inserting 0s here.
4104 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004105 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004106 && !track->isStopped()
4107 && !track->isPaused()
4108 && !track->isTerminated()) {
4109 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4110 __func__, track->id(), track->getTrackStateAsString(),
4111 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004112 track->audioTrackServerProxy()->tallyUnderrunFrames(
4113 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004114 }
4115 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004116 }
4117 }
Andy Hung98ef9782014-03-04 14:46:50 -08004118 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004119 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004120 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004121 // or mSinkBuffer (if there are no effects and there is no data already copied to
4122 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004123 //
4124 // This is done pre-effects computation; if effects change to
4125 // support higher precision, this needs to move.
4126 //
4127 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004128 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004129 uint32_t mixerChannelCount = mEffectBufferValid ?
4130 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004131 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004132 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4133 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4134
David Li88ee0902022-06-22 10:01:21 +08004135 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4136 // do these processes after effects are applied.
4137 if (!mEffectBufferValid) {
4138 // mono blend occurs for mixer threads only (not direct or offloaded)
4139 // and is handled here if we're going directly to the sink.
4140 if (requireMonoBlend()) {
4141 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4142 mNormalFrameCount, true /*limit*/);
4143 }
Andy Hung2ddee192015-12-18 17:34:44 -08004144
David Li88ee0902022-06-22 10:01:21 +08004145 if (!hasFastMixer()) {
4146 // Balance must take effect after mono conversion.
4147 // We do it here if there is no FastMixer.
4148 // mBalance detects zero balance within the class for speed
4149 // (not needed here).
4150 mBalance.setBalance(mMasterBalance.load());
4151 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4152 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004153 }
4154
Andy Hung98ef9782014-03-04 14:46:50 -08004155 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004156 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004157
4158 // If we're going directly to the sink and there are haptic channels,
4159 // we should adjust channels as the sample data is partially interleaved
4160 // in this case.
4161 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4162 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4163 mChannelCount + mHapticChannelCount,
4164 audio_bytes_per_sample(format),
4165 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4166 }
Andy Hung98ef9782014-03-04 14:46:50 -08004167 }
4168
Eric Laurentbfb1b832013-01-07 09:53:42 -08004169 mBytesRemaining = mCurrentWriteLength;
4170 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004171 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4172 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4173 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4174 mBytesWritten += mBytesRemaining;
4175 mFramesWritten += framesRemaining;
4176 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004177 mBytesRemaining = 0;
4178 }
Eric Laurent81784c32012-11-19 14:55:58 -08004179
Eric Laurentbfb1b832013-01-07 09:53:42 -08004180 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004181 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004182 for (size_t i = 0; i < effectChains.size(); i ++) {
4183 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004184 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004185 if (activeHapticSessionId != AUDIO_SESSION_NONE
4186 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004187 // Haptic data is active in this case, copy it directly from
4188 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004189 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4190 audio_channel_count_from_out_mask(mMixerChannelMask) :
4191 mChannelCount;
4192 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4193 hapticSessionChannelCount = mChannelCount;
4194 }
4195
jiabin47affe52019-04-04 18:02:07 -07004196 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004197 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004198 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004199 memcpy_by_audio_format(
4200 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004201 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004202 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004203 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004204 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004205 }
Eric Laurent81784c32012-11-19 14:55:58 -08004206 }
4207 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004208 // Process effect chains for offloaded thread even if no audio
4209 // was read from audio track: process only updates effect state
4210 // and thus does have to be synchronized with audio writes but may have
4211 // to be called while waiting for async write callback
4212 if (mType == OFFLOAD) {
4213 for (size_t i = 0; i < effectChains.size(); i ++) {
4214 effectChains[i]->process_l();
4215 }
4216 }
Eric Laurent81784c32012-11-19 14:55:58 -08004217
Andy Hung98ef9782014-03-04 14:46:50 -08004218 // Only if the Effects buffer is enabled and there is data in the
4219 // Effects buffer (buffer valid), we need to
4220 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004221 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004222 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004223 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004224 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004225 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004226 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004227 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004228 }
4229
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004230 if (!hasFastMixer()) {
4231 // Balance must take effect after mono conversion.
4232 // We do it here if there is no FastMixer.
4233 // mBalance detects zero balance within the class for speed (not needed here).
4234 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004235 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004236 }
4237
Eric Laurentb62d0362021-10-26 17:40:18 +02004238 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4239 // mPostSpatializerBuffer if the haptics track is spatialized.
4240 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4241 // For other thread types, the haptics channels are already in mEffectBuffer.
4242 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4243 const size_t srcBufferSize = mNormalFrameCount *
4244 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4245 mEffectBufferFormat);
4246 const size_t dstBufferSize = mNormalFrameCount
4247 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4248
4249 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4250 mEffectBufferFormat,
4251 (uint8_t*)mEffectBuffer + srcBufferSize,
4252 mEffectBufferFormat,
4253 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004254 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004255 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4256 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4257 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4258 // Clamp PCM float values more than this distance from 0 to insulate
4259 // a HAL which doesn't handle NaN correctly.
4260 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4261 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4262 static_cast<const float*>(effectBuffer),
4263 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4264 } else {
4265 memcpy_by_audio_format(mSinkBuffer, mFormat,
4266 effectBuffer, mEffectBufferFormat, framesToCopy);
4267 }
jiabin245cdd92018-12-07 17:55:15 -08004268 // The sample data is partially interleaved when haptic channels exist,
4269 // we need to adjust channels here.
4270 if (mHapticChannelCount > 0) {
4271 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4272 mChannelCount + mHapticChannelCount,
4273 audio_bytes_per_sample(mFormat),
4274 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4275 }
Andy Hung98ef9782014-03-04 14:46:50 -08004276 }
4277
Eric Laurent81784c32012-11-19 14:55:58 -08004278 // enable changes in effect chain
4279 unlockEffectChains(effectChains);
4280
Vlad Popafce10862023-02-03 10:37:07 +01004281 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004282 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004283 metadataUpdate.playbackMetadataUpdate);
4284 }
4285
Eric Laurentbfb1b832013-01-07 09:53:42 -08004286 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004287 // mSleepTimeUs == 0 means we must write to audio hardware
4288 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004289 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004290 // writePeriodNs is updated >= 0 when ret > 0.
4291 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004292 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004293 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004294 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004295 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004296 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004297 if (ret < 0) {
4298 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004299 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004300 mBytesWritten += ret;
4301 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004302 const int64_t frames = ret / mFrameSize;
4303 mFramesWritten += frames;
4304
4305 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4306 // process information relating to write time.
4307 if (audio_has_proportional_frames(mFormat)) {
4308 // we are in a continuous mixing cycle
4309 if (mMixerStatus == MIXER_TRACKS_READY &&
4310 loopCount == lastLoopCountWritten + 1) {
4311
4312 const double jitterMs =
4313 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4314 {frames, writePeriodNs},
4315 {0, 0} /* lastTimestamp */, mSampleRate);
4316 const double processMs =
4317 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4318
4319 Mutex::Autolock _l(mLock);
4320 mIoJitterMs.add(jitterMs);
4321 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004322
4323 if (mPipeSink.get() != nullptr) {
4324 // Using the Monopipe availableToWrite, we estimate the current
4325 // buffer size.
4326 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4327 const ssize_t
4328 availableToWrite = mPipeSink->availableToWrite();
4329 const size_t pipeFrames = monoPipe->maxFrames();
4330 const size_t
4331 remainingFrames = pipeFrames - max(availableToWrite, 0);
4332 mMonopipePipeDepthStats.add(remainingFrames);
4333 }
Andy Hung446f4df2019-02-21 12:26:41 -08004334 }
4335
4336 // write blocked detection
4337 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004338 if ((mType == MIXER || mType == SPATIALIZER)
4339 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004340 mNumDelayedWrites++;
4341 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4342 ATRACE_NAME("underrun");
4343 ALOGW("write blocked for %lld msecs, "
4344 "%d delayed writes, thread %d",
4345 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4346 mNumDelayedWrites, mId);
4347 lastWarning = lastIoEndNs;
4348 }
4349 }
4350 }
4351 // update timing info.
4352 mLastIoBeginNs = lastIoBeginNs;
4353 mLastIoEndNs = lastIoEndNs;
4354 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004355 }
4356 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4357 (mMixerStatus == MIXER_DRAIN_ALL)) {
4358 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004359 }
Andy Hungd3639922022-04-28 18:00:49 -07004360 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004361
4362 if (mThreadThrottle
4363 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004364 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004365 // Limit MixerThread data processing to no more than twice the
4366 // expected processing rate.
4367 //
4368 // This helps prevent underruns with NuPlayer and other applications
4369 // which may set up buffers that are close to the minimum size, or use
4370 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4371 //
4372 // The throttle smooths out sudden large data drains from the device,
4373 // e.g. when it comes out of standby, which often causes problems with
4374 // (1) mixer threads without a fast mixer (which has its own warm-up)
4375 // (2) minimum buffer sized tracks (even if the track is full,
4376 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004377 //
4378 // Total time spent in last processing cycle equals time spent in
4379 // 1. threadLoop_write, as well as time spent in
4380 // 2. threadLoop_mix (significant for heavy mixing, especially
4381 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004382
Andy Hung446f4df2019-02-21 12:26:41 -08004383 // it's OK if deltaMs is an overestimate.
4384
4385 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004386
Ivan Lozanoea04d392017-11-07 14:37:07 -08004387 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004388 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004389 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004390
Andy Hung08fb1742015-05-31 23:22:10 -07004391 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004392 // notify of throttle start on verbose log
4393 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4394 "mixer(%p) throttle begin:"
4395 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004396 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004397 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004398 // Throttle must be attributed to the previous mixer loop's write time
4399 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004400 // This also ensures proper timing statistics.
4401 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004402 } else {
4403 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4404 if (diff > 0) {
4405 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004406 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004407 ALOGD_IF(!isSingleDeviceType(
4408 outDeviceTypes(), audio_is_a2dp_out_device) &&
4409 !isSingleDeviceType(
4410 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004411 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004412 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4413 }
Andy Hung08fb1742015-05-31 23:22:10 -07004414 }
4415 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004416 }
Eric Laurent81784c32012-11-19 14:55:58 -08004417
Eric Laurentbfb1b832013-01-07 09:53:42 -08004418 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004419 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004420 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004421 // suspended requires accurate metering of sleep time.
4422 if (isSuspended()) {
4423 // advance by expected sleepTime
4424 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4425 const nsecs_t nowNs = systemTime();
4426
4427 // compute expected next time vs current time.
4428 // (negative deltas are treated as delays).
4429 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4430 if (deltaNs < -kMaxNextBufferDelayNs) {
4431 // Delays longer than the max allowed trigger a reset.
4432 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4433 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4434 timeLoopNextNs = nowNs + deltaNs;
4435 } else if (deltaNs < 0) {
4436 // Delays within the max delay allowed: zero the delta/sleepTime
4437 // to help the system catch up in the next iteration(s)
4438 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4439 deltaNs = 0;
4440 }
4441 // update sleep time (which is >= 0)
4442 mSleepTimeUs = deltaNs / 1000;
4443 }
Eric Laurente93cc032016-05-05 10:15:10 -07004444 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4445 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004446 }
Glenn Kastene7754022014-10-31 12:11:26 -07004447 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004448 }
Eric Laurent81784c32012-11-19 14:55:58 -08004449 }
4450
4451 // Finally let go of removed track(s), without the lock held
4452 // since we can't guarantee the destructors won't acquire that
4453 // same lock. This will also mutate and push a new fast mixer state.
4454 threadLoop_removeTracks(tracksToRemove);
4455 tracksToRemove.clear();
4456
4457 // FIXME I don't understand the need for this here;
4458 // it was in the original code but maybe the
4459 // assignment in saveOutputTracks() makes this unnecessary?
4460 clearOutputTracks();
4461
4462 // Effect chains will be actually deleted here if they were removed from
4463 // mEffectChains list during mixing or effects processing
4464 effectChains.clear();
4465
4466 // FIXME Note that the above .clear() is no longer necessary since effectChains
4467 // is now local to this block, but will keep it for now (at least until merge done).
4468 }
4469
Eric Laurentbfb1b832013-01-07 09:53:42 -08004470 threadLoop_exit();
4471
Eric Laurentcf817a22014-08-04 20:36:31 -07004472 if (!mStandby) {
4473 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004474 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004475 }
4476
4477 releaseWakeLock();
4478
4479 ALOGV("Thread %p type %d exiting", this, mType);
4480 return false;
4481}
4482
Andy Hungee58e4a2023-07-07 13:47:37 -07004483void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004484{
Dean Wheatley12473e92021-03-18 23:00:55 +11004485 if (mStandby) {
4486 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4487 return;
4488 } else if (mHwPaused) {
4489 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4490 return;
4491 }
4492
4493 // Gather the framesReleased counters for all active tracks,
4494 // and associate with the sink frames written out. We need
4495 // this to convert the sink timestamp to the track timestamp.
4496 bool kernelLocationUpdate = false;
4497 ExtendedTimestamp timestamp; // use private copy to fetch
4498
4499 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4500 // HAL may be draining some small duration buffered data for fade out.
4501 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4502 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4503 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4504 mSampleRate);
4505
4506 if (isTimestampCorrectionEnabled()) {
4507 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4508 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4509 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4510 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4511 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4512 = correctedTimestamp.mFrames;
4513 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4514 = correctedTimestamp.mTimeNs;
4515 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4516 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4517 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4518
4519 // Note: Downstream latency only added if timestamp correction enabled.
4520 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4521 const int64_t newPosition =
4522 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4523 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4524 // prevent retrograde
4525 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4526 newPosition,
4527 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4528 - mSuspendedFrames));
4529 }
4530 }
4531
4532 // We always fetch the timestamp here because often the downstream
4533 // sink will block while writing.
4534
4535 // We keep track of the last valid kernel position in case we are in underrun
4536 // and the normal mixer period is the same as the fast mixer period, or there
4537 // is some error from the HAL.
4538 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4539 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4540 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4541 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4542 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4543
4544 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4545 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4546 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4547 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4548 }
4549
4550 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4551 kernelLocationUpdate = true;
4552 } else {
4553 ALOGVV("getTimestamp error - no valid kernel position");
4554 }
4555
4556 // copy over kernel info
4557 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4558 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4559 + mSuspendedFrames; // add frames discarded when suspended
4560 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4561 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4562 } else {
4563 mTimestampVerifier.error();
4564 }
4565
4566 // mFramesWritten for non-offloaded tracks are contiguous
4567 // even after standby() is called. This is useful for the track frame
4568 // to sink frame mapping.
4569 bool serverLocationUpdate = false;
4570 if (mFramesWritten != mLastFramesWritten) {
4571 serverLocationUpdate = true;
4572 mLastFramesWritten = mFramesWritten;
4573 }
4574 // Only update timestamps if there is a meaningful change.
4575 // Either the kernel timestamp must be valid or we have written something.
4576 if (kernelLocationUpdate || serverLocationUpdate) {
4577 if (serverLocationUpdate) {
4578 // use the time before we called the HAL write - it is a bit more accurate
4579 // to when the server last read data than the current time here.
4580 //
4581 // If we haven't written anything, mLastIoBeginNs will be -1
4582 // and we use systemTime().
4583 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4584 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4585 ? systemTime() : mLastIoBeginNs;
4586 }
4587
Andy Hung8d31fd22023-06-26 19:20:57 -07004588 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004589 if (!t->isFastTrack()) {
4590 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004591 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004592 mFramesWritten,
4593 mSampleRate,
4594 mTimestamp);
4595 }
4596 }
4597 }
4598
4599 if (audio_has_proportional_frames(mFormat)) {
4600 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4601 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4602 mLatencyMs.add(latencyMs);
4603 }
4604 }
4605#if 0
4606 // logFormat example
4607 if (z % 100 == 0) {
4608 timespec ts;
4609 clock_gettime(CLOCK_MONOTONIC, &ts);
4610 LOGT("This is an integer %d, this is a float %f, this is my "
4611 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4612 LOGT("A deceptive null-terminated string %\0");
4613 }
4614 ++z;
4615#endif
4616}
4617
Eric Laurentbfb1b832013-01-07 09:53:42 -08004618// removeTracks_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07004619void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hung920f6572022-10-06 12:09:49 -07004620NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurentbfb1b832013-01-07 09:53:42 -08004621{
Andy Hungfe726a62018-09-27 15:17:25 -07004622 for (const auto& track : tracksToRemove) {
4623 mActiveTracks.remove(track);
4624 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004625 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004626 if (chain != 0) {
4627 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4628 __func__, track->id(), chain.get(), track->sessionId());
4629 chain->decActiveTrackCnt();
4630 }
4631 // If an external client track, inform APM we're no longer active, and remove if needed.
4632 // We do this under lock so that the state is consistent if the Track is destroyed.
4633 if (track->isExternalTrack()) {
4634 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004635 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004636 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004637 }
4638 }
Andy Hungfe726a62018-09-27 15:17:25 -07004639 if (track->isTerminated()) {
4640 // remove from our tracks vector
4641 removeTrack_l(track);
4642 }
jiabineb3bda02020-06-30 14:07:03 -07004643 if (mHapticChannelCount > 0 &&
4644 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4645 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004646 mLock.unlock();
4647 // Unlock due to VibratorService will lock for this call and will
4648 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004649 afutils::onExternalVibrationStop(track->getExternalVibration());
jiabin57303cc2018-12-18 15:45:57 -08004650 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004651
4652 // When the track is stop, set the haptic intensity as MUTE
4653 // for the HapticGenerator effect.
4654 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004655 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004656 }
jiabin245cdd92018-12-07 17:55:15 -08004657 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004658 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004659}
Eric Laurent81784c32012-11-19 14:55:58 -08004660
Andy Hungee58e4a2023-07-07 13:47:37 -07004661status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004662{
4663 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004664 ExtendedTimestamp ets;
4665 status_t status = mNormalSink->getTimestamp(ets);
4666 if (status == NO_ERROR) {
4667 status = ets.getBestTimestamp(&timestamp);
4668 }
4669 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004670 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004671 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004672 collectTimestamps_l();
4673 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4674 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004675 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004676 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4677 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4678 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4679 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4680 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004681 }
4682 return INVALID_OPERATION;
4683}
Eric Laurent1c333e22014-05-20 10:48:17 -07004684
Eric Laurenteab90452019-06-24 15:17:46 -07004685// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4686// still applied by the mixer.
4687// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4688// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4689// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004690status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004691{
4692 status_t result = NO_ERROR;
4693 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4694 if (*volume != mLeftVolFloat) {
4695 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004696 // HAL can return INVALID_OPERATION if operation is not supported.
4697 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004698 "Error when setting output stream volume: %d", result);
4699 if (result == NO_ERROR) {
4700 mLeftVolFloat = *volume;
4701 }
4702 }
4703 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4704 // remove stream volume contribution from software volume.
4705 if (mLeftVolFloat == *volume) {
4706 *volume = 1.0f;
4707 }
4708 }
4709 return result;
4710}
4711
Andy Hungee58e4a2023-07-07 13:47:37 -07004712status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004713 audio_patch_handle_t *handle)
4714{
Andy Hungf60abce2016-08-26 11:37:54 -07004715 status_t status;
4716 if (property_get_bool("af.patch_park", false /* default_value */)) {
4717 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4718 // or if HAL does not properly lock against access.
4719 AutoPark<FastMixer> park(mFastMixer);
4720 status = PlaybackThread::createAudioPatch_l(patch, handle);
4721 } else {
4722 status = PlaybackThread::createAudioPatch_l(patch, handle);
4723 }
Eric Laurentb0463942022-12-20 16:31:10 +01004724
4725 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004726 return status;
4727}
4728
Andy Hungee58e4a2023-07-07 13:47:37 -07004729status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004730 audio_patch_handle_t *handle)
4731{
4732 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004733
4734 // store new device and send to effects
4735 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004736 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004737 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004738 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4739 && !mOutput->audioHwDev->supportsAudioPatches(),
4740 "Enumerated device type(%#x) must not be used "
4741 "as it does not support audio patches",
4742 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004743 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004744 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4745 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004746 }
4747
François Gaffie0c280aa2018-07-25 10:02:15 +02004748 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004749#ifdef ADD_BATTERY_DATA
4750 // when changing the audio output device, call addBatteryData to notify
4751 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004752 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004753 uint32_t params = 0;
4754 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004755 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004756 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004757 }
4758
Eric Laurent054d9d32015-04-24 08:48:48 -07004759 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004760 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004761 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4762 }
4763
4764 if (params != 0) {
4765 addBatteryData(params);
4766 }
4767 }
4768#endif
4769
4770 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004771 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004772 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004773
jiabinc52b1ff2019-10-31 17:20:42 -07004774 // mPatch.num_sinks is not set when the thread is created so that
4775 // the first patch creation triggers an ioConfigChanged callback
4776 bool configChanged = (mPatch.num_sinks == 0) ||
4777 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004778 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004779 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004780 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004781
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004782 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004783 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4784 status = hwDevice->createAudioPatch(patch->num_sources,
4785 patch->sources,
4786 patch->num_sinks,
4787 patch->sinks,
4788 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004789 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004790 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004791 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004792 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004793 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004794
4795 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004796 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004797 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004798 // also dispatch to active AudioTracks for MediaMetrics
4799 for (const auto &track : mActiveTracks) {
4800 track->logEndInterval();
4801 track->logBeginInterval(patchSinksAsString);
4802 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004803
Eric Laurente8726fe2015-06-26 09:39:24 -07004804 if (configChanged) {
4805 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4806 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004807 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004808 mActiveTracks.setHasChanged();
4809
Eric Laurent1c333e22014-05-20 10:48:17 -07004810 return status;
4811}
4812
Andy Hungee58e4a2023-07-07 13:47:37 -07004813status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004814{
Andy Hungf60abce2016-08-26 11:37:54 -07004815 status_t status;
4816 if (property_get_bool("af.patch_park", false /* default_value */)) {
4817 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4818 // or if HAL does not properly lock against access.
4819 AutoPark<FastMixer> park(mFastMixer);
4820 status = PlaybackThread::releaseAudioPatch_l(handle);
4821 } else {
4822 status = PlaybackThread::releaseAudioPatch_l(handle);
4823 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004824 return status;
4825}
4826
Andy Hungee58e4a2023-07-07 13:47:37 -07004827status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004828{
4829 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004830
jiabinc52b1ff2019-10-31 17:20:42 -07004831 mPatch = audio_patch{};
4832 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004833
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004834 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004835 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4836 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004837 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004838 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004839 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004840 // Force meteadata update after a route change
4841 mActiveTracks.setHasChanged();
4842
Eric Laurent1c333e22014-05-20 10:48:17 -07004843 return status;
4844}
4845
Andy Hungee58e4a2023-07-07 13:47:37 -07004846void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004847{
4848 Mutex::Autolock _l(mLock);
4849 mTracks.add(track);
4850}
4851
Andy Hungee58e4a2023-07-07 13:47:37 -07004852void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004853{
4854 Mutex::Autolock _l(mLock);
4855 destroyTrack_l(track);
4856}
4857
Andy Hungee58e4a2023-07-07 13:47:37 -07004858void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07004859{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004860 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004861 config->role = AUDIO_PORT_ROLE_SOURCE;
4862 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4863 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004864 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4865 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4866 config->flags.output = mOutput->flags;
4867 }
Eric Laurent83b88082014-06-20 18:31:16 -07004868}
4869
Eric Laurent81784c32012-11-19 14:55:58 -08004870// ----------------------------------------------------------------------------
4871
Andy Hungee58e4a2023-07-07 13:47:37 -07004872/* static */
4873sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07004874 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07004875 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07004876 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07004877}
4878
Andy Hung583043b2023-07-17 17:05:00 -07004879MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004880 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07004881 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004882 // mAudioMixer below
4883 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01004884 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004885 mFastMixerFutex(0),
4886 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004887 // mOutputSink below
4888 // mPipeSink below
4889 // mNormalSink below
4890{
Andy Hung583043b2023-07-17 17:05:00 -07004891 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004892 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004893 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004894 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004895 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4896 mNormalFrameCount);
4897 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4898
Andy Hungfbfc3952015-01-15 13:33:51 -08004899 if (type == DUPLICATING) {
4900 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4901 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4902 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4903 return;
4904 }
Eric Laurent81784c32012-11-19 14:55:58 -08004905 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004906 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004907 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004908 const NBAIO_Format offers[1] = {Format_from_SR_C(
4909 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004910#if !LOG_NDEBUG
4911 ssize_t index =
4912#else
4913 (void)
4914#endif
4915 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004916 ALOG_ASSERT(index == 0);
4917
4918 // initialize fast mixer depending on configuration
4919 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00004920 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08004921 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004922 } else {
4923 switch (kUseFastMixer) {
4924 case FastMixer_Never:
4925 initFastMixer = false;
4926 break;
4927 case FastMixer_Always:
4928 initFastMixer = true;
4929 break;
4930 case FastMixer_Static:
4931 case FastMixer_Dynamic:
4932 initFastMixer = mFrameCount < mNormalFrameCount;
4933 break;
4934 }
4935 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4936 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4937 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004938 }
4939 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004940 audio_format_t fastMixerFormat;
4941 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4942 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4943 } else {
4944 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4945 }
4946 if (mFormat != fastMixerFormat) {
4947 // change our Sink format to accept our intermediate precision
4948 mFormat = fastMixerFormat;
4949 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004950 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004951 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4952 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4953 }
Eric Laurent81784c32012-11-19 14:55:58 -08004954
4955 // create a MonoPipe to connect our submix to FastMixer
4956 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004957
Andy Hung1258c1a2014-05-23 21:22:17 -07004958 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004959 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004960 format.mFormat = fastMixerFormat;
4961 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4962
Eric Laurent81784c32012-11-19 14:55:58 -08004963 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4964 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4965 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4966 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07004967 const NBAIO_Format offersFast[1] = {format};
4968 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004969#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02004970 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004971#else
4972 (void)
4973#endif
Andy Hung920f6572022-10-06 12:09:49 -07004974 monoPipe->negotiate(offersFast, std::size(offersFast),
4975 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08004976 ALOG_ASSERT(index == 0);
4977 monoPipe->setAvgFrames((mScreenState & 1) ?
4978 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4979 mPipeSink = monoPipe;
4980
Eric Laurent81784c32012-11-19 14:55:58 -08004981 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004982 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004983 FastMixerStateQueue *sq = mFastMixer->sq();
4984#ifdef STATE_QUEUE_DUMP
4985 sq->setObserverDump(&mStateQueueObserverDump);
4986 sq->setMutatorDump(&mStateQueueMutatorDump);
4987#endif
4988 FastMixerState *state = sq->begin();
4989 FastTrack *fastTrack = &state->mFastTracks[0];
4990 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4991 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4992 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004993 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4994 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4995 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004996 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004997 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004998 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01004999 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005000 fastTrack->mGeneration++;
5001 state->mFastTracksGen++;
5002 state->mTrackMask = 1;
5003 // fast mixer will use the HAL output sink
5004 state->mOutputSink = mOutputSink.get();
5005 state->mOutputSinkGen++;
5006 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005007 // specify sink channel mask when haptic channel mask present as it can not
5008 // be calculated directly from channel count
5009 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005010 ? AUDIO_CHANNEL_NONE
5011 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005012 state->mCommand = FastMixerState::COLD_IDLE;
5013 // already done in constructor initialization list
5014 //mFastMixerFutex = 0;
5015 state->mColdFutexAddr = &mFastMixerFutex;
5016 state->mColdGen++;
5017 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005018 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005019 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005020 sq->end();
5021 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5022
Eric Tan0513b5d2018-09-17 10:32:48 -07005023 NBLog::thread_info_t info;
5024 info.id = mId;
5025 info.type = NBLog::FASTMIXER;
5026 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5027
Eric Laurent81784c32012-11-19 14:55:58 -08005028 // start the fast mixer
5029 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5030 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005031 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005032 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005033
5034#ifdef AUDIO_WATCHDOG
5035 // create and start the watchdog
5036 mAudioWatchdog = new AudioWatchdog();
5037 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5038 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5039 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005040 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005041#endif
Andy Hung8946a282018-04-19 20:04:56 -07005042 } else {
5043#ifdef TEE_SINK
5044 // Only use the MixerThread tee if there is no FastMixer.
5045 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5046 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5047#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005048 }
5049
5050 switch (kUseFastMixer) {
5051 case FastMixer_Never:
5052 case FastMixer_Dynamic:
5053 mNormalSink = mOutputSink;
5054 break;
5055 case FastMixer_Always:
5056 mNormalSink = mPipeSink;
5057 break;
5058 case FastMixer_Static:
5059 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5060 break;
5061 }
5062}
5063
Andy Hungee58e4a2023-07-07 13:47:37 -07005064MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005065{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005066 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005067 FastMixerStateQueue *sq = mFastMixer->sq();
5068 FastMixerState *state = sq->begin();
5069 if (state->mCommand == FastMixerState::COLD_IDLE) {
5070 int32_t old = android_atomic_inc(&mFastMixerFutex);
5071 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005072 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005073 }
5074 }
5075 state->mCommand = FastMixerState::EXIT;
5076 sq->end();
5077 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5078 mFastMixer->join();
5079 // Though the fast mixer thread has exited, it's state queue is still valid.
5080 // We'll use that extract the final state which contains one remaining fast track
5081 // corresponding to our sub-mix.
5082 state = sq->begin();
5083 ALOG_ASSERT(state->mTrackMask == 1);
5084 FastTrack *fastTrack = &state->mFastTracks[0];
5085 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5086 delete fastTrack->mBufferProvider;
5087 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005088 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005089#ifdef AUDIO_WATCHDOG
5090 if (mAudioWatchdog != 0) {
5091 mAudioWatchdog->requestExit();
5092 mAudioWatchdog->requestExitAndWait();
5093 mAudioWatchdog.clear();
5094 }
5095#endif
5096 }
Andy Hung583043b2023-07-17 17:05:00 -07005097 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005098 delete mAudioMixer;
5099}
5100
Andy Hungee58e4a2023-07-07 13:47:37 -07005101void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005102 PlaybackThread::onFirstRef();
5103
5104 Mutex::Autolock _l(mLock);
5105 if (mOutput != nullptr && mOutput->stream != nullptr) {
5106 status_t status = mOutput->stream->setLatencyModeCallback(this);
5107 if (status != INVALID_OPERATION) {
5108 updateHalSupportedLatencyModes_l();
5109 }
5110 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5111 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5112 mBluetoothLatencyModesEnabled.store(
5113 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5114 }
5115}
Eric Laurent81784c32012-11-19 14:55:58 -08005116
Andy Hungee58e4a2023-07-07 13:47:37 -07005117uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005118{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005119 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005120 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5121 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5122 }
5123 return latency;
5124}
5125
Andy Hungee58e4a2023-07-07 13:47:37 -07005126ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005127{
5128 // FIXME we should only do one push per cycle; confirm this is true
5129 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005130 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005131 FastMixerStateQueue *sq = mFastMixer->sq();
5132 FastMixerState *state = sq->begin();
5133 if (state->mCommand != FastMixerState::MIX_WRITE &&
5134 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5135 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005136
5137 // FIXME workaround for first HAL write being CPU bound on some devices
5138 ATRACE_BEGIN("write");
5139 mOutput->write((char *)mSinkBuffer, 0);
5140 ATRACE_END();
5141
Eric Laurent81784c32012-11-19 14:55:58 -08005142 int32_t old = android_atomic_inc(&mFastMixerFutex);
5143 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005144 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005145 }
5146#ifdef AUDIO_WATCHDOG
5147 if (mAudioWatchdog != 0) {
5148 mAudioWatchdog->resume();
5149 }
5150#endif
5151 }
5152 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005153#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005154 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005155 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005156#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005157 sq->end();
5158 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5159 if (kUseFastMixer == FastMixer_Dynamic) {
5160 mNormalSink = mPipeSink;
5161 }
5162 } else {
5163 sq->end(false /*didModify*/);
5164 }
5165 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005166 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005167}
5168
Andy Hungee58e4a2023-07-07 13:47:37 -07005169void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005170{
5171 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005172 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005173 FastMixerStateQueue *sq = mFastMixer->sq();
5174 FastMixerState *state = sq->begin();
5175 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005176 // Report any frames trapped in the Monopipe
5177 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5178 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5179 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5180 "monoPipeWritten:%lld monoPipeLeft:%lld",
5181 (long long)mFramesWritten, (long long)mSuspendedFrames,
5182 (long long)mPipeSink->framesWritten(), pipeFrames);
5183 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5184
Eric Laurent81784c32012-11-19 14:55:58 -08005185 state->mCommand = FastMixerState::COLD_IDLE;
5186 state->mColdFutexAddr = &mFastMixerFutex;
5187 state->mColdGen++;
5188 mFastMixerFutex = 0;
5189 sq->end();
5190 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5191 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5192 if (kUseFastMixer == FastMixer_Dynamic) {
5193 mNormalSink = mOutputSink;
5194 }
5195#ifdef AUDIO_WATCHDOG
5196 if (mAudioWatchdog != 0) {
5197 mAudioWatchdog->pause();
5198 }
5199#endif
5200 } else {
5201 sq->end(false /*didModify*/);
5202 }
5203 }
5204 PlaybackThread::threadLoop_standby();
5205}
5206
Andy Hungee58e4a2023-07-07 13:47:37 -07005207bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005208{
5209 return false;
5210}
5211
Andy Hungee58e4a2023-07-07 13:47:37 -07005212bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005213{
5214 return !mStandby;
5215}
5216
Andy Hungee58e4a2023-07-07 13:47:37 -07005217bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005218{
5219 Mutex::Autolock _l(mLock);
5220 return waitingAsyncCallback_l();
5221}
5222
Eric Laurent81784c32012-11-19 14:55:58 -08005223// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005224void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005225{
5226 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005227 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005228 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005229 // discard any pending drain or write ack by incrementing sequence
5230 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5231 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005232 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005233 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5234 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005235 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005236 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005237 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005238}
5239
Andy Hungee58e4a2023-07-07 13:47:37 -07005240void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005241{
5242 ALOGV("signal playback thread");
5243 broadcast_l();
5244}
5245
Andy Hungee58e4a2023-07-07 13:47:37 -07005246void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005247{
5248 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5249 invalidateTracks((audio_stream_type_t)i);
5250 }
5251}
5252
Andy Hungee58e4a2023-07-07 13:47:37 -07005253void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005254{
Eric Laurent81784c32012-11-19 14:55:58 -08005255 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005256 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005257 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005258 // increase sleep time progressively when application underrun condition clears.
5259 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5260 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5261 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005262 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005263 sleepTimeShift--;
5264 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005265 mSleepTimeUs = 0;
5266 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005267 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005268
Eric Laurent81784c32012-11-19 14:55:58 -08005269}
5270
Andy Hungee58e4a2023-07-07 13:47:37 -07005271void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005272{
5273 // If no tracks are ready, sleep once for the duration of an output
5274 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005275 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005276 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005277 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5278 // Using the Monopipe availableToWrite, we estimate the
5279 // sleep time to retry for more data (before we underrun).
5280 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5281 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5282 const size_t pipeFrames = monoPipe->maxFrames();
5283 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5284 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5285 const size_t framesDelay = std::min(
5286 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5287 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5288 pipeFrames, framesLeft, framesDelay);
5289 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5290 } else {
5291 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5292 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5293 mSleepTimeUs = kMinThreadSleepTimeUs;
5294 }
5295 // reduce sleep time in case of consecutive application underruns to avoid
5296 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5297 // duration we would end up writing less data than needed by the audio HAL if
5298 // the condition persists.
5299 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5300 sleepTimeShift++;
5301 }
Eric Laurent81784c32012-11-19 14:55:58 -08005302 }
5303 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005304 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005305 }
5306 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005307 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5308 // before effects processing or output.
5309 if (mMixerBufferValid) {
5310 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005311 if (mType == SPATIALIZER) {
5312 memset(mSinkBuffer, 0, mSinkBufferSize);
5313 }
Andy Hung98ef9782014-03-04 14:46:50 -08005314 } else {
5315 memset(mSinkBuffer, 0, mSinkBufferSize);
5316 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005317 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005318 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5319 "anticipated start");
5320 }
5321 // TODO add standby time extension fct of effect tail
5322}
5323
5324// prepareTracks_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07005325PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005326 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005327{
Andy Hungc0691382018-09-12 18:01:57 -07005328 // clean up deleted track ids in AudioMixer before allocating new tracks
5329 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5330 // for each trackId, destroy it in the AudioMixer
5331 if (mAudioMixer->exists(trackId)) {
5332 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005333 }
5334 });
Andy Hungc0691382018-09-12 18:01:57 -07005335 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005336
5337 mixer_state mixerStatus = MIXER_IDLE;
5338 // find out which tracks need to be processed
5339 size_t count = mActiveTracks.size();
5340 size_t mixedTracks = 0;
5341 size_t tracksWithEffect = 0;
5342 // counts only _active_ fast tracks
5343 size_t fastTracks = 0;
5344 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5345
5346 float masterVolume = mMasterVolume;
5347 bool masterMute = mMasterMute;
5348
5349 if (masterMute) {
5350 masterVolume = 0;
5351 }
5352 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005353 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005354 if (chain != 0) {
5355 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5356 chain->setVolume_l(&v, &v);
5357 masterVolume = (float)((v + (1 << 23)) >> 24);
5358 chain.clear();
5359 }
5360
5361 // prepare a new state to push
5362 FastMixerStateQueue *sq = NULL;
5363 FastMixerState *state = NULL;
5364 bool didModify = false;
5365 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005366 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005367 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005368 sq = mFastMixer->sq();
5369 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005370 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005371 }
5372
Andy Hung69aed5f2014-02-25 17:24:40 -08005373 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005374 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005375
Andy Hungbd3b2b02018-05-21 10:53:11 -07005376 // DeferredOperations handles statistics after setting mixerStatus.
5377 class DeferredOperations {
5378 public:
Andy Hungea840382020-05-05 21:50:17 -07005379 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5380 : mMixerStatus(mixerStatus)
5381 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005382
5383 // when leaving scope, tally frames properly.
5384 ~DeferredOperations() {
5385 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5386 // because that is when the underrun occurs.
5387 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005388 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005389 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005390 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005391 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005392 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005393 }
5394 }
Andy Hungea840382020-05-05 21:50:17 -07005395 // send the max underrun frames for this mixer period
5396 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005397 }
5398
5399 // tallyUnderrunFrames() is called to update the track counters
5400 // with the number of underrun frames for a particular mixer period.
5401 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005402 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005403 mUnderrunFrames.emplace_back(track, underrunFrames);
5404 }
5405
5406 private:
5407 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005408 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005409 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005410 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005411 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005412
jiabin245cdd92018-12-07 17:55:15 -08005413 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005414 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005415 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005416
5417 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005418 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005419
5420 // process fast tracks
5421 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005422 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5423 "%s(%d): FastTrack(%d) present without FastMixer",
5424 __func__, id(), track->id());
5425
jiabin245cdd92018-12-07 17:55:15 -08005426 if (track->getHapticPlaybackEnabled()) {
5427 noFastHapticTrack = false;
5428 }
Eric Laurent81784c32012-11-19 14:55:58 -08005429
5430 // It's theoretically possible (though unlikely) for a fast track to be created
5431 // and then removed within the same normal mix cycle. This is not a problem, as
5432 // the track never becomes active so it's fast mixer slot is never touched.
5433 // The converse, of removing an (active) track and then creating a new track
5434 // at the identical fast mixer slot within the same normal mix cycle,
5435 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005436 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005437 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005438 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5439 FastTrack *fastTrack = &state->mFastTracks[j];
5440
5441 // Determine whether the track is currently in underrun condition,
5442 // and whether it had a recent underrun.
5443 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5444 FastTrackUnderruns underruns = ftDump->mUnderruns;
5445 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005446 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005447 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005448 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005449 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005450 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005451 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005452 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005453 // don't count underruns that occur while stopping or pausing
5454 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005455 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005456 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5457 recentUnderruns > 0) {
5458 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005459 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005460 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005461 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005462 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005463
5464 // This is similar to the state machine for normal tracks,
5465 // with a few modifications for fast tracks.
5466 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005467 switch (track->state()) {
5468 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005469 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005470 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005471 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005472 }
5473 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005474 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005475 // ramp down is not yet implemented
5476 track->setPaused();
5477 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005478 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005479 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005480 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005481 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005482 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005483 if (recentFull > 0 || recentPartial > 0) {
5484 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005485 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005486 }
5487 if (recentUnderruns == 0) {
5488 // no recent underruns: stay active
5489 break;
5490 }
5491 // there has recently been an underrun of some kind
5492 if (track->sharedBuffer() == 0) {
5493 // were any of the recent underruns "empty" (no frames available)?
5494 if (recentEmpty == 0) {
5495 // no, then ignore the partial underruns as they are allowed indefinitely
5496 break;
5497 }
5498 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005499 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005500 break;
5501 }
5502 // indicate to client process that the track was disabled because of underrun;
5503 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005504 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005505 // remove from active list, but state remains ACTIVE [confusing but true]
5506 isActive = false;
5507 break;
5508 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005509 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005510 case IAfTrackBase::STOPPING_2:
5511 case IAfTrackBase::PAUSED:
5512 case IAfTrackBase::STOPPED:
5513 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005514 // Check for presentation complete if track is inactive
5515 // We have consumed all the buffers of this track.
5516 // This would be incomplete if we auto-paused on underrun
5517 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005518 uint32_t latency = 0;
5519 status_t result = mOutput->stream->getLatency(&latency);
5520 ALOGE_IF(result != OK,
5521 "Error when retrieving output stream latency: %d", result);
5522 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005523 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005524 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5525 // track stays in active list until presentation is complete
5526 break;
5527 }
5528 }
5529 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005530 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005531 }
5532 if (track->isStopped()) {
5533 // Can't reset directly, as fast mixer is still polling this track
5534 // track->reset();
5535 // So instead mark this track as needing to be reset after push with ack
5536 resetMask |= 1 << i;
5537 }
5538 isActive = false;
5539 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005540 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005541 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005542 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005543 }
5544
5545 if (isActive) {
5546 // was it previously inactive?
5547 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005548 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5549 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005550 fastTrack->mBufferProvider = eabp;
5551 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005552 fastTrack->mChannelMask = track->channelMask();
5553 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005554 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005555 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005556 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005557 fastTrack->mGeneration++;
5558 state->mTrackMask |= 1 << j;
5559 didModify = true;
5560 // no acknowledgement required for newly active tracks
5561 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005562 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005563 float volume;
5564 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5565 volume = 0.f;
5566 } else {
5567 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5568 }
5569
5570 handleVoipVolume_l(&volume);
5571
Eric Laurent81784c32012-11-19 14:55:58 -08005572 // cache the combined master volume and stream type volume for fast mixer; this
5573 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005574 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005575 proxy->framesReleased()).first;
5576 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005577 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005578 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005579 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5580 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5581
Andy Hung583043b2023-07-17 17:05:00 -07005582 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005583 /*muteState=*/{masterVolume == 0.f,
5584 mStreamTypes[track->streamType()].volume == 0.f,
5585 mStreamTypes[track->streamType()].mute,
5586 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005587 vlf == 0.f && vrf == 0.f,
5588 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005589
5590 vlf *= volume;
5591 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005592
jiabin76d94692022-12-15 21:51:21 +00005593 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005594 ++fastTracks;
5595 } else {
5596 // was it previously active?
5597 if (state->mTrackMask & (1 << j)) {
5598 fastTrack->mBufferProvider = NULL;
5599 fastTrack->mGeneration++;
5600 state->mTrackMask &= ~(1 << j);
5601 didModify = true;
5602 // If any fast tracks were removed, we must wait for acknowledgement
5603 // because we're about to decrement the last sp<> on those tracks.
5604 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5605 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005606 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5607 // AudioTrack may start (which may not be with a start() but with a write()
5608 // after underrun) and immediately paused or released. In that case the
5609 // FastTrack state hasn't had time to update.
5610 // TODO Remove the ALOGW when this theory is confirmed.
5611 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005612 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005613 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005614 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005615 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005616 }
5617 tracksToRemove->add(track);
5618 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005619 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005620 }
jiabin245cdd92018-12-07 17:55:15 -08005621 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5622 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5623 didModify = true;
5624 }
Eric Laurent81784c32012-11-19 14:55:58 -08005625 continue;
5626 }
5627
5628 { // local variable scope to avoid goto warning
5629
5630 audio_track_cblk_t* cblk = track->cblk();
5631
5632 // The first time a track is added we wait
5633 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005634 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005635
5636 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005637 // use the trackId as the AudioMixer name.
5638 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005639 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005640 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005641 track->channelMask(),
5642 track->format(),
5643 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005644 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005645 ALOGW("%s(): AudioMixer cannot create track(%d)"
5646 " mask %#x, format %#x, sessionId %d",
5647 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005648 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005649 tracksToRemove->add(track);
5650 track->invalidate(); // consider it dead.
5651 continue;
5652 }
5653 }
5654
Eric Laurent81784c32012-11-19 14:55:58 -08005655 // make sure that we have enough frames to mix one full buffer.
5656 // enforce this condition only once to enable draining the buffer in case the client
5657 // app does not call stop() and relies on underrun to stop:
5658 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5659 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005660 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005661 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5662 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005663
5664 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005665 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005666 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5667 // add frames already consumed but not yet released by the resampler
5668 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005669 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005670
Eric Laurent81784c32012-11-19 14:55:58 -08005671 uint32_t minFrames = 1;
5672 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5673 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005674 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005675 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005676
5677 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005678 if (ATRACE_ENABLED()) {
5679 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005680 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005681 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005682 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005683 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005684 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005685 !track->isPaused() && !track->isTerminated())
5686 {
Andy Hungc0691382018-09-12 18:01:57 -07005687 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005688
5689 mixedTracks++;
5690
Andy Hung69aed5f2014-02-25 17:24:40 -08005691 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5692 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005693 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005694 if (track->mainBuffer() != mSinkBuffer &&
5695 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005696 if (mEffectBufferEnabled) {
5697 mEffectBufferValid = true; // Later can set directly.
5698 }
Eric Laurent81784c32012-11-19 14:55:58 -08005699 chain = getEffectChain_l(track->sessionId());
5700 // Delegate volume control to effect in track effect chain if needed
5701 if (chain != 0) {
5702 tracksWithEffect++;
5703 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005704 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005705 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005706 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005707 }
5708 }
5709
5710
5711 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07005712 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005713 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07005714 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5715 if (track->state() == IAfTrackBase::RESUMING) {
5716 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005717 // If a new track is paused immediately after start, do not ramp on resume.
5718 if (cblk->mServer != 0) {
5719 param = AudioMixer::RAMP_VOLUME;
5720 }
Eric Laurent81784c32012-11-19 14:55:58 -08005721 }
Andy Hungc0691382018-09-12 18:01:57 -07005722 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005723 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005724 // FIXME should not make a decision based on mServer
5725 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005726 // If the track is stopped before the first frame was mixed,
5727 // do not apply ramp
5728 param = AudioMixer::RAMP_VOLUME;
5729 }
5730
5731 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005732 uint32_t vl, vr; // in U8.24 integer format
5733 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005734 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005735 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005736 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07005737 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005738 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07005739 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005740
Eric Laurenteab90452019-06-24 15:17:46 -07005741 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5742 v = 0;
5743 }
5744
5745 handleVoipVolume_l(&v);
5746
5747 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005748 vl = vr = 0;
5749 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005750 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005751 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005752 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005753 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5754 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005755 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005756 if (vlf > GAIN_FLOAT_UNITY) {
5757 ALOGV("Track left volume out of range: %.3g", vlf);
5758 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005759 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005760 if (vrf > GAIN_FLOAT_UNITY) {
5761 ALOGV("Track right volume out of range: %.3g", vrf);
5762 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005763 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005764
Andy Hung583043b2023-07-17 17:05:00 -07005765 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005766 /*muteState=*/{masterVolume == 0.f,
5767 mStreamTypes[track->streamType()].volume == 0.f,
5768 mStreamTypes[track->streamType()].mute,
5769 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005770 vlf == 0.f && vrf == 0.f,
5771 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005772
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005773 // now apply the master volume and stream type volume and shaper volume
5774 vlf *= v * vh;
5775 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005776 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005777 // then derive vl and vr as U8.24 versions for the effect chain
5778 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5779 vl = (uint32_t) (scaleto8_24 * vlf);
5780 vr = (uint32_t) (scaleto8_24 * vrf);
5781 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005782 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005783 // send level comes from shared memory and so may be corrupt
5784 if (sendLevel > MAX_GAIN_INT) {
5785 ALOGV("Track send level out of range: %04X", sendLevel);
5786 sendLevel = MAX_GAIN_INT;
5787 }
Andy Hung6be49402014-05-30 10:42:03 -07005788 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5789 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005790 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005791
jiabin76d94692022-12-15 21:51:21 +00005792 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005793
Eric Laurent81784c32012-11-19 14:55:58 -08005794 // Delegate volume control to effect in track effect chain if needed
5795 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5796 // Do not ramp volume if volume is controlled by effect
5797 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005798 // Update remaining floating point volume levels
5799 vlf = (float)vl / (1 << 24);
5800 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07005801 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005802 } else {
5803 // force no volume ramp when volume controller was just disabled or removed
5804 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07005805 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005806 param = AudioMixer::VOLUME;
5807 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005808 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005809 }
5810
Eric Laurent81784c32012-11-19 14:55:58 -08005811 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07005812 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005813 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005814
Andy Hungc0691382018-09-12 18:01:57 -07005815 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5816 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5817 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005818 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005819 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005820 AudioMixer::TRACK,
5821 AudioMixer::FORMAT, (void *)track->format());
5822 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005823 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005824 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005825 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005826
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005827 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005828 mAudioMixer->setParameter(
5829 trackId,
5830 AudioMixer::TRACK,
5831 AudioMixer::MIXER_CHANNEL_MASK,
5832 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5833 } else {
5834 mAudioMixer->setParameter(
5835 trackId,
5836 AudioMixer::TRACK,
5837 AudioMixer::MIXER_CHANNEL_MASK,
5838 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5839 }
5840
Glenn Kastene3aa6592012-12-04 12:22:46 -08005841 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005842 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005843 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005844 if (reqSampleRate == 0) {
5845 reqSampleRate = mSampleRate;
5846 } else if (reqSampleRate > maxSampleRate) {
5847 reqSampleRate = maxSampleRate;
5848 }
Eric Laurent81784c32012-11-19 14:55:58 -08005849 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005850 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005851 AudioMixer::RESAMPLE,
5852 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005853 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005854
Andy Hung8edb8dc2015-03-26 19:13:55 -07005855 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005856 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005857 AudioMixer::TIMESTRETCH,
5858 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07005859 // cast away constness for this generic API.
5860 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005861
Andy Hung69aed5f2014-02-25 17:24:40 -08005862 /*
5863 * Select the appropriate output buffer for the track.
5864 *
Andy Hung98ef9782014-03-04 14:46:50 -08005865 * Tracks with effects go into their own effects chain buffer
5866 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005867 *
5868 * Other tracks can use mMixerBuffer for higher precision
5869 * channel accumulation. If this buffer is enabled
5870 * (mMixerBufferEnabled true), then selected tracks will accumulate
5871 * into it.
5872 *
5873 */
5874 if (mMixerBufferEnabled
5875 && (track->mainBuffer() == mSinkBuffer
5876 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005877 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005878 mAudioMixer->setParameter(
5879 trackId,
5880 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005881 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005882 mAudioMixer->setParameter(
5883 trackId,
5884 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005885 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005886 } else {
5887 mAudioMixer->setParameter(
5888 trackId,
5889 AudioMixer::TRACK,
5890 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5891 mAudioMixer->setParameter(
5892 trackId,
5893 AudioMixer::TRACK,
5894 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5895 // TODO: override track->mainBuffer()?
5896 mMixerBufferValid = true;
5897 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005898 } else {
5899 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005900 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005901 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07005902 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005903 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005904 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005905 AudioMixer::TRACK,
5906 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5907 }
Eric Laurent81784c32012-11-19 14:55:58 -08005908 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005909 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005910 AudioMixer::TRACK,
5911 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005912 mAudioMixer->setParameter(
5913 trackId,
5914 AudioMixer::TRACK,
5915 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005916 mAudioMixer->setParameter(
5917 trackId,
5918 AudioMixer::TRACK,
5919 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung8d31fd22023-06-26 19:20:57 -07005920 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005921 mAudioMixer->setParameter(
5922 trackId,
5923 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07005924 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08005925
5926 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005927 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005928
5929 // If one track is ready, set the mixer ready if:
5930 // - the mixer was not ready during previous round OR
5931 // - no other track is not ready
5932 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5933 mixerStatus != MIXER_TRACKS_ENABLED) {
5934 mixerStatus = MIXER_TRACKS_READY;
5935 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005936
5937 // Enable the next few lines to instrument a test for underrun log handling.
5938 // TODO: Remove when we have a better way of testing the underrun log.
5939#if 0
5940 static int i;
5941 if ((++i & 0xf) == 0) {
5942 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5943 }
5944#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005945 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005946 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005947 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005948 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5949 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005950 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005951 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005952 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005953
Eric Laurent81784c32012-11-19 14:55:58 -08005954 // clear effect chain input buffer if an active track underruns to avoid sending
5955 // previous audio buffer again to effects
5956 chain = getEffectChain_l(track->sessionId());
5957 if (chain != 0) {
5958 chain->clearInputBuffer();
5959 }
5960
Andy Hungc0691382018-09-12 18:01:57 -07005961 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005962 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5963 track->isStopped() || track->isPaused()) {
5964 // We have consumed all the buffers of this track.
5965 // Remove it from the list of active tracks.
5966 // TODO: use actual buffer filling status instead of latency when available from
5967 // audio HAL
5968 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005969 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005970 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5971 if (track->isStopped()) {
5972 track->reset();
5973 }
5974 tracksToRemove->add(track);
5975 }
5976 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005977 // No buffers for this track. Give it a few chances to
5978 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07005979 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005980 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5981 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005982 tracksToRemove->add(track);
5983 // indicate to client process that the track was disabled because of underrun;
5984 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005985 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005986 // If one track is not ready, mark the mixer also not ready if:
5987 // - the mixer was ready during previous round OR
5988 // - no other track is ready
5989 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5990 mixerStatus != MIXER_TRACKS_READY) {
5991 mixerStatus = MIXER_TRACKS_ENABLED;
5992 }
5993 }
Andy Hungc0691382018-09-12 18:01:57 -07005994 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005995 }
5996
5997 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005998
5999 }
6000
jiabin245cdd92018-12-07 17:55:15 -08006001 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6002 // When there is no fast track playing haptic and FastMixer exists,
6003 // enabling the first FastTrack, which provides mixed data from normal
6004 // tracks, to play haptic data.
6005 FastTrack *fastTrack = &state->mFastTracks[0];
6006 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6007 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6008 didModify = true;
6009 }
6010 }
6011
Eric Laurent81784c32012-11-19 14:55:58 -08006012 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006013 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006014 if (didModify) {
6015 state->mFastTracksGen++;
6016 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6017 if (kUseFastMixer == FastMixer_Dynamic &&
6018 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6019 state->mCommand = FastMixerState::COLD_IDLE;
6020 state->mColdFutexAddr = &mFastMixerFutex;
6021 state->mColdGen++;
6022 mFastMixerFutex = 0;
6023 if (kUseFastMixer == FastMixer_Dynamic) {
6024 mNormalSink = mOutputSink;
6025 }
6026 // If we go into cold idle, need to wait for acknowledgement
6027 // so that fast mixer stops doing I/O.
6028 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6029 pauseAudioWatchdog = true;
6030 }
Eric Laurent81784c32012-11-19 14:55:58 -08006031 }
6032 if (sq != NULL) {
6033 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006034 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6035 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6036 // when bringing the output sink into standby.)
6037 //
6038 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6039 //
6040 // This occurs with BT suspend when we idle the FastMixer with
6041 // active tracks, which may be added or removed.
6042 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006043 }
6044#ifdef AUDIO_WATCHDOG
6045 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6046 mAudioWatchdog->pause();
6047 }
6048#endif
6049
6050 // Now perform the deferred reset on fast tracks that have stopped
6051 while (resetMask != 0) {
6052 size_t i = __builtin_ctz(resetMask);
6053 ALOG_ASSERT(i < count);
6054 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006055 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006056 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6057 track->reset();
6058 }
6059
Andy Hung80d03d22018-04-10 10:32:11 -07006060 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6061 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6062 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6063 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6064 // See also the implementation of destroyTrack_l().
6065 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006066 const int trackId = track->id();
6067 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6068 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006069 }
6070 }
6071
Eric Laurent81784c32012-11-19 14:55:58 -08006072 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006073 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006074
Eric Laurentb3f315a2021-07-13 15:09:05 +02006075 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6076 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006077 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006078 }
6079
6080 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006081 // as long as there are effects we should clear the effects buffer, to avoid
6082 // passing a non-clean buffer to the effect chain
6083 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006084 if (mType == SPATIALIZER) {
6085 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6086 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006087 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006088 // sink or mix buffer must be cleared if all tracks are connected to an
6089 // effect chain as in this case the mixer will not write to the sink or mix buffer
6090 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006091 // always clear sink buffer for spatializer output as the output of the spatializer
6092 // effect will be accumulated into it
6093 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6094 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006095 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006096 if (mMixerBufferValid) {
6097 memset(mMixerBuffer, 0, mMixerBufferSize);
6098 // TODO: In testing, mSinkBuffer below need not be cleared because
6099 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6100 // after mixing.
6101 //
6102 // To enforce this guarantee:
6103 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6104 // (mixedTracks == 0 && fastTracks > 0))
6105 // must imply MIXER_TRACKS_READY.
6106 // Later, we may clear buffers regardless, and skip much of this logic.
6107 }
Andy Hung98ef9782014-03-04 14:46:50 -08006108 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006109 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006110 }
6111
6112 // if any fast tracks, then status is ready
6113 mMixerStatusIgnoringFastTracks = mixerStatus;
6114 if (fastTracks > 0) {
6115 mixerStatus = MIXER_TRACKS_READY;
6116 }
6117 return mixerStatus;
6118}
6119
Eric Laurentad7dd962016-09-22 12:38:37 -07006120// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07006121uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006122{
6123 uint32_t trackCount = 0;
6124 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006125 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006126 trackCount++;
6127 }
6128 }
6129 return trackCount;
6130}
6131
Andy Hungee58e4a2023-07-07 13:47:37 -07006132bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006133{
Brian Lindahl65e90012022-07-27 18:01:07 +02006134 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6135 // could falsely detect that the frame position has stalled due to underrun because we haven't
6136 // given the Audio HAL enough time to update.
6137 const nsecs_t nowNs = systemTime();
6138 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6139 return mLatchedValue;
6140 }
6141 mPreviousNs = nowNs;
6142 mLatchedValue = false;
6143 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006144 uint64_t position = 0;
6145 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006146 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006147 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006148 if (position != mPreviousPosition) {
6149 mPreviousPosition = position;
6150 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006151 }
6152 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006153 return mLatchedValue;
6154}
6155
Andy Hungee58e4a2023-07-07 13:47:37 -07006156void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006157{
6158 mLatchedValue = true;
6159 mPreviousPosition = 0;
6160 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006161}
6162
Andy Hung1bc088a2018-02-09 15:57:31 -08006163// isTrackAllowed_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07006164bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006165 audio_channel_mask_t channelMask, audio_format_t format,
6166 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006167{
Andy Hung1bc088a2018-02-09 15:57:31 -08006168 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6169 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006170 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006171 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006172 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006173 ALOGW("%s: invalid format: %#x", __func__, format);
6174 return false;
6175 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006176 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006177 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6178 return false;
6179 }
6180 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006181}
6182
Eric Laurent10351942014-05-08 18:49:52 -07006183// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07006184bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006185 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006186{
Eric Laurent81784c32012-11-19 14:55:58 -08006187 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006188 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006189
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006190 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006191
Eric Laurent10351942014-05-08 18:49:52 -07006192 AudioParameter param = AudioParameter(keyValuePair);
6193 int value;
6194 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6195 reconfig = true;
6196 }
6197 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hungee58e4a2023-07-07 13:47:37 -07006198 if (!AudioFlinger::isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006199 status = BAD_VALUE;
6200 } else {
6201 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006202 reconfig = true;
6203 }
Eric Laurent10351942014-05-08 18:49:52 -07006204 }
6205 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hungee58e4a2023-07-07 13:47:37 -07006206 if (!AudioFlinger::isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006207 status = BAD_VALUE;
6208 } else {
6209 // no need to save value, since it's constant
6210 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006211 }
Eric Laurent10351942014-05-08 18:49:52 -07006212 }
6213 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6214 // do not accept frame count changes if tracks are open as the track buffer
6215 // size depends on frame count and correct behavior would not be guaranteed
6216 // if frame count is changed after track creation
6217 if (!mTracks.isEmpty()) {
6218 status = INVALID_OPERATION;
6219 } else {
6220 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006221 }
Eric Laurent10351942014-05-08 18:49:52 -07006222 }
6223 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006224 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006225 }
Eric Laurent81784c32012-11-19 14:55:58 -08006226
Eric Laurent10351942014-05-08 18:49:52 -07006227 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006228 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006229 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006230 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6231 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006232 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006233 mThreadMetrics.logEndInterval();
6234 mThreadSnapshot.onEnd();
6235 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006236 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006237 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006238 }
Eric Laurent10351942014-05-08 18:49:52 -07006239 if (status == NO_ERROR && reconfig) {
6240 readOutputParameters_l();
6241 delete mAudioMixer;
6242 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006243 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006244 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006245 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006246 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006247 track->channelMask(),
6248 track->format(),
6249 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006250 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006251 "%s(): AudioMixer cannot create track(%d)"
6252 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006253 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006254 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006255 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006256 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006257 }
Eric Laurent81784c32012-11-19 14:55:58 -08006258 }
6259
Dean Wheatley68918102021-03-19 22:09:19 +11006260 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006261}
6262
6263
Andy Hungee58e4a2023-07-07 13:47:37 -07006264void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006265{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006266 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006267 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006268 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006269 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006270 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6271 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6272 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006273 if (hasFastMixer()) {
6274 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6275
6276 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6277 // while we are dumping it. It may be inconsistent, but it won't mutate!
6278 // This is a large object so we place it on the heap.
6279 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006280 const std::unique_ptr<FastMixerDumpState> copy =
6281 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006282 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006283
6284#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006285 // Similar for state queue
6286 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6287 observerCopy.dump(fd);
6288 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6289 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006290#endif
6291
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006292#ifdef AUDIO_WATCHDOG
6293 if (mAudioWatchdog != 0) {
6294 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6295 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6296 wdCopy.dump(fd);
6297 }
6298#endif
6299
6300 } else {
6301 dprintf(fd, " No FastMixer\n");
6302 }
Eric Laurent90cea102023-05-15 15:08:27 +02006303
6304 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6305 mBluetoothLatencyModesEnabled ? "" : "not ");
6306 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6307 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6308 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006309}
6310
Andy Hungee58e4a2023-07-07 13:47:37 -07006311uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006312{
6313 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6314}
6315
Andy Hungee58e4a2023-07-07 13:47:37 -07006316uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006317{
6318 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6319}
6320
Andy Hungee58e4a2023-07-07 13:47:37 -07006321void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006322{
6323 PlaybackThread::cacheParameters_l();
6324
6325 // FIXME: Relaxed timing because of a certain device that can't meet latency
6326 // Should be reduced to 2x after the vendor fixes the driver issue
6327 // increase threshold again due to low power audio mode. The way this warning
6328 // threshold is calculated and its usefulness should be reconsidered anyway.
6329 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6330}
6331
Andy Hungee58e4a2023-07-07 13:47:37 -07006332void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006333 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006334}
6335
Andy Hungee58e4a2023-07-07 13:47:37 -07006336void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006337 // Only handle latency mode if:
6338 // - mBluetoothLatencyModesEnabled is true
6339 // - the HAL supports latency modes
6340 // - the selected device is Bluetooth LE or A2DP
6341 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6342 return;
6343 }
6344 if (mOutDeviceTypeAddrs.size() != 1
6345 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6346 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6347 return;
6348 }
6349
6350 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6351 if (mSupportedLatencyModes.size() == 1) {
6352 // If the HAL only support one latency mode currently, confirm the choice
6353 latencyMode = mSupportedLatencyModes[0];
6354 } else if (mSupportedLatencyModes.size() > 1) {
6355 // Request low latency if:
6356 // - At least one active track is either:
6357 // - a fast track with gaming usage or
6358 // - a track with acessibility usage
6359 for (const auto& track : mActiveTracks) {
6360 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6361 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6362 latencyMode = AUDIO_LATENCY_MODE_LOW;
6363 break;
6364 }
6365 }
6366 }
6367
6368 if (latencyMode != mSetLatencyMode) {
6369 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6370 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6371 __func__, mId, toString(latencyMode).c_str(), status);
6372 if (status == NO_ERROR) {
6373 mSetLatencyMode = latencyMode;
6374 }
6375 }
6376}
6377
Andy Hungee58e4a2023-07-07 13:47:37 -07006378void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006379
6380 if (mOutput == nullptr || mOutput->stream == nullptr) {
6381 return;
6382 }
6383 std::vector<audio_latency_mode_t> latencyModes;
6384 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6385 if (status != NO_ERROR) {
6386 latencyModes.clear();
6387 }
6388 if (latencyModes != mSupportedLatencyModes) {
6389 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6390 __func__, mId, status, toString(latencyModes).c_str());
6391 mSupportedLatencyModes.swap(latencyModes);
6392 sendHalLatencyModesChangedEvent_l();
6393 }
6394}
6395
Andy Hungee58e4a2023-07-07 13:47:37 -07006396status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006397 std::vector<audio_latency_mode_t>* modes) {
6398 if (modes == nullptr) {
6399 return BAD_VALUE;
6400 }
6401 Mutex::Autolock _l(mLock);
6402 *modes = mSupportedLatencyModes;
6403 return NO_ERROR;
6404}
6405
Andy Hungee58e4a2023-07-07 13:47:37 -07006406void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006407 std::vector<audio_latency_mode_t> modes) {
6408 Mutex::Autolock _l(mLock);
6409 if (modes != mSupportedLatencyModes) {
6410 ALOGD("%s: thread(%d) supported latency modes: %s",
6411 __func__, mId, toString(modes).c_str());
6412 mSupportedLatencyModes.swap(modes);
6413 sendHalLatencyModesChangedEvent_l();
6414 }
6415}
6416
Andy Hungee58e4a2023-07-07 13:47:37 -07006417status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006418 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6419 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6420 return INVALID_OPERATION;
6421 }
6422 mBluetoothLatencyModesEnabled.store(enabled);
6423 return NO_ERROR;
6424}
6425
Eric Laurent81784c32012-11-19 14:55:58 -08006426// ----------------------------------------------------------------------------
6427
Andy Hungee58e4a2023-07-07 13:47:37 -07006428/* static */
6429sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006430 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006431 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6432 const audio_offload_info_t& offloadInfo) {
6433 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006434 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006435}
6436
Andy Hung583043b2023-07-17 17:05:00 -07006437DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006438 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6439 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006440 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006441 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006442{
Andy Hung583043b2023-07-17 17:05:00 -07006443 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006444}
6445
Andy Hungee58e4a2023-07-07 13:47:37 -07006446DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006447{
6448}
6449
Andy Hungee58e4a2023-07-07 13:47:37 -07006450void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006451{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006452 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006453 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6454 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6455}
6456
Andy Hungee58e4a2023-07-07 13:47:37 -07006457void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006458{
6459 Mutex::Autolock _l(mLock);
6460 if (mMasterBalance != balance) {
6461 mMasterBalance.store(balance);
6462 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6463 broadcast_l();
6464 }
6465}
6466
Andy Hungee58e4a2023-07-07 13:47:37 -07006467void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006468{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006469 float left, right;
6470
Andy Hung333ab962019-05-28 20:23:35 -07006471 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006472 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006473
6474 const size_t framesReleased = proxy->framesReleased();
6475 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6476 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6477
6478 ALOGV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6479 __func__, framesReleased, (long long)frames, (long long)time);
6480
6481 const int64_t volumeShaperFrames =
6482 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6483 const auto [shaperVolume, shaperActive] =
6484 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006485 mVolumeShaperActive = shaperActive;
6486
Vlad Popae2f5aef2022-07-25 16:00:20 +02006487 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6488 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6489 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6490
6491 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6492
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006493 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006494 left = right = 0;
6495 } else {
6496 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006497 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006498
Glenn Kastenc56f3422014-03-21 17:53:17 -07006499 if (left > GAIN_FLOAT_UNITY) {
6500 left = GAIN_FLOAT_UNITY;
6501 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006502 if (right > GAIN_FLOAT_UNITY) {
6503 right = GAIN_FLOAT_UNITY;
6504 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006505 left *= v;
6506 right *= v;
Andy Hung583043b2023-07-17 17:05:00 -07006507 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006508 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6509 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6510 right *= mMasterBalanceRight;
6511 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006512 }
6513
Andy Hung583043b2023-07-17 17:05:00 -07006514 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006515 /*muteState=*/{mMasterMute,
6516 mStreamTypes[track->streamType()].volume == 0.f,
6517 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006518 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006519 clientVolumeMute,
6520 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006521
Eric Laurentbfb1b832013-01-07 09:53:42 -08006522 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006523 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006524 if (left != mLeftVolFloat || right != mRightVolFloat) {
6525 mLeftVolFloat = left;
6526 mRightVolFloat = right;
6527
Eric Laurentbfb1b832013-01-07 09:53:42 -08006528 // Delegate volume control to effect in track effect chain if needed
6529 // only one effect chain can be present on DirectOutputThread, so if
6530 // there is one, the track is connected to it
6531 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006532 // if effect chain exists, volume is handled by it.
6533 // Convert volumes from float to 8.24
6534 uint32_t vl = (uint32_t)(left * (1 << 24));
6535 uint32_t vr = (uint32_t)(right * (1 << 24));
6536 // Direct/Offload effect chains set output volume in setVolume_l().
6537 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6538 } else {
6539 // otherwise we directly set the volume.
6540 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006541 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006542 }
6543 }
6544}
6545
Andy Hungee58e4a2023-07-07 13:47:37 -07006546void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006547{
Andy Hung8d31fd22023-06-26 19:20:57 -07006548 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6549 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006550
Eric Laurent0f0631e2015-07-06 18:01:25 -07006551 if (previousTrack != 0 && latestTrack != 0) {
6552 if (mType == DIRECT) {
6553 if (previousTrack.get() != latestTrack.get()) {
6554 mFlushPending = true;
6555 }
6556 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006557 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6558 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006559 mFlushPending = true;
6560 }
6561 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006562 } else if (previousTrack == 0) {
6563 // there could be an old track added back during track transition for direct
6564 // output, so always issues flush to flush data of the previous track if it
6565 // was already destroyed with HAL paused, then flush can resume the playback
6566 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006567 }
6568 PlaybackThread::onAddNewTrack_l();
6569}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006570
Andy Hungee58e4a2023-07-07 13:47:37 -07006571PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006572 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006573)
6574{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006575 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006576 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006577 bool doHwPause = false;
6578 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006579
6580 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006581 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006582 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006583 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006584 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006585 continue;
6586 }
6587
Andy Hung8d31fd22023-06-26 19:20:57 -07006588 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006589#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006590 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006591#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006592 // Only consider last track started for volume and mixer state control.
6593 // In theory an older track could underrun and restart after the new one starts
6594 // but as we only care about the transition phase between two tracks on a
6595 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006596 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006597 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006598
Kuowei Li23666472021-01-20 10:23:25 +08006599 if (track->isPausePending()) {
6600 track->pauseAck();
6601 // It is possible a track might have been flushed or stopped.
6602 // Other operations such as flush pending might occur on the next prepare.
6603 if (track->isPausing()) {
6604 track->setPaused();
6605 }
6606 // Always perform pause, as an immediate flush will change
6607 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006608 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006609 doHwPause = true;
6610 mHwPaused = true;
6611 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006612 } else if (track->isFlushPending()) {
6613 track->flushAck();
6614 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006615 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006616 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006617 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006618 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006619 if (last) {
6620 mLeftVolFloat = mRightVolFloat = -1.0;
6621 if (mHwPaused) {
6622 doHwResume = true;
6623 mHwPaused = false;
6624 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006625 }
6626 }
6627
Eric Laurent81784c32012-11-19 14:55:58 -08006628 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006629 // for all its buffers to be filled before processing it.
6630 // Allow draining the buffer in case the client
6631 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006632 // hence the test on (track->retryCount() > 1).
6633 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006634 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6635 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006636 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006637
6638 // target retry count that we will use is based on the time we wait for retries.
6639 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6640 // the retry threshold is when we accept any size for PCM data. This is slightly
6641 // smaller than the retry count so we can push small bits of data without a glitch.
6642 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006643 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006644 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006645 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006646 minFrames = mNormalFrameCount;
6647 } else {
6648 minFrames = 1;
6649 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006650
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006651 const size_t framesReady = track->framesReady();
6652 const int trackId = track->id();
6653 if (ATRACE_ENABLED()) {
6654 std::string traceName("nRdy");
6655 traceName += std::to_string(trackId);
6656 ATRACE_INT(traceName.c_str(), framesReady);
6657 }
6658 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006659 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006660 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006661 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006662
Andy Hung8d31fd22023-06-26 19:20:57 -07006663 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6664 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006665 if (last) {
6666 // make sure processVolume_l() will apply new volume even if 0
6667 mLeftVolFloat = mRightVolFloat = -1.0;
6668 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006669 if (!mHwSupportsPause) {
6670 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006671 }
6672 }
6673
6674 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006675 processVolume_l(track, last);
6676 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006677 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006678 if (previousTrack != 0) {
6679 if (track != previousTrack.get()) {
6680 // Flush any data still being written from last track
6681 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006682 // Invalidate previous track to force a seek when resuming.
6683 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006684 }
6685 }
6686 mPreviousTrack = track;
6687
Eric Laurentd595b7c2013-04-03 17:27:56 -07006688 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006689 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006690 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006691 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006692 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006693 doHwResume = true;
6694 mHwPaused = false;
6695 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006696 }
Eric Laurent81784c32012-11-19 14:55:58 -08006697 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006698 // clear effect chain input buffer if the last active track started underruns
6699 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006700 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006701 mEffectChains[0]->clearInputBuffer();
6702 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006703 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006704 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006705 if (last && mHwPaused) {
6706 doHwResume = true;
6707 mHwPaused = false;
6708 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006709 }
6710 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6711 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006712 // We have consumed all the buffers of this track.
6713 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006714 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006715 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006716 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006717 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006718 if (presComplete) {
6719 mOutput->presentationComplete();
6720 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006721 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006722 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006723 }
Eric Laurent81784c32012-11-19 14:55:58 -08006724 if (track->isStopped()) {
6725 track->reset();
6726 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006727 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006728 }
6729 } else {
6730 // No buffers for this track. Give it a few chances to
6731 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006732 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006733 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006734 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07006735 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006736 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07006737 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006738 } else {
6739 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6740 tracksToRemove->add(track);
6741 // indicate to client process that the track was disabled because of
6742 // underrun; it will then automatically call start() when data is available
6743 track->disable();
6744 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6745 // unlike mixerthread, HAL can be paused for direct output
6746 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6747 "minFrames = %u, mFormat = %#x",
6748 framesReady, minFrames, mFormat);
6749 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6750 doHwPause = true;
6751 mHwPaused = true;
6752 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006753 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006754 } else if (last) {
6755 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006756 }
6757 }
6758 }
6759 }
6760
Eric Laurentd1f69b02014-12-15 14:33:13 -08006761 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006762 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006763 for (size_t i = 0; i < mTracks.size(); i++) {
6764 if (mTracks[i]->isFlushPending()) {
6765 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006766 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006767 }
6768 }
6769 }
6770
6771 // make sure the pause/flush/resume sequence is executed in the right order.
6772 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6773 // before flush and then resume HW. This can happen in case of pause/flush/resume
6774 // if resume is received before pause is executed.
6775 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006776 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006777 status_t result = mOutput->stream->pause();
6778 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006779 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006780 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006781 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006782 flushHw_l();
6783 }
6784 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006785 status_t result = mOutput->stream->resume();
6786 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006787 }
Eric Laurent81784c32012-11-19 14:55:58 -08006788 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006789 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006790
6791 return mixerStatus;
6792}
6793
Andy Hungee58e4a2023-07-07 13:47:37 -07006794void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006795{
Eric Laurent81784c32012-11-19 14:55:58 -08006796 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006797 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006798 // output audio to hardware
6799 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006800 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006801 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006802 status_t status = mActiveTrack->getNextBuffer(&buffer);
6803 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006804 // no need to pad with 0 for compressed audio
6805 if (audio_has_proportional_frames(mFormat)) {
6806 memset(curBuf, 0, frameCount * mFrameSize);
6807 }
Eric Laurent81784c32012-11-19 14:55:58 -08006808 break;
6809 }
6810 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6811 frameCount -= buffer.frameCount;
6812 curBuf += buffer.frameCount * mFrameSize;
6813 mActiveTrack->releaseBuffer(&buffer);
6814 }
Andy Hung2098f272014-02-27 14:00:06 -08006815 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006816 mSleepTimeUs = 0;
6817 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006818 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006819}
6820
Andy Hungee58e4a2023-07-07 13:47:37 -07006821void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006822{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006823 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006824 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006825 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006826 return;
6827 }
Andy Hung85ba3332021-04-27 17:40:26 -07006828 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6829 mSleepTimeUs = mActiveSleepTimeUs;
6830 } else {
6831 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006832 }
Andy Hung85ba3332021-04-27 17:40:26 -07006833 // Note: In S or later, we do not write zeroes for
6834 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006835}
6836
Andy Hungee58e4a2023-07-07 13:47:37 -07006837void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006838{
6839 {
6840 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006841 for (size_t i = 0; i < mTracks.size(); i++) {
6842 if (mTracks[i]->isFlushPending()) {
6843 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006844 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006845 }
6846 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006847 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006848 flushHw_l();
6849 }
6850 }
6851 PlaybackThread::threadLoop_exit();
6852}
6853
6854// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07006855bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006856{
6857 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006858 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006859
6860 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6861 // after a timeout and we will enter standby then.
6862 if (mTracks.size() > 0) {
6863 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006864 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung8d31fd22023-06-26 19:20:57 -07006865 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006866 }
6867
Eric Laurent5cff4032015-05-26 13:49:58 -07006868 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006869}
6870
Eric Laurent10351942014-05-08 18:49:52 -07006871// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07006872bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006873 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006874{
6875 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006876 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006877
Eric Laurent10351942014-05-08 18:49:52 -07006878 AudioParameter param = AudioParameter(keyValuePair);
6879 int value;
6880 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006881 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006882 }
Eric Laurent10351942014-05-08 18:49:52 -07006883 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6884 // do not accept frame count changes if tracks are open as the track buffer
6885 // size depends on frame count and correct behavior would not be garantied
6886 // if frame count is changed after track creation
6887 if (!mTracks.isEmpty()) {
6888 status = INVALID_OPERATION;
6889 } else {
6890 reconfig = true;
6891 }
6892 }
6893 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006894 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006895 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006896 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006897 if (!mStandby) {
6898 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006899 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02006900 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07006901 }
Eric Laurent10351942014-05-08 18:49:52 -07006902 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006903 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006904 }
6905 if (status == NO_ERROR && reconfig) {
6906 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006907 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006908 }
6909 }
6910
Dean Wheatley68918102021-03-19 22:09:19 +11006911 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006912}
6913
Andy Hungee58e4a2023-07-07 13:47:37 -07006914uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006915{
6916 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006917 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006918 time = PlaybackThread::activeSleepTimeUs();
6919 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006920 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006921 }
6922 return time;
6923}
6924
Andy Hungee58e4a2023-07-07 13:47:37 -07006925uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006926{
6927 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006928 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006929 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6930 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006931 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006932 }
6933 return time;
6934}
6935
Andy Hungee58e4a2023-07-07 13:47:37 -07006936uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006937{
6938 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006939 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006940 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6941 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006942 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006943 }
6944 return time;
6945}
6946
Andy Hungee58e4a2023-07-07 13:47:37 -07006947void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006948{
6949 PlaybackThread::cacheParameters_l();
6950
6951 // use shorter standby delay as on normal output to release
6952 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006953 // no delay on outputs with HW A/V sync
6954 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006955 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006956 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006957 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006958 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006959 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006960 }
Eric Laurent81784c32012-11-19 14:55:58 -08006961}
6962
Andy Hungee58e4a2023-07-07 13:47:37 -07006963void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07006964{
ziyangch8f194f12021-12-01 13:48:04 -08006965 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08006966 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006967 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006968 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006969 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006970 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08006971 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07006972}
6973
Andy Hungee58e4a2023-07-07 13:47:37 -07006974int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08006975 // If a VolumeShaper is active, we must wake up periodically to update volume.
6976 const int64_t NS_PER_MS = 1000000;
6977 return mVolumeShaperActive ?
6978 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6979}
6980
Eric Laurent81784c32012-11-19 14:55:58 -08006981// ----------------------------------------------------------------------------
6982
Andy Hungee58e4a2023-07-07 13:47:37 -07006983AsyncCallbackThread::AsyncCallbackThread(
6984 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006985 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006986 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006987 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006988 mDrainSequence(0),
6989 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006990{
6991}
6992
Andy Hungee58e4a2023-07-07 13:47:37 -07006993void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08006994{
6995 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6996}
6997
Andy Hungee58e4a2023-07-07 13:47:37 -07006998bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08006999{
7000 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007001 uint32_t writeAckSequence;
7002 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007003 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007004
7005 {
7006 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007007 while (!((mWriteAckSequence & 1) ||
7008 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007009 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007010 exitPending())) {
7011 mWaitWorkCV.wait(mLock);
7012 }
7013
Eric Laurentbfb1b832013-01-07 09:53:42 -08007014 if (exitPending()) {
7015 break;
7016 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007017 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7018 mWriteAckSequence, mDrainSequence);
7019 writeAckSequence = mWriteAckSequence;
7020 mWriteAckSequence &= ~1;
7021 drainSequence = mDrainSequence;
7022 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007023 asyncError = mAsyncError;
7024 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007025 }
7026 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007027 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007028 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007029 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007030 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007031 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007032 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007033 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007034 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007035 if (asyncError) {
7036 playbackThread->onAsyncError();
7037 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007038 }
7039 }
7040 }
7041 return false;
7042}
7043
Andy Hungee58e4a2023-07-07 13:47:37 -07007044void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007045{
7046 ALOGV("AsyncCallbackThread::exit");
7047 Mutex::Autolock _l(mLock);
7048 requestExit();
7049 mWaitWorkCV.broadcast();
7050}
7051
Andy Hungee58e4a2023-07-07 13:47:37 -07007052void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007053{
7054 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007055 // bit 0 is cleared
7056 mWriteAckSequence = sequence << 1;
7057}
7058
Andy Hungee58e4a2023-07-07 13:47:37 -07007059void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007060{
7061 Mutex::Autolock _l(mLock);
7062 // ignore unexpected callbacks
7063 if (mWriteAckSequence & 2) {
7064 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007065 mWaitWorkCV.signal();
7066 }
7067}
7068
Andy Hungee58e4a2023-07-07 13:47:37 -07007069void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007070{
7071 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007072 // bit 0 is cleared
7073 mDrainSequence = sequence << 1;
7074}
7075
Andy Hungee58e4a2023-07-07 13:47:37 -07007076void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007077{
7078 Mutex::Autolock _l(mLock);
7079 // ignore unexpected callbacks
7080 if (mDrainSequence & 2) {
7081 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007082 mWaitWorkCV.signal();
7083 }
7084}
7085
Andy Hungee58e4a2023-07-07 13:47:37 -07007086void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007087{
7088 Mutex::Autolock _l(mLock);
7089 mAsyncError = true;
7090 mWaitWorkCV.signal();
7091}
7092
Eric Laurentbfb1b832013-01-07 09:53:42 -08007093
7094// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007095
7096/* static */
7097sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007098 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007099 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7100 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007101 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007102}
7103
Andy Hung583043b2023-07-17 17:05:00 -07007104OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007105 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7106 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007107 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007108 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007109{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007110 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007111 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007112 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007113}
7114
Andy Hungee58e4a2023-07-07 13:47:37 -07007115void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007116{
7117 if (mFlushPending || mHwPaused) {
7118 // If a flush is pending or track was paused, just discard buffered data
7119 flushHw_l();
7120 } else {
7121 mMixerStatus = MIXER_DRAIN_ALL;
7122 threadLoop_drain();
7123 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007124 if (mUseAsyncWrite) {
7125 ALOG_ASSERT(mCallbackThread != 0);
7126 mCallbackThread->exit();
7127 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007128 PlaybackThread::threadLoop_exit();
7129}
7130
Andy Hungee58e4a2023-07-07 13:47:37 -07007131PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007132 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007133)
7134{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007135 size_t count = mActiveTracks.size();
7136
7137 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007138 bool doHwPause = false;
7139 bool doHwResume = false;
7140
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007141 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007142
Eric Laurentbfb1b832013-01-07 09:53:42 -08007143 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007144 for (const sp<IAfTrack>& t : mActiveTracks) {
7145 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007146#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007147 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007148#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007149 // Only consider last track started for volume and mixer state control.
7150 // In theory an older track could underrun and restart after the new one starts
7151 // but as we only care about the transition phase between two tracks on a
7152 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007153 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007154 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007155
Haynes Mathew George7844f672014-01-15 12:32:55 -08007156 if (track->isInvalid()) {
7157 ALOGW("An invalidated track shouldn't be in active list");
7158 tracksToRemove->add(track);
7159 continue;
7160 }
7161
Andy Hung8d31fd22023-06-26 19:20:57 -07007162 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007163 ALOGW("An idle track shouldn't be in active list");
7164 continue;
7165 }
7166
Kuowei Li23666472021-01-20 10:23:25 +08007167 if (track->isPausePending()) {
7168 track->pauseAck();
7169 // It is possible a track might have been flushed or stopped.
7170 // Other operations such as flush pending might occur on the next prepare.
7171 if (track->isPausing()) {
7172 track->setPaused();
7173 }
7174 // Always perform pause if last, as an immediate flush will change
7175 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007176 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007177 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007178 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007179 mHwPaused = true;
7180 }
7181 // If we were part way through writing the mixbuffer to
7182 // the HAL we must save this until we resume
7183 // BUG - this will be wrong if a different track is made active,
7184 // in that case we want to discard the pending data in the
7185 // mixbuffer and tell the client to present it again when the
7186 // track is resumed
7187 mPausedWriteLength = mCurrentWriteLength;
7188 mPausedBytesRemaining = mBytesRemaining;
7189 mBytesRemaining = 0; // stop writing
7190 }
7191 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007192 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007193 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007194 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007195 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007196 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007197 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007198 track->flushAck();
7199 if (last) {
7200 mFlushPending = true;
7201 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007202 } else if (track->isResumePending()){
7203 track->resumeAck();
7204 if (last) {
7205 if (mPausedBytesRemaining) {
7206 // Need to continue write that was interrupted
7207 mCurrentWriteLength = mPausedWriteLength;
7208 mBytesRemaining = mPausedBytesRemaining;
7209 mPausedBytesRemaining = 0;
7210 }
7211 if (mHwPaused) {
7212 doHwResume = true;
7213 mHwPaused = false;
7214 // threadLoop_mix() will handle the case that we need to
7215 // resume an interrupted write
7216 }
7217 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007218 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007219
Eric Laurent3df841a2016-07-15 15:15:40 -07007220 mLeftVolFloat = mRightVolFloat = -1.0;
7221
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007222 // Do not handle new data in this iteration even if track->framesReady()
7223 mixerStatus = MIXER_TRACKS_ENABLED;
7224 }
7225 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007226 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007227 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007228 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7229 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007230 if (last) {
7231 // make sure processVolume_l() will apply new volume even if 0
7232 mLeftVolFloat = mRightVolFloat = -1.0;
7233 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007234 }
7235
7236 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007237 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007238 if (previousTrack != 0) {
7239 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007240 // Flush any data still being written from last track
7241 mBytesRemaining = 0;
7242 if (mPausedBytesRemaining) {
7243 // Last track was paused so we also need to flush saved
7244 // mixbuffer state and invalidate track so that it will
7245 // re-submit that unwritten data when it is next resumed
7246 mPausedBytesRemaining = 0;
7247 // Invalidate is a bit drastic - would be more efficient
7248 // to have a flag to tell client that some of the
7249 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007250 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007251 }
7252 // flush data already sent to the DSP if changing audio session as audio
7253 // comes from a different source. Also invalidate previous track to force a
7254 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007255 if (previousTrack->sessionId() != track->sessionId()) {
7256 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007257 }
7258 }
7259 }
7260 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007261 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007262 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007263 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007264 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007265 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007266 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007267 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007268 mixerStatus = MIXER_TRACKS_READY;
7269 }
7270 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007271 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007272 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007273 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007274 // Hardware buffer can hold a large amount of audio so we must
7275 // wait for all current track's data to drain before we say
7276 // that the track is stopped.
7277 if (mBytesRemaining == 0) {
7278 // Only start draining when all data in mixbuffer
7279 // has been written
7280 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007281 track->setState(IAfTrackBase::STOPPING_2);
7282 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007283 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7284 if (last && !mStandby) {
7285 // do not modify drain sequence if we are already draining. This happens
7286 // when resuming from pause after drain.
7287 if ((mDrainSequence & 1) == 0) {
7288 mSleepTimeUs = 0;
7289 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7290 mixerStatus = MIXER_DRAIN_TRACK;
7291 mDrainSequence += 2;
7292 }
7293 if (mHwPaused) {
7294 // It is possible to move from PAUSED to STOPPING_1 without
7295 // a resume so we must ensure hardware is running
7296 doHwResume = true;
7297 mHwPaused = false;
7298 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007299 }
7300 }
Eric Laurente93cc032016-05-05 10:15:10 -07007301 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007302 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007303 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007304 }
7305 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007306 // Drain has completed or we are in standby, signal presentation complete
7307 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007308 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007309 mOutput->presentationComplete();
7310 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007311 track->reset();
7312 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007313 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007314 if (!mUseAsyncWrite) {
7315 // If we don't get explicit drain notification we must
7316 // register discontinuity regardless of whether this is
7317 // the previous (!last) or the upcoming (last) track
7318 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007319 mTimestampVerifier.discontinuity(
7320 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007321 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007322 }
7323 } else {
7324 // No buffers for this track. Give it a few chances to
7325 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007326 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007327 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007328 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007329 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007330 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007331 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007332 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7333 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007334 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007335 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007336 // it will then automatically call start() when data is available
7337 track->disable();
7338 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007339 } else if (last){
7340 mixerStatus = MIXER_TRACKS_ENABLED;
7341 }
7342 }
7343 }
7344 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007345 if (track->isReady()) { // check ready to prevent premature start.
7346 processVolume_l(track, last);
7347 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007348 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007349
Eric Laurentea0fade2013-10-04 16:23:48 -07007350 // make sure the pause/flush/resume sequence is executed in the right order.
7351 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7352 // before flush and then resume HW. This can happen in case of pause/flush/resume
7353 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007354 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007355 status_t result = mOutput->stream->pause();
7356 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007357 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007358 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007359 if (mFlushPending) {
7360 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007361 }
Eric Laurentfd477972013-10-25 18:10:40 -07007362 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007363 status_t result = mOutput->stream->resume();
7364 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007365 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007366
Eric Laurentbfb1b832013-01-07 09:53:42 -08007367 // remove all the tracks that need to be...
7368 removeTracks_l(*tracksToRemove);
7369
7370 return mixerStatus;
7371}
7372
Eric Laurentbfb1b832013-01-07 09:53:42 -08007373// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007374bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007375{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007376 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7377 mWriteAckSequence, mDrainSequence);
7378 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007379 return true;
7380 }
7381 return false;
7382}
7383
Andy Hungee58e4a2023-07-07 13:47:37 -07007384bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007385{
7386 Mutex::Autolock _l(mLock);
7387 return waitingAsyncCallback_l();
7388}
7389
Andy Hungee58e4a2023-07-07 13:47:37 -07007390void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007391{
Eric Laurente659ef42014-09-29 13:06:46 -07007392 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007393 // Flush anything still waiting in the mixbuffer
7394 mCurrentWriteLength = 0;
7395 mBytesRemaining = 0;
7396 mPausedWriteLength = 0;
7397 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007398 // reset bytes written count to reflect that DSP buffers are empty after flush.
7399 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007400
Eric Laurentbfb1b832013-01-07 09:53:42 -08007401 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007402 // discard any pending drain or write ack by incrementing sequence
7403 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7404 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007405 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007406 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7407 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007408 }
7409}
7410
Andy Hungee58e4a2023-07-07 13:47:37 -07007411void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007412{
7413 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007414 if (PlaybackThread::invalidateTracks_l(streamType)) {
7415 mFlushPending = true;
7416 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007417}
7418
Andy Hungee58e4a2023-07-07 13:47:37 -07007419void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08007420 Mutex::Autolock _l(mLock);
7421 if (PlaybackThread::invalidateTracks_l(portIds)) {
7422 mFlushPending = true;
7423 }
7424}
7425
Eric Laurentbfb1b832013-01-07 09:53:42 -08007426// ----------------------------------------------------------------------------
7427
Andy Hungee58e4a2023-07-07 13:47:37 -07007428/* static */
7429sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007430 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007431 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007432 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007433}
7434
Andy Hung583043b2023-07-17 17:05:00 -07007435DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007436 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007437 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007438 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007439 mWaitTimeMs(UINT_MAX)
7440{
7441 addOutputTrack(mainThread);
7442}
7443
Andy Hungee58e4a2023-07-07 13:47:37 -07007444DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007445{
7446 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7447 mOutputTracks[i]->destroy();
7448 }
7449}
7450
Andy Hungee58e4a2023-07-07 13:47:37 -07007451void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007452{
7453 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007454 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007455 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007456 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007457 if (mMixerBufferValid) {
7458 memset(mMixerBuffer, 0, mMixerBufferSize);
7459 } else {
7460 memset(mSinkBuffer, 0, mSinkBufferSize);
7461 }
Eric Laurent81784c32012-11-19 14:55:58 -08007462 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007463 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007464 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007465 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007466 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007467}
7468
Andy Hungee58e4a2023-07-07 13:47:37 -07007469void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007470{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007471 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007472 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007473 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007474 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007475 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007476 }
7477 } else if (mBytesWritten != 0) {
7478 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7479 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007480 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007481 } else {
7482 // flush remaining overflow buffers in output tracks
7483 writeFrames = 0;
7484 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007485 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007486 }
7487}
7488
Andy Hungee58e4a2023-07-07 13:47:37 -07007489ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007490{
7491 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007492 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7493
7494 // Consider the first OutputTrack for timestamp and frame counting.
7495
7496 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7497 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7498 // we always claim success.
7499 if (i == 0) {
7500 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7501 ALOGD_IF(correction != 0 && writeFrames != 0,
7502 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7503 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7504 mFramesWritten -= correction;
7505 }
7506
7507 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007508 }
Andy Hungcf10d742020-04-28 15:38:24 -07007509 if (mStandby) {
7510 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007511 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007512 mStandby = false;
7513 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007514 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007515}
7516
Andy Hungee58e4a2023-07-07 13:47:37 -07007517void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007518{
7519 // DuplicatingThread implements standby by stopping all tracks
7520 for (size_t i = 0; i < outputTracks.size(); i++) {
7521 outputTracks[i]->stop();
7522 }
7523}
7524
Andy Hungee58e4a2023-07-07 13:47:37 -07007525void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007526{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007527 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007528
7529 std::stringstream ss;
7530 const size_t numTracks = mOutputTracks.size();
7531 ss << " " << numTracks << " OutputTracks";
7532 if (numTracks > 0) {
7533 ss << ":";
7534 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007535 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007536 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007537 if (thread.get() != nullptr) {
7538 ss << thread.get() << ", " << thread->id();
7539 } else {
7540 ss << "null";
7541 }
7542 ss << ")";
7543 }
7544 }
7545 ss << "\n";
7546 std::string result = ss.str();
7547 write(fd, result.c_str(), result.size());
7548}
7549
Andy Hungee58e4a2023-07-07 13:47:37 -07007550void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007551{
7552 outputTracks = mOutputTracks;
7553}
7554
Andy Hungee58e4a2023-07-07 13:47:37 -07007555void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007556{
7557 outputTracks.clear();
7558}
7559
Andy Hungee58e4a2023-07-07 13:47:37 -07007560void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007561{
7562 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007563 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7564 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7565 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7566 const size_t frameCount =
7567 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7568 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7569 // from different OutputTracks and their associated MixerThreads (e.g. one may
7570 // nearly empty and the other may be dropping data).
7571
Svet Ganov33761132021-05-13 22:51:08 +00007572 // TODO b/182392769: use attribution source util, move to server edge
7573 AttributionSourceState attributionSource = AttributionSourceState();
7574 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007575 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007576 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007577 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007578 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007579 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007580 this,
7581 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007582 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007583 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007584 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007585 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007586 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7587 if (status != NO_ERROR) {
7588 ALOGE("addOutputTrack() initCheck failed %d", status);
7589 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007590 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007591 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7592 mOutputTracks.add(outputTrack);
7593 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7594 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007595}
7596
Andy Hungee58e4a2023-07-07 13:47:37 -07007597void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007598{
7599 Mutex::Autolock _l(mLock);
7600 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7601 if (mOutputTracks[i]->thread() == thread) {
7602 mOutputTracks[i]->destroy();
7603 mOutputTracks.removeAt(i);
7604 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007605 if (thread->getOutput() == mOutput) {
7606 mOutput = NULL;
7607 }
Eric Laurent81784c32012-11-19 14:55:58 -08007608 return;
7609 }
7610 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007611 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007612}
7613
7614// caller must hold mLock
Andy Hungee58e4a2023-07-07 13:47:37 -07007615void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007616{
7617 mWaitTimeMs = UINT_MAX;
7618 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007619 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007620 if (strong != 0) {
7621 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7622 if (waitTimeMs < mWaitTimeMs) {
7623 mWaitTimeMs = waitTimeMs;
7624 }
7625 }
7626 }
7627}
7628
Andy Hungee58e4a2023-07-07 13:47:37 -07007629bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007630{
7631 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007632 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007633 if (thread == 0) {
7634 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7635 outputTracks[i].get());
7636 return false;
7637 }
Andy Hung87c693c2023-07-06 20:56:16 -07007638 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007639 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07007640 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007641 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7642 thread.get());
7643 return false;
7644 }
7645 }
7646 return true;
7647}
7648
Andy Hungee58e4a2023-07-07 13:47:37 -07007649void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007650 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007651{
Kevin Rocard12381092018-04-11 09:19:59 -07007652 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7653 outputTrack->setMetadatas(metadata.tracks);
7654 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007655}
7656
Andy Hungee58e4a2023-07-07 13:47:37 -07007657uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007658{
7659 return (mWaitTimeMs * 1000) / 2;
7660}
7661
Andy Hungee58e4a2023-07-07 13:47:37 -07007662void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007663{
7664 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7665 updateWaitTime_l();
7666
7667 MixerThread::cacheParameters_l();
7668}
7669
Eric Laurentb3f315a2021-07-13 15:09:05 +02007670// ----------------------------------------------------------------------------
7671
Andy Hungee58e4a2023-07-07 13:47:37 -07007672/* static */
7673sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07007674 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007675 AudioStreamOut* output,
7676 audio_io_handle_t id,
7677 bool systemReady,
7678 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07007679 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07007680}
7681
Andy Hung583043b2023-07-17 17:05:00 -07007682SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007683 AudioStreamOut* output,
7684 audio_io_handle_t id,
7685 bool systemReady,
7686 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07007687 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007688{
7689}
7690
Andy Hungee58e4a2023-07-07 13:47:37 -07007691void SpatializerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01007692 MixerThread::onFirstRef();
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007693
Andy Hung41ccf7f2022-12-14 14:25:49 -08007694 const pid_t tid = getTid();
7695 if (tid == -1) {
7696 // Unusual: PlaybackThread::onFirstRef() should set the threadLoop running.
7697 ALOGW("%s: Cannot update Spatializer mixer thread priority, not running", __func__);
7698 } else {
7699 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
7700 if (priorityBoost > 0) {
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007701 stream()->setHalThreadPriority(priorityBoost);
7702 }
7703 }
Eric Laurent68a40a82022-05-03 18:15:04 +02007704}
7705
Andy Hungee58e4a2023-07-07 13:47:37 -07007706void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007707 // if mSupportedLatencyModes is empty, the HAL stream does not support
7708 // latency mode control and we can exit.
7709 if (mSupportedLatencyModes.empty()) {
7710 return;
7711 }
7712 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7713 if (mSupportedLatencyModes.size() == 1) {
7714 // If the HAL only support one latency mode currently, confirm the choice
7715 latencyMode = mSupportedLatencyModes[0];
7716 } else if (mSupportedLatencyModes.size() > 1) {
7717 // Request low latency if:
7718 // - The low latency mode is requested by the spatializer controller
7719 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7720 // AND
7721 // - At least one active track is spatialized
7722 bool hasSpatializedActiveTrack = false;
7723 for (const auto& track : mActiveTracks) {
7724 if (track->isSpatialized()) {
7725 hasSpatializedActiveTrack = true;
7726 break;
7727 }
7728 }
7729 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7730 latencyMode = AUDIO_LATENCY_MODE_LOW;
7731 }
7732 }
7733
7734 if (latencyMode != mSetLatencyMode) {
7735 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007736 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7737 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007738 if (status == NO_ERROR) {
7739 mSetLatencyMode = latencyMode;
7740 }
7741 }
7742}
7743
Andy Hungee58e4a2023-07-07 13:47:37 -07007744status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007745 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7746 return BAD_VALUE;
7747 }
7748 Mutex::Autolock _l(mLock);
7749 mRequestedLatencyMode = mode;
7750 return NO_ERROR;
7751}
7752
Andy Hungee58e4a2023-07-07 13:47:37 -07007753void SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007754{
7755 bool hasVirtualizer = false;
7756 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007757 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007758 {
7759 Mutex::Autolock _l(mLock);
Andy Hung116bc262023-06-20 18:56:17 -07007760 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007761 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007762 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007763 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7764 }
7765
7766 finalDownMixer = mFinalDownMixer;
7767 mFinalDownMixer.clear();
7768 }
7769
7770 if (hasVirtualizer) {
7771 if (finalDownMixer != nullptr) {
7772 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007773 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007774 }
7775 finalDownMixer.clear();
7776 } else if (!hasDownMixer) {
7777 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07007778 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007779 EFFECT_UIID_DOWNMIX, &descriptors);
7780 if (status != NO_ERROR) {
7781 return;
7782 }
7783 ALOG_ASSERT(!descriptors.empty(),
7784 "%s getDescriptors() returned no error but empty list", __func__);
7785
7786 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7787 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007788 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007789
7790 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7791 ALOGW("%s error creating downmixer %d", __func__, status);
7792 finalDownMixer.clear();
7793 } else {
7794 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007795 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007796 }
7797 }
7798
7799 {
7800 Mutex::Autolock _l(mLock);
7801 mFinalDownMixer = finalDownMixer;
7802 }
7803}
7804
Eric Laurent81784c32012-11-19 14:55:58 -08007805// ----------------------------------------------------------------------------
7806// Record
7807// ----------------------------------------------------------------------------
7808
Andy Hung583043b2023-07-17 17:05:00 -07007809sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007810 AudioStreamIn* input,
7811 audio_io_handle_t id,
7812 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007813 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07007814}
7815
Andy Hung583043b2023-07-17 17:05:00 -07007816RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007817 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007818 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007819 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007820 ) :
Andy Hung583043b2023-07-17 17:05:00 -07007821 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007822 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007823 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007824 mActiveTracks(&this->mLocalLog),
7825 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007826 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007827 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007828 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7829 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007830 // mFastCapture below
7831 , mFastCaptureFutex(0)
7832 // mInputSource
7833 // mPipeSink
7834 // mPipeSource
7835 , mPipeFramesP2(0)
7836 // mPipeMemory
7837 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007838 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007839 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007840{
Glenn Kastend7dca052015-03-05 16:05:54 -08007841 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07007842 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007843
George Burgess IVa8f90c12020-05-14 11:27:19 -07007844 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007845 mIsMsdDevice = strcmp(
7846 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7847 }
7848
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007849 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007850
Andy Hungc8fddf32018-08-08 18:32:37 -07007851 // TODO: We may also match on address as well as device type for
7852 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007853 // TODO: This property should be ensure that only contains one single device type.
7854 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7855 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007856 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7857 : AUDIO_DEVICE_NONE));
7858
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007859 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007860 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007861 size_t numCounterOffers = 0;
7862 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007863#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007864 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007865#else
7866 (void)
7867#endif
7868 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007869 ALOG_ASSERT(index == 0);
7870
7871 // initialize fast capture depending on configuration
7872 bool initFastCapture;
7873 switch (kUseFastCapture) {
7874 case FastCapture_Never:
7875 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007876 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007877 break;
7878 case FastCapture_Always:
7879 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007880 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007881 break;
7882 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007883 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
7884 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7885 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d "
7886 "mIsMsdDevice = %d", this, (long long)mFrameCount, mSampleRate,
7887 kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007888 break;
7889 // case FastCapture_Dynamic:
7890 }
7891
7892 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007893 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007894 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007895 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7896 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007897 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007898 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007899 const sp<MemoryDealer> roHeap(readOnlyHeap());
7900 sp<IMemory> pipeMemory;
7901 if ((roHeap == 0) ||
7902 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007903 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007904 ALOGE("not enough memory for pipe buffer size=%zu; "
7905 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7906 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7907 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007908 goto failed;
7909 }
7910 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7911 memset(pipeBuffer, 0, pipeSize);
7912 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07007913 const NBAIO_Format offersFast[1] = {format};
7914 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007915 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07007916 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007917 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007918 mPipeSink = pipe;
7919 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07007920 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007921 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07007922 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007923 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007924 mPipeSource = pipeReader;
7925 mPipeFramesP2 = pipeFramesP2;
7926 mPipeMemory = pipeMemory;
7927
7928 // create fast capture
7929 mFastCapture = new FastCapture();
7930 FastCaptureStateQueue *sq = mFastCapture->sq();
7931#ifdef STATE_QUEUE_DUMP
7932 // FIXME
7933#endif
7934 FastCaptureState *state = sq->begin();
7935 state->mCblk = NULL;
7936 state->mInputSource = mInputSource.get();
7937 state->mInputSourceGen++;
7938 state->mPipeSink = pipe;
7939 state->mPipeSinkGen++;
7940 state->mFrameCount = mFrameCount;
7941 state->mCommand = FastCaptureState::COLD_IDLE;
7942 // already done in constructor initialization list
7943 //mFastCaptureFutex = 0;
7944 state->mColdFutexAddr = &mFastCaptureFutex;
7945 state->mColdGen++;
7946 state->mDumpState = &mFastCaptureDumpState;
7947#ifdef TEE_SINK
7948 // FIXME
7949#endif
Andy Hung583043b2023-07-17 17:05:00 -07007950 mFastCaptureNBLogWriter =
7951 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007952 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7953 sq->end();
7954 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7955
7956 // start the fast capture
7957 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7958 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007959 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007960 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007961#ifdef AUDIO_WATCHDOG
7962 // FIXME
7963#endif
7964
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007965 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007966 }
Andy Hung8946a282018-04-19 20:04:56 -07007967#ifdef TEE_SINK
7968 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7969 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7970#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007971failed: ;
7972
7973 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007974}
7975
Andy Hungee58e4a2023-07-07 13:47:37 -07007976RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007977{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007978 if (mFastCapture != 0) {
7979 FastCaptureStateQueue *sq = mFastCapture->sq();
7980 FastCaptureState *state = sq->begin();
7981 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7982 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7983 if (old == -1) {
7984 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7985 }
7986 }
7987 state->mCommand = FastCaptureState::EXIT;
7988 sq->end();
7989 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7990 mFastCapture->join();
7991 mFastCapture.clear();
7992 }
Andy Hung583043b2023-07-17 17:05:00 -07007993 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
7994 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007995 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007996}
7997
Andy Hungee58e4a2023-07-07 13:47:37 -07007998void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08007999{
Glenn Kastend7dca052015-03-05 16:05:54 -08008000 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008001}
8002
Andy Hungee58e4a2023-07-07 13:47:37 -07008003void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008004{
8005 ALOGV(" preExit()");
8006 Mutex::Autolock _l(mLock);
8007 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008008 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008009 track->invalidate();
8010 }
8011 mActiveTracks.clear();
8012 mStartStopCond.broadcast();
8013}
8014
Andy Hungee58e4a2023-07-07 13:47:37 -07008015bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008016{
Eric Laurent81784c32012-11-19 14:55:58 -08008017 nsecs_t lastWarning = 0;
8018
8019 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008020
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008021reacquire_wakelock:
Andy Hung8d31fd22023-06-26 19:20:57 -07008022 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008023 {
8024 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07008025 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008026 }
8027
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008028 // used to request a deferred sleep, to be executed later while mutex is unlocked
8029 uint32_t sleepUs = 0;
8030
Andy Hung446f4df2019-02-21 12:26:41 -08008031 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8032
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008033 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008034 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung116bc262023-06-20 18:56:17 -07008035 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008036
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008037 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008038 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008039
Glenn Kasten735f45f2014-08-18 15:51:59 -07008040 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008041 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008042
Glenn Kasten735f45f2014-08-18 15:51:59 -07008043 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008044 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008045
Eric Laurent33403f02020-05-29 18:35:06 -07008046 bool silenceFastCapture = false;
8047
Eric Laurent81784c32012-11-19 14:55:58 -08008048 { // scope for mLock
8049 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08008050
Eric Laurent021cf962014-05-13 10:18:14 -07008051 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008052
Eric Laurent000a4192014-01-29 15:17:32 -08008053 // check exitPending here because checkForNewParameters_l() and
8054 // checkForNewParameters_l() can temporarily release mLock
8055 if (exitPending()) {
8056 break;
8057 }
8058
Eric Laurent5c25d562016-07-13 17:17:45 -07008059 // sleep with mutex unlocked
8060 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008061 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07008062 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
8063 ATRACE_END();
8064 sleepUs = 0;
8065 continue;
8066 }
8067
Glenn Kasten2b806402013-11-20 16:37:38 -08008068 // if no active track(s), then standby and release wakelock
8069 size_t size = mActiveTracks.size();
8070 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008071 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008072 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008073 releaseWakeLock_l();
8074 ALOGV("RecordThread: loop stopping");
8075 // go to sleep
8076 mWaitWorkCV.wait(mLock);
8077 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008078 goto reacquire_wakelock;
8079 }
8080
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008081 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008082 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008083 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008084
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008085 activeTrack = mActiveTracks[i];
8086 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008087 if (activeTrack->isFastTrack()) {
8088 ALOG_ASSERT(fastTrackToRemove == 0);
8089 fastTrackToRemove = activeTrack;
8090 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008091 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008092 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008093 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008094 continue;
8095 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008096
Andy Hung8d31fd22023-06-26 19:20:57 -07008097 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008098 switch (activeTrackState) {
8099
Andy Hung8d31fd22023-06-26 19:20:57 -07008100 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008101 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008102 activeTrack->setState(IAfTrackBase::PAUSED);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008103 doBroadcast = true;
8104 size--;
8105 continue;
8106
Andy Hung8d31fd22023-06-26 19:20:57 -07008107 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008108 sleepUs = 10000;
8109 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008110 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008111 continue;
8112
Andy Hung8d31fd22023-06-26 19:20:57 -07008113 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008114 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008115 if (mStandby) {
8116 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008117 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008118 mStandby = false;
8119 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008120 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008121 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008122 break;
8123
Andy Hung8d31fd22023-06-26 19:20:57 -07008124 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008125 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008126 break;
8127
Andy Hung8d31fd22023-06-26 19:20:57 -07008128 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8129 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8130 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008131 default:
Andy Hungce685402018-10-05 17:23:27 -07008132 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8133 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008134 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008135
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008136 if (activeTrack->isFastTrack()) {
8137 ALOG_ASSERT(!mFastTrackAvail);
8138 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008139 // if the active fast track is silenced either:
8140 // 1) silence the whole capture from fast capture buffer if this is
8141 // the only active track
8142 // 2) invalidate this track: this will cause the client to reconnect and possibly
8143 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008144 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008145 if (activeTrack->isSilenced()) {
8146 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008147 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008148 } else {
8149 silenceFastCapture = true;
8150 }
8151 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008152 // Invalidate fast tracks if access to audio history is required as this is not
8153 // possible with fast tracks. Once the fast track has been invalidated, no new
8154 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8155 if (mMaxSharedAudioHistoryMs != 0) {
8156 invalidate = true;
8157 }
8158 if (invalidate) {
8159 activeTrack->invalidate();
8160 ALOG_ASSERT(fastTrackToRemove == 0);
8161 fastTrackToRemove = activeTrack;
8162 removeTrack_l(activeTrack);
8163 mActiveTracks.remove(activeTrack);
8164 size--;
8165 continue;
8166 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008167 fastTrack = activeTrack;
8168 }
Eric Laurent33403f02020-05-29 18:35:06 -07008169
8170 activeTracks.add(activeTrack);
8171 i++;
8172
Glenn Kasten9e982352013-08-14 14:39:50 -07008173 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008174
Andy Hungdae27702016-10-31 14:01:16 -07008175 mActiveTracks.updatePowerState(this);
8176
Kevin Rocard069c2712018-03-29 19:09:14 -07008177 updateMetadata_l();
8178
Eric Laurent5c25d562016-07-13 17:17:45 -07008179 if (allStopped) {
8180 standbyIfNotAlreadyInStandby();
8181 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008182 if (doBroadcast) {
8183 mStartStopCond.broadcast();
8184 }
8185
8186 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008187 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008188 if (sleepUs == 0) {
8189 sleepUs = kRecordThreadSleepUs;
8190 }
8191 continue;
8192 }
8193 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008194
Eric Laurent81784c32012-11-19 14:55:58 -08008195 lockEffectChains_l(effectChains);
8196 }
8197
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008198 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008199
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008200 size_t size = effectChains.size();
8201 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008202 // thread mutex is not locked, but effect chain is locked
8203 effectChains[i]->process_l();
8204 }
8205
Glenn Kasten735f45f2014-08-18 15:51:59 -07008206 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008207 if (mFastCapture != 0) {
8208 FastCaptureStateQueue *sq = mFastCapture->sq();
8209 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008210 bool didModify = false;
8211 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008212 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8213 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8214 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8215 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8216 if (old == -1) {
8217 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8218 }
8219 }
8220 state->mCommand = FastCaptureState::READ_WRITE;
8221#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008222 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008223 FastThreadDumpState::kSamplingNforLowRamDevice :
8224 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008225#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008226 didModify = true;
8227 }
8228 audio_track_cblk_t *cblkOld = state->mCblk;
8229 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8230 if (cblkNew != cblkOld) {
8231 state->mCblk = cblkNew;
8232 // block until acked if removing a fast track
8233 if (cblkOld != NULL) {
8234 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8235 }
8236 didModify = true;
8237 }
jiabin01c8f562018-07-19 17:47:28 -07008238 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8239 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8240 if (state->mFastPatchRecordBufferProvider != abp) {
8241 state->mFastPatchRecordBufferProvider = abp;
8242 state->mFastPatchRecordFormat = fastTrack == 0 ?
8243 AUDIO_FORMAT_INVALID : fastTrack->format();
8244 didModify = true;
8245 }
Eric Laurent33403f02020-05-29 18:35:06 -07008246 if (state->mSilenceCapture != silenceFastCapture) {
8247 state->mSilenceCapture = silenceFastCapture;
8248 didModify = true;
8249 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008250 sq->end(didModify);
8251 if (didModify) {
8252 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008253#if 0
8254 if (kUseFastCapture == FastCapture_Dynamic) {
8255 mNormalSource = mPipeSource;
8256 }
8257#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008258 }
8259 }
8260
Glenn Kasten735f45f2014-08-18 15:51:59 -07008261 // now run the fast track destructor with thread mutex unlocked
8262 fastTrackToRemove.clear();
8263
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008264 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8265 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8266 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8267 // If destination is non-contiguous, first read past the nominal end of buffer, then
8268 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008269
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008270 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008271 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008272 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008273
8274 // If an NBAIO source is present, use it to read the normal capture's data
8275 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008276 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008277
8278 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8279 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8280 // we immediately retry the read() to get data and prevent another overflow.
8281 for (int retries = 0; retries <= 2; ++retries) {
8282 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8283 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8284 framesToRead);
8285 if (framesRead != OVERRUN) break;
8286 }
8287
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008288 const ssize_t availableToRead = mPipeSource->availableToRead();
8289 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008290 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008291 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008292 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8293 "more frames to read than fifo size, %zd > %zu",
8294 availableToRead, mPipeFramesP2);
8295 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8296 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8297 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8298 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008299 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8300 }
8301 if (framesRead < 0) {
8302 status_t status = (status_t) framesRead;
8303 switch (status) {
8304 case OVERRUN:
8305 ALOGW("overrun on read from pipe");
8306 framesRead = 0;
8307 break;
8308 case NEGOTIATE:
8309 ALOGE("re-negotiation is needed");
8310 framesRead = -1; // Will cause an attempt to recover.
8311 break;
8312 default:
8313 ALOGE("unknown error %d on read from pipe", status);
8314 break;
8315 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008316 }
8317 // otherwise use the HAL / AudioStreamIn directly
8318 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008319 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008320 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008321 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008322 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008323 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008324 if (result < 0) {
8325 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008326 } else {
8327 framesRead = bytesRead / mFrameSize;
8328 }
8329 }
8330
Andy Hung446f4df2019-02-21 12:26:41 -08008331 const int64_t lastIoEndNs = systemTime(); // end IO timing
8332
Andy Hung3f0c9022016-01-15 17:49:46 -08008333 // Update server timestamp with server stats
8334 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008335 if (framesRead >= 0) {
8336 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8337 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8338 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008339
8340 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008341 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008342 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008343 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008344 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8345 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8346 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008347 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008348 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8349
8350 mTimestampVerifier.add(position, time, mSampleRate);
8351
8352 // Correct timestamps
8353 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008354 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008355 id(), (long long)time, (long long)position);
8356 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8357 position = correctedTimestamp.mFrames;
8358 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008359 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008360 id(), (long long)time, (long long)position);
8361 }
8362
Andy Hung3f0c9022016-01-15 17:49:46 -08008363 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8364 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8365 // Note: In general record buffers should tend to be empty in
8366 // a properly running pipeline.
8367 //
8368 // Also, it is not advantageous to call get_presentation_position during the read
8369 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008370 } else {
8371 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008372 }
8373 }
Andy Hunge6c37112019-02-26 17:38:10 -08008374
8375 // From the timestamp, input read latency is negative output write latency.
8376 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008377 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008378 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8379 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8380 mLatencyMs.add(latencyMs);
8381 }
8382
Andy Hung3f0c9022016-01-15 17:49:46 -08008383 // Use this to track timestamp information
8384 // ALOGD("%s", mTimestamp.toString().c_str());
8385
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008386 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008387 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008388 // Force input into standby so that it tries to recover at next read attempt
8389 inputStandBy();
8390 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008391 }
8392 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008393 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008394 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008395 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008396 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008397
Andy Hung8946a282018-04-19 20:04:56 -07008398#ifdef TEE_SINK
8399 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8400#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008401 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008402 {
8403 size_t part1 = mRsmpInFramesP2 - rear;
8404 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008405 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008406 (framesRead - part1) * mFrameSize);
8407 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008408 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008409 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008410
8411 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008412
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008413 // loop over each active track
8414 for (size_t i = 0; i < size; i++) {
8415 activeTrack = activeTracks[i];
8416
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008417 // skip fast tracks, as those are handled directly by FastCapture
8418 if (activeTrack->isFastTrack()) {
8419 continue;
8420 }
8421
Andy Hung73c02e42015-03-29 01:13:58 -07008422 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008423 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8424
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008425 enum {
8426 OVERRUN_UNKNOWN,
8427 OVERRUN_TRUE,
8428 OVERRUN_FALSE
8429 } overrun = OVERRUN_UNKNOWN;
8430
8431 // loop over getNextBuffer to handle circular sink
8432 for (;;) {
8433
Andy Hung8d31fd22023-06-26 19:20:57 -07008434 activeTrack->sinkBuffer().frameCount = ~0;
8435 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8436 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008437 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8438
Andy Hung73c02e42015-03-29 01:13:58 -07008439 // check available frames and handle overrun conditions
8440 // if the record track isn't draining fast enough.
8441 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008442 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008443 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008444 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008445 overrun = OVERRUN_TRUE;
8446 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008447 if (framesOut == 0 || framesIn == 0) {
8448 break;
8449 }
8450
Andy Hung6770c6f2015-04-07 13:43:36 -07008451 // Don't allow framesOut to be larger than what is possible with resampling
8452 // from framesIn.
8453 // This isn't strictly necessary but helps limit buffer resizing in
8454 // RecordBufferConverter. TODO: remove when no longer needed.
8455 framesOut = min(framesOut,
8456 destinationFramesPossible(
Andy Hung8d31fd22023-06-26 19:20:57 -07008457 framesIn, mSampleRate, activeTrack->sampleRate()));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008458
8459 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008460 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008461 // straight from RecordThread buffer to RecordTrack buffer.
8462 AudioBufferProvider::Buffer buffer;
8463 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008464 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008465 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008466 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008467 ALOGV_IF(buffer.frameCount != framesOut,
8468 "%s() read less than expected (%zu vs %zu)",
8469 __func__, buffer.frameCount, framesOut);
8470 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008471 memcpy(activeTrack->sinkBuffer().raw,
8472 buffer.raw, buffer.frameCount * mFrameSize);
8473 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008474 } else {
8475 framesOut = 0;
8476 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008477 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008478 }
8479 } else {
8480 // process frames from the RecordThread buffer provider to the RecordTrack
8481 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008482 framesOut = activeTrack->recordBufferConverter()->convert(
8483 activeTrack->sinkBuffer().raw,
8484 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008485 framesOut);
8486 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008487
8488 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8489 overrun = OVERRUN_FALSE;
8490 }
8491
Andy Hung93bb5732023-05-04 21:16:34 -07008492 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8493 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008494 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008495 if (framesToDrop == 0) {
8496 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008497 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008498 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008499 // Sanitize before releasing if the track has no access to the source data
8500 // An idle UID receives silence from non virtual devices until active
8501 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008502 memset(activeTrack->sinkBuffer().raw,
8503 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008504 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008505 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008506 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008507 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008508 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008509 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008510 }
8511 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008512
8513 switch (overrun) {
8514 case OVERRUN_TRUE:
8515 // client isn't retrieving buffers fast enough
8516 if (!activeTrack->setOverflow()) {
8517 nsecs_t now = systemTime();
8518 // FIXME should lastWarning per track?
8519 if ((now - lastWarning) > kWarningThrottleNs) {
8520 ALOGW("RecordThread: buffer overflow");
8521 lastWarning = now;
8522 }
8523 }
8524 break;
8525 case OVERRUN_FALSE:
8526 activeTrack->clearOverflow();
8527 break;
8528 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008529 break;
8530 }
8531
Andy Hung3f0c9022016-01-15 17:49:46 -08008532 // update frame information and push timestamp out
8533 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008534 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008535 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8536 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008537 }
8538
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008539unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008540 // enable changes in effect chain
8541 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008542 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008543 if (audio_has_proportional_frames(mFormat)
8544 && loopCount == lastLoopCountRead + 1) {
8545 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8546 const double jitterMs =
8547 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8548 {framesRead, readPeriodNs},
8549 {0, 0} /* lastTimestamp */, mSampleRate);
8550 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8551
8552 Mutex::Autolock _l(mLock);
8553 mIoJitterMs.add(jitterMs);
8554 mProcessTimeMs.add(processMs);
8555 }
8556 // update timing info.
8557 mLastIoBeginNs = lastIoBeginNs;
8558 mLastIoEndNs = lastIoEndNs;
8559 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008560 }
8561
Glenn Kasten93e471f2013-08-19 08:40:07 -07008562 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008563
8564 {
8565 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008566 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008567 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008568 track->invalidate();
8569 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008570 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008571 mStartStopCond.broadcast();
8572 }
8573
8574 releaseWakeLock();
8575
8576 ALOGV("RecordThread %p exiting", this);
8577 return false;
8578}
8579
Andy Hungee58e4a2023-07-07 13:47:37 -07008580void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008581{
8582 if (!mStandby) {
8583 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008584 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008585 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008586 mStandby = true;
8587 }
8588}
8589
Andy Hungee58e4a2023-07-07 13:47:37 -07008590void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008591{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008592 // Idle the fast capture if it's currently running
8593 if (mFastCapture != 0) {
8594 FastCaptureStateQueue *sq = mFastCapture->sq();
8595 FastCaptureState *state = sq->begin();
8596 if (!(state->mCommand & FastCaptureState::IDLE)) {
8597 state->mCommand = FastCaptureState::COLD_IDLE;
8598 state->mColdFutexAddr = &mFastCaptureFutex;
8599 state->mColdGen++;
8600 mFastCaptureFutex = 0;
8601 sq->end();
8602 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8603 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8604#if 0
8605 if (kUseFastCapture == FastCapture_Dynamic) {
8606 // FIXME
8607 }
8608#endif
8609#ifdef AUDIO_WATCHDOG
8610 // FIXME
8611#endif
8612 } else {
8613 sq->end(false /*didModify*/);
8614 }
8615 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008616 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008617 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008618
8619 // If going into standby, flush the pipe source.
8620 if (mPipeSource.get() != nullptr) {
8621 const ssize_t flushed = mPipeSource->flush();
8622 if (flushed > 0) {
8623 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8624 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8625 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8626 }
8627 }
Eric Laurent81784c32012-11-19 14:55:58 -08008628}
8629
Glenn Kasten05997e22014-03-13 15:08:33 -07008630// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07008631sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008632 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008633 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008634 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008635 audio_format_t format,
8636 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008637 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008638 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008639 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008640 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008641 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008642 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008643 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008644 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008645 audio_port_handle_t portId,
8646 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008647{
Glenn Kasten74935e42013-12-19 08:56:45 -08008648 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008649 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008650 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008651 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008652 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008653 audio_input_flags_t requestedFlags = *flags;
8654 uint32_t sampleRate;
8655
8656 lStatus = initCheck();
8657 if (lStatus != NO_ERROR) {
8658 ALOGE("createRecordTrack_l() audio driver not initialized");
8659 goto Exit;
8660 }
8661
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008662 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8663 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8664 lStatus = BAD_VALUE;
8665 goto Exit;
8666 }
8667
Eric Laurentec376dc2021-04-08 20:41:22 +02008668 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008669 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008670 lStatus = PERMISSION_DENIED;
8671 goto Exit;
8672 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008673 if (maxSharedAudioHistoryMs < 0
8674 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8675 lStatus = BAD_VALUE;
8676 goto Exit;
8677 }
8678 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008679 if (*pSampleRate == 0) {
8680 *pSampleRate = mSampleRate;
8681 }
8682 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008683
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008684 // special case for FAST flag considered OK if fast capture is present and access to
8685 // audio history is not required
8686 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008687 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8688 }
8689
Eric Laurentf14db3c2017-12-08 14:20:36 -08008690 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008691 if ((*flags & inputFlags) != *flags) {
8692 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8693 " input flags (%08x)",
8694 *flags, inputFlags);
8695 *flags = (audio_input_flags_t)(*flags & inputFlags);
8696 }
Eric Laurent81784c32012-11-19 14:55:58 -08008697
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008698 // client expresses a preference for FAST and no access to audio history,
8699 // but we get the final say
8700 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008701 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008702 // we formerly checked for a callback handler (non-0 tid),
8703 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008704 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008705 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008706 // Frame count is not specified (0), or is less than or equal the pipe depth.
8707 // It is OK to provide a higher capacity than requested.
8708 // We will force it to mPipeFramesP2 below.
8709 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008710 // PCM data
8711 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008712 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008713 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008714 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008715 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008716 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008717 hasFastCapture() &&
8718 // there are sufficient fast track slots available
8719 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008720 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008721 // check compatibility with audio effects.
8722 Mutex::Autolock _l(mLock);
8723 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008724 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008725 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008726 audio_input_flags_t old = *flags;
8727 chain->checkInputFlagCompatibility(flags);
8728 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008729 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8730 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008731 }
8732 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008733 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008734 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8735 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008736 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008737 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8738 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008739 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008740 this, frameCount, mFrameCount, mPipeFramesP2,
8741 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008742 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008743 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008744 }
8745 }
8746
Eric Laurentf14db3c2017-12-08 14:20:36 -08008747 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8748 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8749 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8750 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8751 lStatus = BAD_TYPE;
8752 goto Exit;
8753 }
8754
Glenn Kasten74105912014-07-03 12:28:53 -07008755 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008756 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008757 // fast track: frame count is exactly the pipe depth
8758 frameCount = mPipeFramesP2;
8759 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008760 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008761 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008762 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8763 // or 20 ms if there is a fast capture
8764 // TODO This could be a roundupRatio inline, and const
8765 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8766 * sampleRate + mSampleRate - 1) / mSampleRate;
8767 // minimum number of notification periods is at least kMinNotifications,
8768 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8769 static const size_t kMinNotifications = 3;
8770 static const uint32_t kMinMs = 30;
8771 // TODO This could be a roundupRatio inline
8772 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8773 // TODO This could be a roundupRatio inline
8774 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8775 maxNotificationFrames;
8776 const size_t minFrameCount = maxNotificationFrames *
8777 max(kMinNotifications, minNotificationsByMs);
8778 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008779 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8780 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008781 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008782 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008783 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008784 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008785
8786 { // scope for mLock
8787 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008788 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008789 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008790 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008791 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008792 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008793 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008794 }
Eric Laurent81784c32012-11-19 14:55:58 -08008795
Andy Hung8d31fd22023-06-26 19:20:57 -07008796 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008797 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008798 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07008799 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008800 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008801
Glenn Kasten03003332013-08-06 15:40:54 -07008802 lStatus = track->initCheck();
8803 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008804 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008805 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008806 goto Exit;
8807 }
8808 mTracks.add(track);
8809
Eric Laurent05067782016-06-01 18:27:28 -07008810 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008811 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8812 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8813 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008814 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008815 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008816
8817 if (maxSharedAudioHistoryMs != 0) {
8818 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8819 }
Eric Laurent81784c32012-11-19 14:55:58 -08008820 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008821
Eric Laurent81784c32012-11-19 14:55:58 -08008822 lStatus = NO_ERROR;
8823
8824Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008825 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008826 return track;
8827}
8828
Andy Hungee58e4a2023-07-07 13:47:37 -07008829status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08008830 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008831 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008832{
8833 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8834 sp<ThreadBase> strongMe = this;
8835 status_t status = NO_ERROR;
8836
8837 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008838 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008839 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008840 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07008841 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07008842 event, triggerSession,
8843 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08008844 }
8845
8846 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008847 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008848 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008849 if (recordTrack->isInvalid()) {
8850 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008851 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8852 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008853 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008854 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008855 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008856 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8857 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008858 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07008859 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008860 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07008861 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008862 }
8863 return status;
8864 }
8865
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008866 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8867 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8868 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07008869 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08008870 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008871 if (recordTrack->isExternalTrack()) {
8872 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008873 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008874 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008875 if (recordTrack->isInvalid()) {
8876 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07008877 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
8878 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07008879 // STARTING_2 forces destroy to call stopInput.
8880 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008881 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8882 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008883 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008884 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07008885 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07008886 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07008887 // Someone else has changed state, let them take over,
8888 // leave mState in the new state.
8889 recordTrack->clearSyncStartEvent();
8890 return INVALID_OPERATION;
8891 }
8892 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008893 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008894 ALOGW("%s(%d): startInput failed, status %d",
8895 __func__, recordTrack->id(), status);
8896 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8897 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008898 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008899 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008900 return status;
8901 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008902 sendIoConfigEvent_l(
8903 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008904 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008905
8906 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8907
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008908 // Catch up with current buffer indices if thread is already running.
8909 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8910 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8911 // see previously buffered data before it called start(), but with greater risk of overrun.
8912
Andy Hung8d31fd22023-06-26 19:20:57 -07008913 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008914 if (!recordTrack->isDirect()) {
8915 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07008916 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008917 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008918 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08008919 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008920 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008921 return status;
8922 }
Eric Laurent81784c32012-11-19 14:55:58 -08008923}
8924
Andy Hungee58e4a2023-07-07 13:47:37 -07008925void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08008926{
Andy Hungee58e4a2023-07-07 13:47:37 -07008927 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08008928
8929 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07008930 sp<IAfTrackBase> ptr =
8931 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
8932 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07008933 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07008934 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08008935 }
Eric Laurent81784c32012-11-19 14:55:58 -08008936 }
8937}
8938
Andy Hungee58e4a2023-07-07 13:47:37 -07008939bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008940 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008941 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008942 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07008943 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008944 return false;
8945 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008946 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07008947 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07008948
Andy Hungabfab202019-03-07 19:45:54 -08008949 // NOTE: Waiting here is important to keep stop synchronous.
8950 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07008951 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungce685402018-10-05 17:23:27 -07008952 mWaitWorkCV.broadcast(); // signal thread to stop
8953 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008954 }
Andy Hungce685402018-10-05 17:23:27 -07008955
Andy Hung8d31fd22023-06-26 19:20:57 -07008956 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008957 ALOGV("Record stopped OK");
8958 return true;
8959 }
Andy Hungce685402018-10-05 17:23:27 -07008960
8961 // don't handle anything - we've been invalidated or restarted and in a different state
8962 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07008963 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008964 return false;
8965}
8966
Andy Hungee58e4a2023-07-07 13:47:37 -07008967bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08008968{
8969 return false;
8970}
8971
Andy Hungee58e4a2023-07-07 13:47:37 -07008972status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08008973{
8974#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8975 if (!isValidSyncEvent(event)) {
8976 return BAD_VALUE;
8977 }
8978
Glenn Kastend848eb42016-03-08 13:42:11 -08008979 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008980 status_t ret = NAME_NOT_FOUND;
8981
8982 Mutex::Autolock _l(mLock);
8983
8984 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008985 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08008986 if (eventSession == track->sessionId()) {
8987 (void) track->setSyncEvent(event);
8988 ret = NO_ERROR;
8989 }
8990 }
8991 return ret;
8992#else
8993 return BAD_VALUE;
8994#endif
8995}
8996
Andy Hungee58e4a2023-07-07 13:47:37 -07008997status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07008998 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08008999{
9000 ALOGV("RecordThread::getActiveMicrophones");
9001 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009002 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009003 return NO_INIT;
9004 }
jiabin9ff780e2018-03-19 18:19:52 -07009005 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9006 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009007}
9008
Andy Hungee58e4a2023-07-07 13:47:37 -07009009status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009010 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009011{
Paul McLean12340082019-03-19 09:35:05 -06009012 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009013 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009014 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009015 return NO_INIT;
9016 }
Paul McLean12340082019-03-19 09:35:05 -06009017 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009018}
9019
Andy Hungee58e4a2023-07-07 13:47:37 -07009020status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009021{
Paul McLean12340082019-03-19 09:35:05 -06009022 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009023 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009024 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009025 return NO_INIT;
9026 }
Paul McLean12340082019-03-19 09:35:05 -06009027 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009028}
9029
Andy Hungee58e4a2023-07-07 13:47:37 -07009030status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009031 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9032 int64_t sharedAudioStartMs) {
9033 AutoMutex _l(mLock);
9034 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9035}
9036
Andy Hungee58e4a2023-07-07 13:47:37 -07009037status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009038 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9039 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009040
Eric Laurentec376dc2021-04-08 20:41:22 +02009041 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9042 return BAD_VALUE;
9043 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009044
9045 if (sharedAudioStartMs < 0
9046 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009047 return BAD_VALUE;
9048 }
9049
Eric Laurent2407ce32021-04-26 14:56:03 +02009050 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9051 // As we cannot detect more than one wraparound, only accept values up current write position
9052 // after one wraparound
9053 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9054 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009055 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009056 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9057 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009058 // Bring the start frame position within the input buffer to match the documented
9059 // "best effort" behavior of the API.
9060 if (sharedOffset < 0) {
9061 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009062 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009063 sharedAudioStartFrames =
9064 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009065 }
9066
Eric Laurentec376dc2021-04-08 20:41:22 +02009067 mSharedAudioPackageName = sharedAudioPackageName;
9068 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009069 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009070 } else {
9071 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009072 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009073 }
9074 return NO_ERROR;
9075}
9076
Andy Hungee58e4a2023-07-07 13:47:37 -07009077void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009078 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9079 mSharedAudioStartFrames = -1;
9080 mSharedAudioPackageName = "";
9081}
9082
Andy Hungee58e4a2023-07-07 13:47:37 -07009083ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009084{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009085 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009086 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009087 }
9088 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009089 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009090 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009091 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009092 }
9093 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009094 MetadataUpdate change;
9095 change.recordMetadataUpdate = metadata.tracks;
9096 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009097}
9098
Eric Laurent81784c32012-11-19 14:55:58 -08009099// destroyTrack_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -07009100void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009101{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009102 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009103 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009104
Eric Laurent81784c32012-11-19 14:55:58 -08009105 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009106 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009107 removeTrack_l(track);
9108 }
9109}
9110
Andy Hungee58e4a2023-07-07 13:47:37 -07009111void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009112{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009113 String8 result;
9114 track->appendDump(result, false /* active */);
9115 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
9116
Eric Laurent81784c32012-11-19 14:55:58 -08009117 mTracks.remove(track);
9118 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009119 if (track->isFastTrack()) {
9120 ALOG_ASSERT(!mFastTrackAvail);
9121 mFastTrackAvail = true;
9122 }
Eric Laurent81784c32012-11-19 14:55:58 -08009123}
9124
Andy Hungee58e4a2023-07-07 13:47:37 -07009125void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009126{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009127 AudioStreamIn *input = mInput;
9128 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9129 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009130 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009131 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009132 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009133 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009134 }
Andy Hungbfa64962017-06-12 14:43:19 -07009135
9136 if (input != nullptr) {
9137 dprintf(fd, " Hal stream dump:\n");
9138 (void)input->stream->dump(fd);
9139 }
9140
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009141 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009142 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009143
Glenn Kasten2f90c512015-12-02 11:40:09 -08009144 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9145 // while we are dumping it. It may be inconsistent, but it won't mutate!
9146 // This is a large object so we place it on the heap.
9147 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009148 const std::unique_ptr<FastCaptureDumpState> copy =
9149 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009150 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009151}
9152
Andy Hungee58e4a2023-07-07 13:47:37 -07009153void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009154{
Eric Laurent81784c32012-11-19 14:55:58 -08009155 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009156 size_t numtracks = mTracks.size();
9157 size_t numactive = mActiveTracks.size();
9158 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009159 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009160 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009161 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009162 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009163 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009164 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009165 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009166 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009167 if (track != 0) {
9168 bool active = mActiveTracks.indexOf(track) >= 0;
9169 if (active) {
9170 numactiveseen++;
9171 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009172 result.append(prefix);
9173 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009174 }
Eric Laurent81784c32012-11-19 14:55:58 -08009175 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009176 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009177 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009178 }
9179
Marco Nelissenb2208842014-02-07 14:00:50 -08009180 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009181 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009182 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009183 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009184 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009185 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009186 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009187 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009188 result.append(prefix);
9189 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009190 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009191 }
Eric Laurent81784c32012-11-19 14:55:58 -08009192
9193 }
9194 write(fd, result.string(), result.size());
9195}
9196
Andy Hungee58e4a2023-07-07 13:47:37 -07009197void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009198{
9199 Mutex::Autolock _l(mLock);
9200 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009201 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009202 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009203 track->setSilenced(silenced);
9204 }
9205 }
9206}
Andy Hung73c02e42015-03-29 01:13:58 -07009207
Andy Hung8d31fd22023-06-26 19:20:57 -07009208void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009209{
Andy Hung87c693c2023-07-06 20:56:16 -07009210 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009211 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009212 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009213 const int32_t rear = recordThread->mRsmpInRear;
9214 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009215 if (mRecordTrack->startFrames() >= 0) {
9216 int32_t startFrames = mRecordTrack->startFrames();
9217 // Accept a recent wraparound of mRsmpInRear
9218 if (startFrames <= rear) {
9219 deltaFrames = rear - startFrames;
9220 } else {
9221 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009222 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009223 // start frame cannot be further in the past than start of resampling buffer
9224 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9225 deltaFrames = recordThread->mRsmpInFrames;
9226 }
9227 }
9228 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009229}
9230
Andy Hung8d31fd22023-06-26 19:20:57 -07009231void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009232 size_t *framesAvailable, bool *hasOverrun)
9233{
Andy Hung87c693c2023-07-06 20:56:16 -07009234 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009235 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009236 const int32_t rear = recordThread->mRsmpInRear;
9237 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009238 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009239
9240 size_t framesIn;
9241 bool overrun = false;
9242 if (filled < 0) {
9243 // should not happen, but treat like a massive overrun and re-sync
9244 framesIn = 0;
9245 mRsmpInFront = rear;
9246 overrun = true;
9247 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9248 framesIn = (size_t) filled;
9249 } else {
9250 // client is not keeping up with server, but give it latest data
9251 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009252 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9253 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009254 overrun = true;
9255 }
9256 if (framesAvailable != NULL) {
9257 *framesAvailable = framesIn;
9258 }
9259 if (hasOverrun != NULL) {
9260 *hasOverrun = overrun;
9261 }
9262}
9263
Eric Laurent81784c32012-11-19 14:55:58 -08009264// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009265status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009266 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009267{
Andy Hung87c693c2023-07-06 20:56:16 -07009268 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009269 if (threadBase == 0) {
9270 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009271 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009272 return NOT_ENOUGH_DATA;
9273 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009274 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009275 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009276 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009277 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009278 // FIXME should not be P2 (don't want to increase latency)
9279 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009280 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009281 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009282
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009283 front &= recordThread->mRsmpInFramesP2 - 1;
9284 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009285 if (part1 > (size_t) filled) {
9286 part1 = filled;
9287 }
9288 size_t ask = buffer->frameCount;
9289 ALOG_ASSERT(ask > 0);
9290 if (part1 > ask) {
9291 part1 = ask;
9292 }
9293 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009294 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009295 buffer->raw = NULL;
9296 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009297 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009298 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009299 }
9300
Andy Hung57446612015-04-19 23:56:46 -07009301 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009302 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009303 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009304 return NO_ERROR;
9305}
9306
9307// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009308void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009309 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009310{
Hongwei Wang95e37682019-04-12 11:13:36 -07009311 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009312 if (stepCount == 0) {
9313 return;
9314 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009315 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009316 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009317 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009318 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009319 buffer->frameCount = 0;
9320}
9321
Andy Hungee58e4a2023-07-07 13:47:37 -07009322void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009323{
9324 Mutex::Autolock _l(mLock);
9325 checkBtNrec_l();
9326}
9327
Andy Hungee58e4a2023-07-07 13:47:37 -07009328void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009329{
9330 // disable AEC and NS if the device is a BT SCO headset supporting those
9331 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009332 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009333 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009334 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9335 for (size_t i = 0; i < mEffectChains.size(); i++) {
9336 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9337 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9338 }
9339 }
9340}
9341
Andy Hung97a893e2015-03-29 01:03:07 -07009342
Andy Hungee58e4a2023-07-07 13:47:37 -07009343bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009344 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009345{
9346 bool reconfig = false;
9347
Eric Laurent10351942014-05-08 18:49:52 -07009348 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009349
Eric Laurent10351942014-05-08 18:49:52 -07009350 audio_format_t reqFormat = mFormat;
9351 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009352 // 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 +08009353 [[maybe_unused]] audio_channel_mask_t channelMask =
9354 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009355
9356 AudioParameter param = AudioParameter(keyValuePair);
9357 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009358
9359 // scope for AutoPark extends to end of method
9360 AutoPark<FastCapture> park(mFastCapture);
9361
Eric Laurent10351942014-05-08 18:49:52 -07009362 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9363 // channel count change can be requested. Do we mandate the first client defines the
9364 // HAL sampling rate and channel count or do we allow changes on the fly?
9365 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9366 samplingRate = value;
9367 reconfig = true;
9368 }
9369 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009370 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009371 status = BAD_VALUE;
9372 } else {
9373 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009374 reconfig = true;
9375 }
Eric Laurent10351942014-05-08 18:49:52 -07009376 }
9377 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9378 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009379 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009380 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009381 status = BAD_VALUE;
9382 } else {
9383 channelMask = mask;
9384 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009385 }
Eric Laurent10351942014-05-08 18:49:52 -07009386 }
9387 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9388 // do not accept frame count changes if tracks are open as the track buffer
9389 // size depends on frame count and correct behavior would not be guaranteed
9390 // if frame count is changed after track creation
9391 if (mActiveTracks.size() > 0) {
9392 status = INVALID_OPERATION;
9393 } else {
9394 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009395 }
Eric Laurent10351942014-05-08 18:49:52 -07009396 }
9397 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009398 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009399 }
9400 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9401 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009402 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009403 }
Glenn Kastene198c362013-08-13 09:13:36 -07009404
Eric Laurent10351942014-05-08 18:49:52 -07009405 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009406 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009407 if (status == INVALID_OPERATION) {
9408 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009409 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009410 }
9411 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009412 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009413 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9414 if (mInput->stream->getAudioProperties(&config) == OK &&
9415 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9416 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009417 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009418 status = NO_ERROR;
9419 }
Eric Laurent81784c32012-11-19 14:55:58 -08009420 }
Eric Laurent10351942014-05-08 18:49:52 -07009421 if (status == NO_ERROR) {
9422 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009423 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009424 }
9425 }
Eric Laurent81784c32012-11-19 14:55:58 -08009426 }
Eric Laurent10351942014-05-08 18:49:52 -07009427
Eric Laurent81784c32012-11-19 14:55:58 -08009428 return reconfig;
9429}
9430
Andy Hungee58e4a2023-07-07 13:47:37 -07009431String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009432{
Eric Laurent81784c32012-11-19 14:55:58 -08009433 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009434 if (initCheck() == NO_ERROR) {
9435 String8 out_s8;
9436 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9437 return out_s8;
9438 }
Eric Laurent81784c32012-11-19 14:55:58 -08009439 }
Andy Hung920f6572022-10-06 12:09:49 -07009440 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009441}
9442
Andy Hungee58e4a2023-07-07 13:47:37 -07009443void RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009444 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009445 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009446 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009447 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009448 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009449 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009450 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9451 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009452 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009453 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009454 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009455 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009456 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009457 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009458 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009459 break;
9460 }
Andy Hung583043b2023-07-17 17:05:00 -07009461 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009462}
9463
Andy Hungee58e4a2023-07-07 13:47:37 -07009464void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009465{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009466 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9467 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009468 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009469 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9470 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009471 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9472 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009473 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009474 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009475 ALOGI("HAL format %#x is not linear pcm", mFormat);
9476 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009477 result = mInput->stream->getFrameSize(&mFrameSize);
9478 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009479 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9480 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009481 result = mInput->stream->getBufferSize(&mBufferSize);
9482 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009483 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009484 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9485 "mBufferSize=%zu, mFrameCount=%zu",
9486 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009487
Eric Laurentec376dc2021-04-08 20:41:22 +02009488 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9489 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009490 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009491
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009492 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9493 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009494
9495 audio_input_flags_t flags = mInput->flags;
9496 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9497 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9498 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9499 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9500 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9501 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9502 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9503 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9504 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009505}
9506
Andy Hungee58e4a2023-07-07 13:47:37 -07009507uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009508{
9509 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009510 uint32_t result;
9511 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9512 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009513 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009514 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009515}
9516
Andy Hungee58e4a2023-07-07 13:47:37 -07009517KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009518{
Glenn Kastend848eb42016-03-08 13:42:11 -08009519 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009520 Mutex::Autolock _l(mLock);
9521 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009522 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009523 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009524 if (ids.indexOfKey(sessionId) < 0) {
9525 ids.add(sessionId, true);
9526 }
9527 }
9528 return ids;
9529}
9530
Andy Hungee58e4a2023-07-07 13:47:37 -07009531AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009532{
9533 Mutex::Autolock _l(mLock);
9534 AudioStreamIn *input = mInput;
9535 mInput = NULL;
9536 return input;
9537}
9538
9539// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009540sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009541{
9542 if (mInput == NULL) {
9543 return NULL;
9544 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009545 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009546}
9547
Andy Hungee58e4a2023-07-07 13:47:37 -07009548status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009549{
Eric Laurent81784c32012-11-19 14:55:58 -08009550 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009551 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009552 chain->setInBuffer(NULL);
9553 chain->setOutBuffer(NULL);
9554
9555 checkSuspendOnAddEffectChain_l(chain);
9556
Eric Laurent1b928682014-10-02 19:41:47 -07009557 // make sure enabled pre processing effects state is communicated to the HAL as we
9558 // just moved them to a new input stream.
9559 chain->syncHalEffectsState();
9560
Eric Laurent81784c32012-11-19 14:55:58 -08009561 mEffectChains.add(chain);
9562
9563 return NO_ERROR;
9564}
9565
Andy Hungee58e4a2023-07-07 13:47:37 -07009566size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009567{
9568 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009569
9570 for (size_t i = 0; i < mEffectChains.size(); i++) {
9571 if (chain == mEffectChains[i]) {
9572 mEffectChains.removeAt(i);
9573 break;
9574 }
Eric Laurent81784c32012-11-19 14:55:58 -08009575 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009576 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009577}
9578
Andy Hungee58e4a2023-07-07 13:47:37 -07009579status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009580 audio_patch_handle_t *handle)
9581{
9582 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009583
9584 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009585 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009586 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009587 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009588 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009589 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009590 }
9591
Eric Laurentd8365c52017-07-16 15:27:05 -07009592 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009593
9594 // store new source and send to effects
9595 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9596 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009597 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009598 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009599 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009600 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009601
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009602 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009603 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9604 status = hwDevice->createAudioPatch(patch->num_sources,
9605 patch->sources,
9606 patch->num_sinks,
9607 patch->sinks,
9608 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009609 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009610 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9611 patch->sinks[0].ext.mix.usecase.source,
9612 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009613 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009614 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009615
jiabinc52b1ff2019-10-31 17:20:42 -07009616 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009617 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009618 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009619 }
Eric Laurent296fb132015-05-01 11:38:42 -07009620
Andy Hungc2b11cb2020-04-22 09:04:01 -07009621 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009622 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009623 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009624 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009625 // also dispatch to active AudioRecords
9626 for (const auto &track : mActiveTracks) {
9627 track->logEndInterval();
9628 track->logBeginInterval(pathSourcesAsString);
9629 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009630 // Force meteadata update after a route change
9631 mActiveTracks.setHasChanged();
9632
Eric Laurent1c333e22014-05-20 10:48:17 -07009633 return status;
9634}
9635
Andy Hungee58e4a2023-07-07 13:47:37 -07009636status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009637{
9638 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009639
jiabinc52b1ff2019-10-31 17:20:42 -07009640 mPatch = audio_patch{};
9641 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009642
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009643 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009644 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9645 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009646 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009647 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009648 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009649 // Force meteadata update after a route change
9650 mActiveTracks.setHasChanged();
9651
Eric Laurent1c333e22014-05-20 10:48:17 -07009652 return status;
9653}
9654
Andy Hungee58e4a2023-07-07 13:47:37 -07009655void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009656{
wendy lin56aa82b2020-12-02 15:19:55 +08009657 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009658 mOutDevices = outDevices;
9659 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9660 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009661 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009662 }
9663}
9664
Andy Hungee58e4a2023-07-07 13:47:37 -07009665int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009666{
9667 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009668 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009669 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009670 int32_t oldestFront = mRsmpInRear;
9671 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009672 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009673 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009674 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009675 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009676 if (filled > maxFilled) {
9677 oldestFront = front;
9678 maxFilled = filled;
9679 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009680 }
Andy Hung920f6572022-10-06 12:09:49 -07009681 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009682 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9683 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009684 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009685}
9686
Andy Hungee58e4a2023-07-07 13:47:37 -07009687void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009688{
9689 if (offset == 0) {
9690 return;
9691 }
9692 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009693 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009694 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -07009695 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009696 }
9697}
9698
Andy Hungee58e4a2023-07-07 13:47:37 -07009699void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009700{
9701 // This is the formula for calculating the temporary buffer size.
9702 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9703 // 1 full output buffer, regardless of the alignment of the available input.
9704 // The value is somewhat arbitrary, and could probably be even larger.
9705 // A larger value should allow more old data to be read after a track calls start(),
9706 // without increasing latency.
9707 //
9708 // Note this is independent of the maximum downsampling ratio permitted for capture.
9709 size_t minRsmpInFrames = mFrameCount * 7;
9710
9711 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9712 // capture history available to another client using the same session ID:
9713 // dimension the resampler input buffer accordingly.
9714
9715 // Get oldest client read position: getOldestFront_l() must be called before altering
9716 // mRsmpInRear, or mRsmpInFrames
9717 int32_t previousFront = getOldestFront_l();
9718 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9719 int32_t previousRear = mRsmpInRear;
9720 mRsmpInRear = 0;
9721
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009722 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -07009723 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009724 "resizeInputBuffer_l() called with invalid max shared history %d",
9725 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009726 if (maxSharedAudioHistoryMs != 0) {
9727 // resizeInputBuffer_l should never be called with a non zero shared history if the
9728 // buffer was not already allocated
9729 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9730 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9731 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9732 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009733 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009734 return;
9735 }
9736 mRsmpInFrames = rsmpInFrames;
9737 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009738 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009739 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9740 // initialized
9741 if (mRsmpInFrames < minRsmpInFrames) {
9742 mRsmpInFrames = minRsmpInFrames;
9743 }
9744 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9745
9746 // TODO optimize audio capture buffer sizes ...
9747 // Here we calculate the size of the sliding buffer used as a source
9748 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9749 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9750 // be better to have it derived from the pipe depth in the long term.
9751 // The current value is higher than necessary. However it should not add to latency.
9752
9753 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9754 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9755
9756 void *rsmpInBuffer;
9757 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9758 // if posix_memalign fails, will segv here.
9759 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9760
9761 // Copy audio history if any from old buffer before freeing it
9762 if (previousRear != 0) {
9763 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9764 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9765
9766 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9767 previousFront &= previousRsmpInFramesP2 - 1;
9768 size_t part1 = previousRsmpInFramesP2 - previousFront;
9769 if (part1 > (size_t) unread) {
9770 part1 = unread;
9771 }
9772 if (part1 != 0) {
9773 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9774 part1 * mFrameSize);
9775 mRsmpInRear = part1;
9776 part1 = unread - part1;
9777 if (part1 != 0) {
9778 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9779 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9780 mRsmpInRear += part1;
9781 }
9782 }
9783 // Update front for all clients according to new rear
9784 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9785 } else {
9786 mRsmpInRear = 0;
9787 }
9788 free(mRsmpInBuffer);
9789 mRsmpInBuffer = rsmpInBuffer;
9790}
9791
Andy Hungee58e4a2023-07-07 13:47:37 -07009792void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009793{
9794 Mutex::Autolock _l(mLock);
9795 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009796 if (record->getSource()) {
9797 mSource = record->getSource();
9798 }
Eric Laurent83b88082014-06-20 18:31:16 -07009799}
9800
Andy Hungee58e4a2023-07-07 13:47:37 -07009801void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009802{
9803 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009804 if (mSource == record->getSource()) {
9805 mSource = mInput;
9806 }
Eric Laurent83b88082014-06-20 18:31:16 -07009807 destroyTrack_l(record);
9808}
9809
Andy Hungee58e4a2023-07-07 13:47:37 -07009810void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07009811{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009812 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009813 config->role = AUDIO_PORT_ROLE_SINK;
9814 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9815 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009816 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9817 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9818 config->flags.input = mInput->flags;
9819 }
Eric Laurent83b88082014-06-20 18:31:16 -07009820}
Eric Laurent1c333e22014-05-20 10:48:17 -07009821
Eric Laurent6acd1d42017-01-04 14:23:29 -08009822// ----------------------------------------------------------------------------
9823// Mmap
9824// ----------------------------------------------------------------------------
9825
Andy Hung7aa7d102023-07-07 15:58:48 -07009826// Mmap stream control interface implementation. Each MmapThreadHandle controls one
9827// MmapPlaybackThread or MmapCaptureThread instance.
9828class MmapThreadHandle : public MmapStreamInterface {
9829public:
9830 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
9831 ~MmapThreadHandle() override;
9832
9833 // MmapStreamInterface virtuals
9834 status_t createMmapBuffer(int32_t minSizeFrames,
9835 struct audio_mmap_buffer_info* info) final;
9836 status_t getMmapPosition(struct audio_mmap_position* position) final;
9837 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
9838 status_t start(const AudioClient& client,
9839 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
9840 status_t stop(audio_port_handle_t handle) final;
9841 status_t standby() final;
9842 status_t reportData(const void* buffer, size_t frameCount) final;
9843private:
9844 const sp<IAfMmapThread> mThread;
9845};
9846
9847/* static */
9848sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
9849 const sp<IAfMmapThread>& mmapThread) {
9850 return sp<MmapThreadHandle>::make(mmapThread);
9851}
9852
9853MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009854 : mThread(thread)
9855{
Phil Burk9fabbf82017-08-03 12:02:00 -07009856 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009857}
9858
Andy Hung7aa7d102023-07-07 15:58:48 -07009859// MmapStreamInterface could be directly implemented by MmapThread excepting this
9860// special handling on adapter dtor.
9861MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009862{
Phil Burk9fabbf82017-08-03 12:02:00 -07009863 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009864}
9865
Andy Hung7aa7d102023-07-07 15:58:48 -07009866status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009867 struct audio_mmap_buffer_info *info)
9868{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009869 return mThread->createMmapBuffer(minSizeFrames, info);
9870}
9871
Andy Hung7aa7d102023-07-07 15:58:48 -07009872status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009873{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009874 return mThread->getMmapPosition(position);
9875}
9876
Andy Hung7aa7d102023-07-07 15:58:48 -07009877status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -07009878 int64_t *timeNanos) {
9879 return mThread->getExternalPosition(position, timeNanos);
9880}
9881
Andy Hung7aa7d102023-07-07 15:58:48 -07009882status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009883 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009884{
jiabind1f1cb62020-03-24 11:57:57 -07009885 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009886}
9887
Andy Hung7aa7d102023-07-07 15:58:48 -07009888status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009889{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009890 return mThread->stop(handle);
9891}
9892
Andy Hung7aa7d102023-07-07 15:58:48 -07009893status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -08009894{
Eric Laurent18b57012017-02-13 16:23:52 -08009895 return mThread->standby();
9896}
9897
Andy Hung7aa7d102023-07-07 15:58:48 -07009898status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
9899{
jiabinfc791ee2023-02-15 19:43:40 +00009900 return mThread->reportData(buffer, frameCount);
9901}
9902
Eric Laurent6acd1d42017-01-04 14:23:29 -08009903
Andy Hungee58e4a2023-07-07 13:47:37 -07009904MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -07009905 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -07009906 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -07009907 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009908 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009909 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009910 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009911 mActiveTracks(&this->mLocalLog),
9912 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9913 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009914{
Eric Laurent18b57012017-02-13 16:23:52 -08009915 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009916 readHalParameters_l();
9917}
9918
Andy Hungee58e4a2023-07-07 13:47:37 -07009919void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009920{
9921 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9922}
9923
Andy Hungee58e4a2023-07-07 13:47:37 -07009924void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009925{
Andy Hung8d31fd22023-06-26 19:20:57 -07009926 ActiveTracks<IAfMmapTrack> activeTracks;
Eric Laurent331679c2018-04-16 17:03:16 -07009927 {
9928 Mutex::Autolock _l(mLock);
Andy Hung8d31fd22023-06-26 19:20:57 -07009929 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -07009930 activeTracks.add(t);
9931 }
9932 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009933 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009934 stop(t->portId());
9935 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009936 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009937 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009938 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009939 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009940 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009941 }
9942}
9943
9944
Andy Hungee58e4a2023-07-07 13:47:37 -07009945void MmapThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009946 audio_stream_type_t streamType __unused,
9947 audio_session_t sessionId,
9948 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009949 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009950 audio_port_handle_t portId)
9951{
9952 mAttr = *attr;
9953 mSessionId = sessionId;
9954 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009955 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009956 mPortId = portId;
9957}
9958
Andy Hungee58e4a2023-07-07 13:47:37 -07009959status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009960 struct audio_mmap_buffer_info *info)
9961{
9962 if (mHalStream == 0) {
9963 return NO_INIT;
9964 }
Eric Laurent18b57012017-02-13 16:23:52 -08009965 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009966 return mHalStream->createMmapBuffer(minSizeFrames, info);
9967}
9968
Andy Hungee58e4a2023-07-07 13:47:37 -07009969status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -08009970{
9971 if (mHalStream == 0) {
9972 return NO_INIT;
9973 }
9974 return mHalStream->getMmapPosition(position);
9975}
9976
Andy Hungee58e4a2023-07-07 13:47:37 -07009977status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -07009978{
Eric Laurentdda206a2022-07-08 17:28:35 +02009979 // The HAL must receive track metadata before starting the stream
9980 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -07009981 status_t ret = mHalStream->start();
9982 if (ret != NO_ERROR) {
9983 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9984 return ret;
9985 }
Andy Hungcf10d742020-04-28 15:38:24 -07009986 if (mStandby) {
9987 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009988 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07009989 mStandby = false;
9990 }
Eric Laurent331679c2018-04-16 17:03:16 -07009991 return NO_ERROR;
9992}
9993
Andy Hungee58e4a2023-07-07 13:47:37 -07009994status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009995 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009996 audio_port_handle_t *handle)
9997{
Eric Laurenta54f1282017-07-01 19:39:32 -07009998 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009999 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010000 if (mHalStream == 0) {
10001 return NO_INIT;
10002 }
10003
10004 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010005
Eric Laurentdda206a2022-07-08 17:28:35 +020010006 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010007 if (*handle == mPortId) {
Eric Laurentdda206a2022-07-08 17:28:35 +020010008 acquireWakeLock();
10009 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010010 }
10011
10012 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10013
10014 audio_io_handle_t io = mId;
Andy Hung6cd79802023-07-19 16:56:19 -070010015 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010016 client.attributionSource);
10017
Eric Laurenta54f1282017-07-01 19:39:32 -070010018 if (isOutput()) {
10019 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10020 config.sample_rate = mSampleRate;
10021 config.channel_mask = mChannelMask;
10022 config.format = mFormat;
10023 audio_stream_type_t stream = streamType();
10024 audio_output_flags_t flags =
10025 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010026 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010027 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010028 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010029 bool isBitPerfect;
Eric Laurenta54f1282017-07-01 19:39:32 -070010030 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
10031 mSessionId,
10032 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010033 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010034 &config,
10035 flags,
10036 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010037 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010038 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010039 &isSpatialized,
10040 &isBitPerfect);
Kevin Rocard153f92d2018-12-18 18:33:28 -080010041 ALOGD_IF(!secondaryOutputs.empty(),
10042 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010043 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010044 audio_config_base_t config;
10045 config.sample_rate = mSampleRate;
10046 config.channel_mask = mChannelMask;
10047 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010048 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -070010049 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010050 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -070010051 mSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010052 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010053 &config,
10054 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10055 &deviceId,
10056 &portId);
10057 }
10058 // APM should not chose a different input or output stream for the same set of attributes
10059 // and audo configuration
10060 if (ret != NO_ERROR || io != mId) {
10061 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10062 __FUNCTION__, ret, io, mId);
10063 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010064 }
10065
10066 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010067 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010068 } else {
jiabin09609032022-06-15 19:26:01 +000010069 {
10070 // Add the track record before starting input so that the silent status for the
10071 // client can be cached.
10072 Mutex::Autolock _l(mLock);
10073 setClientSilencedState_l(portId, false /*silenced*/);
10074 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010075 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010076 }
10077
Eric Laurent331679c2018-04-16 17:03:16 -070010078 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010079 // abort if start is rejected by audio policy manager
10080 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010081 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010082 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -070010083 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010084 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010085 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010086 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010087 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010088 }
Eric Laurent331679c2018-04-16 17:03:16 -070010089 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010090 } else {
10091 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010092 }
jiabin09609032022-06-15 19:26:01 +000010093 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010094 return PERMISSION_DENIED;
10095 }
10096
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010097 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010098 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10099 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010100 mChannelMask, mSessionId, isOutput(),
10101 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010102 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010103 if (!isOutput()) {
10104 track->setSilenced_l(isClientSilenced_l(portId));
10105 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010106
Eric Laurent4eb58f12018-12-07 16:41:02 -080010107 if (isOutput()) {
10108 // force volume update when a new track is added
10109 mHalVolFloat = -1.0f;
10110 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010111 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010112 if (t->isSilenced_l()
10113 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010114 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010115 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010116 }
10117 }
10118
Eric Laurent6acd1d42017-01-04 14:23:29 -080010119 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010120 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010121 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +020010122 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010123 chain->incTrackCnt();
10124 chain->incActiveTrackCnt();
10125 }
10126
Andy Hungc2b11cb2020-04-22 09:04:01 -070010127 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010128 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010129
10130 if (mActiveTracks.size() == 1) {
10131 ret = exitStandby_l();
10132 }
10133
Eric Laurent6acd1d42017-01-04 14:23:29 -080010134 broadcast_l();
10135
Eric Laurentdda206a2022-07-08 17:28:35 +020010136 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010137
Eric Laurentdda206a2022-07-08 17:28:35 +020010138 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010139}
10140
Andy Hungee58e4a2023-07-07 13:47:37 -070010141status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010142{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010143 ALOGV("%s handle %d", __FUNCTION__, handle);
10144
10145 if (mHalStream == 0) {
10146 return NO_INIT;
10147 }
10148
Eric Laurenta54f1282017-07-01 19:39:32 -070010149 if (handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +000010150 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -070010151 return NO_ERROR;
10152 }
10153
Eric Laurent331679c2018-04-16 17:03:16 -070010154 Mutex::Autolock _l(mLock);
10155
Andy Hung8d31fd22023-06-26 19:20:57 -070010156 sp<IAfMmapTrack> track;
10157 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010158 if (handle == t->portId()) {
10159 track = t;
10160 break;
10161 }
10162 }
10163 if (track == 0) {
10164 return BAD_VALUE;
10165 }
10166
10167 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010168 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010169
Eric Laurent331679c2018-04-16 17:03:16 -070010170 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010171 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010172 AudioSystem::stopOutput(track->portId());
10173 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010174 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010175 AudioSystem::stopInput(track->portId());
10176 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010177 }
Eric Laurent331679c2018-04-16 17:03:16 -070010178 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010179
Andy Hung116bc262023-06-20 18:56:17 -070010180 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010181 if (chain != 0) {
10182 chain->decActiveTrackCnt();
10183 chain->decTrackCnt();
10184 }
10185
Eric Laurentdda206a2022-07-08 17:28:35 +020010186 if (mActiveTracks.isEmpty()) {
10187 mHalStream->stop();
10188 }
10189
Eric Laurent6acd1d42017-01-04 14:23:29 -080010190 broadcast_l();
10191
Eric Laurent6acd1d42017-01-04 14:23:29 -080010192 return NO_ERROR;
10193}
10194
Andy Hungee58e4a2023-07-07 13:47:37 -070010195status_t MmapThread::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010196{
10197 ALOGV("%s", __FUNCTION__);
10198
10199 if (mHalStream == 0) {
10200 return NO_INIT;
10201 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010202 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010203 return INVALID_OPERATION;
10204 }
10205 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010206 if (!mStandby) {
10207 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010208 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010209 mStandby = true;
10210 }
Eric Laurent18b57012017-02-13 16:23:52 -080010211 releaseWakeLock();
10212 return NO_ERROR;
10213}
10214
Andy Hungee58e4a2023-07-07 13:47:37 -070010215status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010216 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10217 return INVALID_OPERATION;
10218}
10219
Andy Hungee58e4a2023-07-07 13:47:37 -070010220void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010221{
10222 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10223 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10224 mFormat = mHALFormat;
10225 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10226 result = mHalStream->getFrameSize(&mFrameSize);
10227 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010228 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10229 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010230 result = mHalStream->getBufferSize(&mBufferSize);
10231 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10232 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010233
Andy Hungcf10d742020-04-28 15:38:24 -070010234 // TODO: make a readHalParameters call?
10235 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010236 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
10237 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
10238 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10239 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10240 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10241 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10242 /*
10243 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10244 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10245 (int32_t)mHapticChannelMask)
10246 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10247 (int32_t)mHapticChannelCount)
10248 */
10249 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
10250 formatToString(mHALFormat).c_str())
10251 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10252 (int32_t)mFrameCount) // sic - added HAL
10253 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010254}
10255
Andy Hungee58e4a2023-07-07 13:47:37 -070010256bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010257{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010258 checkSilentMode_l();
10259
10260 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10261
10262 while (!exitPending())
10263 {
Andy Hung116bc262023-06-20 18:56:17 -070010264 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010265
Andy Hung13850be2019-03-14 11:33:09 -070010266 { // under Thread lock
10267 Mutex::Autolock _l(mLock);
10268
Eric Laurent6acd1d42017-01-04 14:23:29 -080010269 if (mSignalPending) {
10270 // A signal was raised while we were unlocked
10271 mSignalPending = false;
10272 } else {
10273 if (mConfigEvents.isEmpty()) {
10274 // we're about to wait, flush the binder command buffer
10275 IPCThreadState::self()->flushCommands();
10276
10277 if (exitPending()) {
10278 break;
10279 }
10280
Eric Laurent6acd1d42017-01-04 14:23:29 -080010281 // wait until we have something to do...
10282 ALOGV("%s going to sleep", myName.string());
10283 mWaitWorkCV.wait(mLock);
10284 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010285
10286 checkSilentMode_l();
10287
10288 continue;
10289 }
10290 }
10291
10292 processConfigEvents_l();
10293
10294 processVolume_l();
10295
10296 checkInvalidTracks_l();
10297
10298 mActiveTracks.updatePowerState(this);
10299
Kevin Rocard069c2712018-03-29 19:09:14 -070010300 updateMetadata_l();
10301
Eric Laurent6acd1d42017-01-04 14:23:29 -080010302 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010303 } // release Thread lock
10304
Eric Laurent6acd1d42017-01-04 14:23:29 -080010305 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010306 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010307 }
Andy Hung13850be2019-03-14 11:33:09 -070010308
10309 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010310 unlockEffectChains(effectChains);
10311 // Effect chains will be actually deleted here if they were removed from
10312 // mEffectChains list during mixing or effects processing
10313 }
10314
10315 threadLoop_exit();
10316
10317 if (!mStandby) {
10318 threadLoop_standby();
10319 mStandby = true;
10320 }
10321
Eric Laurent6acd1d42017-01-04 14:23:29 -080010322 ALOGV("Thread %p type %d exiting", this, mType);
10323 return false;
10324}
10325
10326// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -070010327bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010328 status_t& status)
10329{
10330 AudioParameter param = AudioParameter(keyValuePair);
10331 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010332 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010333 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010334 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010335 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010336 if (sendToHal) {
10337 status = mHalStream->setParameters(keyValuePair);
10338 } else {
10339 status = NO_ERROR;
10340 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010341
10342 return false;
10343}
10344
Andy Hungee58e4a2023-07-07 13:47:37 -070010345String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010346{
10347 Mutex::Autolock _l(mLock);
10348 String8 out_s8;
10349 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10350 return out_s8;
10351 }
Andy Hung920f6572022-10-06 12:09:49 -070010352 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010353}
10354
Andy Hungee58e4a2023-07-07 13:47:37 -070010355void MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010356 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010357 sp<AudioIoDescriptor> desc;
10358 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010359 switch (event) {
10360 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010361 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010362 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010363 isInput = true;
10364 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010365 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010366 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010367 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010368 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10369 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010370 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010371 case AUDIO_INPUT_CLOSED:
10372 case AUDIO_OUTPUT_CLOSED:
10373 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010374 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010375 break;
10376 }
Andy Hung583043b2023-07-17 17:05:00 -070010377 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010378}
10379
Andy Hungee58e4a2023-07-07 13:47:37 -070010380status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010381 audio_patch_handle_t *handle)
Andy Hung920f6572022-10-06 12:09:49 -070010382NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010383{
10384 status_t status = NO_ERROR;
10385
10386 // store new device and send to effects
10387 audio_devices_t type = AUDIO_DEVICE_NONE;
10388 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010389 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10390 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10391 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010392 if (isOutput()) {
10393 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010394 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10395 && !mAudioHwDev->supportsAudioPatches(),
10396 "Enumerated device type(%#x) must not be used "
10397 "as it does not support audio patches",
10398 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010399 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010400 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10401 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010402 }
10403 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010404 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010405 } else {
10406 type = patch->sources[0].ext.device.type;
10407 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010408 numDevices = mPatch.num_sources;
10409 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010410 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010411 }
10412
10413 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010414 if (isOutput()) {
10415 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10416 } else {
10417 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10418 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010419 }
10420
jiabinc52b1ff2019-10-31 17:20:42 -070010421 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010422 // store new source and send to effects
10423 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10424 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10425 for (size_t i = 0; i < mEffectChains.size(); i++) {
10426 mEffectChains[i]->setAudioSource_l(mAudioSource);
10427 }
10428 }
10429 }
10430
10431 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010432 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10433 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010434 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010435 audio_port_config port;
10436 std::optional<audio_source_t> source;
10437 if (isOutput()) {
10438 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010439 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010440 port = patch->sources[0];
10441 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010442 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010443 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010444 *handle = AUDIO_PATCH_HANDLE_NONE;
10445 }
10446
jiabinc52b1ff2019-10-31 17:20:42 -070010447 if (numDevices == 0 || mDeviceId != deviceId) {
10448 if (isOutput()) {
10449 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10450 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010451 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010452 } else {
10453 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10454 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10455 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010456 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010457 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010458 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010459 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -070010460 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010461 }
jiabinc52b1ff2019-10-31 17:20:42 -070010462 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010463 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010464 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010465 // Force meteadata update after a route change
10466 mActiveTracks.setHasChanged();
10467
Eric Laurent6acd1d42017-01-04 14:23:29 -080010468 return status;
10469}
10470
Andy Hungee58e4a2023-07-07 13:47:37 -070010471status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010472{
10473 status_t status = NO_ERROR;
10474
jiabinc52b1ff2019-10-31 17:20:42 -070010475 mPatch = audio_patch{};
10476 mOutDeviceTypeAddrs.clear();
10477 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010478
10479 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10480 supportsAudioPatches : false;
10481
10482 if (supportsAudioPatches) {
10483 status = mHalDevice->releaseAudioPatch(handle);
10484 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010485 status = mHalStream->legacyReleaseAudioPatch();
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 Hungee58e4a2023-07-07 13:47:37 -070010493void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010494{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010495 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010496 if (isOutput()) {
10497 config->role = AUDIO_PORT_ROLE_SOURCE;
10498 config->ext.mix.hw_module = mAudioHwDev->handle();
10499 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10500 } else {
10501 config->role = AUDIO_PORT_ROLE_SINK;
10502 config->ext.mix.hw_module = mAudioHwDev->handle();
10503 config->ext.mix.usecase.source = mAudioSource;
10504 }
10505}
10506
Andy Hungee58e4a2023-07-07 13:47:37 -070010507status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010508{
10509 audio_session_t session = chain->sessionId();
10510
10511 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10512 // Attach all tracks with same session ID to this chain.
10513 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010514 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010515 if (session == track->sessionId()) {
10516 chain->incTrackCnt();
10517 chain->incActiveTrackCnt();
10518 }
10519 }
10520
10521 chain->setThread(this);
10522 chain->setInBuffer(nullptr);
10523 chain->setOutBuffer(nullptr);
10524 chain->syncHalEffectsState();
10525
10526 mEffectChains.add(chain);
10527 checkSuspendOnAddEffectChain_l(chain);
10528 return NO_ERROR;
10529}
10530
Andy Hungee58e4a2023-07-07 13:47:37 -070010531size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010532{
10533 audio_session_t session = chain->sessionId();
10534
10535 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10536
10537 for (size_t i = 0; i < mEffectChains.size(); i++) {
10538 if (chain == mEffectChains[i]) {
10539 mEffectChains.removeAt(i);
10540 // detach all active tracks from the chain
10541 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010542 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010543 if (session == track->sessionId()) {
10544 chain->decActiveTrackCnt();
10545 chain->decTrackCnt();
10546 }
10547 }
10548 break;
10549 }
10550 }
10551 return mEffectChains.size();
10552}
10553
Andy Hungee58e4a2023-07-07 13:47:37 -070010554void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010555{
10556 mHalStream->standby();
10557}
10558
Andy Hungee58e4a2023-07-07 13:47:37 -070010559void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010560{
Phil Burk7dce7282017-09-27 13:51:41 -070010561 // Do not call callback->onTearDown() because it is redundant for thread exit
10562 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010563}
10564
Andy Hungee58e4a2023-07-07 13:47:37 -070010565status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010566{
10567 return BAD_VALUE;
10568}
10569
Andy Hungee58e4a2023-07-07 13:47:37 -070010570bool MmapThread::isValidSyncEvent(
10571 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010572{
10573 return false;
10574}
10575
Andy Hungee58e4a2023-07-07 13:47:37 -070010576status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010577 const effect_descriptor_t *desc, audio_session_t sessionId)
10578{
10579 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010580 if (audio_is_global_session(sessionId)) {
10581 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010582 desc->name, mThreadName);
10583 return BAD_VALUE;
10584 }
10585
10586 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10587 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10588 desc->name);
10589 return BAD_VALUE;
10590 }
10591 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010592 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10593 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010594 return BAD_VALUE;
10595 }
10596
10597 // Only allow effects without processing load or latency
10598 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10599 return BAD_VALUE;
10600 }
10601
Andy Hung116bc262023-06-20 18:56:17 -070010602 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010603 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10604 return BAD_VALUE;
10605 }
10606
Eric Laurent6acd1d42017-01-04 14:23:29 -080010607 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010608}
10609
Andy Hungee58e4a2023-07-07 13:47:37 -070010610void MmapThread::checkInvalidTracks_l()
Andy Hung920f6572022-10-06 12:09:49 -070010611NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010612{
Eric Laurent039c24a2022-10-07 14:01:59 +020010613 sp<MmapStreamCallback> callback;
Andy Hung8d31fd22023-06-26 19:20:57 -070010614 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010615 if (track->isInvalid()) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010616 callback = mCallback.promote();
10617 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10618 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10619 mNoCallbackWarningCount++;
10620 }
10621 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010622 }
10623 }
Eric Laurent039c24a2022-10-07 14:01:59 +020010624 if (callback != 0) {
10625 mLock.unlock();
10626 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10627 mLock.lock();
jiabindfa32482022-10-06 19:45:50 +000010628 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010629}
10630
Andy Hungee58e4a2023-07-07 13:47:37 -070010631void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010632{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010633 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10634 mAttr.content_type, mAttr.usage, mAttr.source);
10635 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010636 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010637 dprintf(fd, " No active clients\n");
10638 }
10639}
10640
Andy Hungee58e4a2023-07-07 13:47:37 -070010641void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010642{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010643 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010644 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010645 dprintf(fd, " %zu Tracks\n", numtracks);
10646 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010647 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010648 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010649 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010650 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010651 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010652 result.append(prefix);
10653 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010654 }
10655 } else {
10656 dprintf(fd, "\n");
10657 }
10658 write(fd, result.string(), result.size());
10659}
10660
Andy Hungee58e4a2023-07-07 13:47:37 -070010661/* static */
10662sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070010663 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070010664 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070010665 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070010666}
10667
10668MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070010669 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010670 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070010671 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010672 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010673 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010674{
10675 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10676 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070010677 mMasterVolume = afThreadCallback->masterVolume_l();
10678 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010679
10680 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
10681 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
10682 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -070010683 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010684 }
10685 // Audio patch and call assistant volume are always max
10686 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
10687 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
10688 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
10689 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
10690
Eric Laurent6acd1d42017-01-04 14:23:29 -080010691 if (mAudioHwDev) {
10692 if (mAudioHwDev->canSetMasterVolume()) {
10693 mMasterVolume = 1.0;
10694 }
10695
10696 if (mAudioHwDev->canSetMasterMute()) {
10697 mMasterMute = false;
10698 }
10699 }
10700}
10701
Andy Hungee58e4a2023-07-07 13:47:37 -070010702void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010703 audio_stream_type_t streamType,
10704 audio_session_t sessionId,
10705 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010706 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010707 audio_port_handle_t portId)
10708{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010709 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010710 mStreamType = streamType;
10711}
10712
Andy Hungee58e4a2023-07-07 13:47:37 -070010713AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010714{
10715 Mutex::Autolock _l(mLock);
10716 AudioStreamOut *output = mOutput;
10717 mOutput = NULL;
10718 return output;
10719}
10720
Andy Hungee58e4a2023-07-07 13:47:37 -070010721void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010722{
10723 Mutex::Autolock _l(mLock);
10724 // Don't apply master volume in SW if our HAL can do it for us.
10725 if (mAudioHwDev &&
10726 mAudioHwDev->canSetMasterVolume()) {
10727 mMasterVolume = 1.0;
10728 } else {
10729 mMasterVolume = value;
10730 }
10731}
10732
Andy Hungee58e4a2023-07-07 13:47:37 -070010733void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010734{
10735 Mutex::Autolock _l(mLock);
10736 // Don't apply master mute in SW if our HAL can do it for us.
10737 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10738 mMasterMute = false;
10739 } else {
10740 mMasterMute = muted;
10741 }
10742}
10743
Andy Hungee58e4a2023-07-07 13:47:37 -070010744void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010745{
10746 Mutex::Autolock _l(mLock);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010747 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010748 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010749 broadcast_l();
10750 }
10751}
10752
Andy Hungee58e4a2023-07-07 13:47:37 -070010753float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010754{
10755 Mutex::Autolock _l(mLock);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010756 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010757}
10758
Andy Hungee58e4a2023-07-07 13:47:37 -070010759void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010760{
10761 Mutex::Autolock _l(mLock);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010762 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010763 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010764 broadcast_l();
10765 }
10766}
10767
Andy Hungee58e4a2023-07-07 13:47:37 -070010768void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010769{
10770 Mutex::Autolock _l(mLock);
10771 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010772 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010773 track->invalidate();
10774 }
10775 broadcast_l();
10776 }
10777}
10778
Andy Hungee58e4a2023-07-07 13:47:37 -070010779void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010780{
10781 Mutex::Autolock _l(mLock);
10782 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070010783 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010784 if (portIds.find(track->portId()) != portIds.end()) {
10785 track->invalidate();
10786 trackMatch = true;
10787 portIds.erase(track->portId());
10788 }
10789 if (portIds.empty()) {
10790 break;
10791 }
10792 }
10793 if (trackMatch) {
10794 broadcast_l();
10795 }
10796}
10797
Andy Hungee58e4a2023-07-07 13:47:37 -070010798void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070010799NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080010800{
10801 float volume;
10802
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010803 if (mMasterMute || streamMuted_l()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010804 volume = 0;
10805 } else {
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010806 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010807 }
10808
10809 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010810 // Convert volumes from float to 8.24
10811 uint32_t vol = (uint32_t)(volume * (1 << 24));
10812
10813 // Delegate volume control to effect in track effect chain if needed
10814 // only one effect chain can be present on DirectOutputThread, so if
10815 // there is one, the track is connected to it
10816 if (!mEffectChains.isEmpty()) {
10817 mEffectChains[0]->setVolume_l(&vol, &vol);
10818 volume = (float)vol / (1 << 24);
10819 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010820 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010821 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10822 mHalVolFloat = volume; // HW volume control worked, so update value.
10823 mNoCallbackWarningCount = 0;
10824 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010825 sp<MmapStreamCallback> callback = mCallback.promote();
10826 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010827 mHalVolFloat = volume; // SW volume control worked, so update value.
10828 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010829 mLock.unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010830 callback->onVolumeChanged(volume);
Eric Laurent734046e2018-04-16 14:50:52 -070010831 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010832 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010833 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10834 ALOGW("Could not set MMAP stream volume: no volume callback!");
10835 mNoCallbackWarningCount++;
10836 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010837 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010838 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010839 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010840 track->setMetadataHasChanged();
Andy Hung583043b2023-07-17 17:05:00 -070010841 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010842 /*muteState=*/{mMasterMute,
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010843 streamVolume_l() == 0.f,
10844 streamMuted_l(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010845 // TODO(b/241533526): adjust logic to include mute from AppOps
10846 false /*muteFromPlaybackRestricted*/,
10847 false /*muteFromClientVolume*/,
10848 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010849 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010850 }
10851}
10852
Andy Hungee58e4a2023-07-07 13:47:37 -070010853ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070010854{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010855 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010010856 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010857 }
10858 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070010859 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070010860 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010861 playback_track_metadata_v7_t trackMetadata;
10862 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010863 .usage = track->attributes().usage,
10864 .content_type = track->attributes().content_type,
10865 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010866 };
10867 trackMetadata.channel_mask = track->channelMask(),
10868 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10869 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010870 }
10871 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010010872
10873 MetadataUpdate change;
10874 change.playbackMetadataUpdate = metadata.tracks;
10875 return change;
10876};
Kevin Rocard069c2712018-03-29 19:09:14 -070010877
Andy Hungee58e4a2023-07-07 13:47:37 -070010878void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010879{
10880 if (!mMasterMute) {
10881 char value[PROPERTY_VALUE_MAX];
10882 if (property_get("ro.audio.silent", value, "0") > 0) {
10883 char *endptr;
10884 unsigned long ul = strtoul(value, &endptr, 0);
10885 if (*endptr == '\0' && ul != 0) {
10886 ALOGD("Silence is golden");
10887 // The setprop command will not allow a property to be changed after
10888 // the first time it is set, so we don't have to worry about un-muting.
10889 setMasterMute_l(true);
10890 }
10891 }
10892 }
10893}
10894
Andy Hungee58e4a2023-07-07 13:47:37 -070010895void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010896{
10897 MmapThread::toAudioPortConfig(config);
10898 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10899 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10900 config->flags.output = mOutput->flags;
10901 }
10902}
10903
Andy Hungee58e4a2023-07-07 13:47:37 -070010904status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070010905 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070010906{
10907 if (mOutput == nullptr) {
10908 return NO_INIT;
10909 }
10910 struct timespec timestamp;
10911 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10912 if (status == NO_ERROR) {
10913 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10914 }
10915 return status;
10916}
10917
Andy Hungee58e4a2023-07-07 13:47:37 -070010918status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010919 // Send to MelProcessor for sound dose measurement.
10920 auto processor = mMelProcessor.load();
10921 if (processor) {
10922 processor->process(buffer, frameCount * mFrameSize);
10923 }
10924
jiabinfc791ee2023-02-15 19:43:40 +000010925 return NO_ERROR;
10926}
10927
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010928// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -070010929void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010930 const sp<audio_utils::MelProcessor>& processor)
10931{
10932 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010933 mMelProcessor.store(processor);
10934 if (processor) {
10935 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010936 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010937
10938 // no need to update output format for MMapPlaybackThread since it is
10939 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010940}
10941
10942// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hungee58e4a2023-07-07 13:47:37 -070010943void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010944{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010945 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
10946 auto melProcessor = mMelProcessor.load();
10947 if (melProcessor != nullptr) {
10948 melProcessor->pause();
10949 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010950}
10951
Andy Hungee58e4a2023-07-07 13:47:37 -070010952void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010953{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010954 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010955
Glenn Kastend3bb6452016-12-05 18:14:37 -080010956 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010957 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010958 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10959}
10960
Andy Hungee58e4a2023-07-07 13:47:37 -070010961/* static */
10962sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070010963 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070010964 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070010965 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070010966}
10967
10968MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070010969 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010970 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070010971 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010972 mInput(input)
10973{
10974 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10975 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10976}
10977
Andy Hungee58e4a2023-07-07 13:47:37 -070010978status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010979{
Phil Burkf054fc32018-12-06 09:45:59 -080010980 {
10981 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080010982 if (mInput != nullptr && mInput->stream != nullptr) {
10983 mInput->stream->setGain(1.0f);
10984 }
10985 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010986 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010987}
10988
Andy Hungee58e4a2023-07-07 13:47:37 -070010989AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010990{
10991 Mutex::Autolock _l(mLock);
10992 AudioStreamIn *input = mInput;
10993 mInput = NULL;
10994 return input;
10995}
Kevin Rocard069c2712018-03-29 19:09:14 -070010996
Andy Hungee58e4a2023-07-07 13:47:37 -070010997void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010998{
10999 bool changed = false;
11000 bool silenced = false;
11001
11002 sp<MmapStreamCallback> callback = mCallback.promote();
11003 if (callback == 0) {
11004 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11005 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11006 mNoCallbackWarningCount++;
11007 }
11008 }
11009
11010 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11011 // track is silenced and unmute otherwise
11012 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11013 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11014 changed = true;
11015 silenced = mActiveTracks[i]->isSilenced_l();
11016 }
11017 }
11018
11019 if (changed) {
11020 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11021 }
11022}
11023
Andy Hungee58e4a2023-07-07 13:47:37 -070011024ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011025{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011026 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011027 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011028 }
11029 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011030 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011031 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011032 record_track_metadata_v7_t trackMetadata;
11033 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011034 .source = track->attributes().source,
11035 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011036 };
11037 trackMetadata.channel_mask = track->channelMask(),
11038 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11039 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011040 }
11041 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011042 MetadataUpdate change;
11043 change.recordMetadataUpdate = metadata.tracks;
11044 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011045}
11046
Andy Hungee58e4a2023-07-07 13:47:37 -070011047void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011048{
11049 Mutex::Autolock _l(mLock);
11050 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011051 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011052 mActiveTracks[i]->setSilenced_l(silenced);
11053 broadcast_l();
11054 }
11055 }
jiabin09609032022-06-15 19:26:01 +000011056 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011057}
11058
Andy Hungee58e4a2023-07-07 13:47:37 -070011059void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011060{
11061 MmapThread::toAudioPortConfig(config);
11062 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11063 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11064 config->flags.input = mInput->flags;
11065 }
11066}
11067
Andy Hungee58e4a2023-07-07 13:47:37 -070011068status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011069 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011070{
11071 if (mInput == nullptr) {
11072 return NO_INIT;
11073 }
11074 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11075}
11076
jiabinc658e452022-10-21 20:52:21 +000011077// ----------------------------------------------------------------------------
11078
Andy Hungee58e4a2023-07-07 13:47:37 -070011079/* static */
11080sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011081 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011082 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011083 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011084}
11085
Andy Hung583043b2023-07-17 17:05:00 -070011086BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011087 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011088 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011089
Andy Hungee58e4a2023-07-07 13:47:37 -070011090PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011091 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011092 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11093 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011094 float volumeLeft = 1.0f;
11095 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011096 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11097 const int trackId = mActiveTracks[0]->id();
11098 mAudioMixer->setParameter(
11099 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11100 mAudioMixer->setParameter(
11101 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11102 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011103 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011104 mIsBitPerfect = true;
11105 } else {
11106 mIsBitPerfect = false;
11107 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11108 // active.
11109 for (const auto& track : mActiveTracks) {
11110 const int trackId = track->id();
11111 mAudioMixer->setParameter(
11112 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11113 }
11114 }
jiabin76d94692022-12-15 21:51:21 +000011115 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11116 mVolumeLeft = volumeLeft;
11117 mVolumeRight = volumeRight;
11118 setVolumeForOutput_l(volumeLeft, volumeRight);
11119 }
jiabinc658e452022-10-21 20:52:21 +000011120 return result;
11121}
11122
Andy Hungee58e4a2023-07-07 13:47:37 -070011123void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011124 MixerThread::threadLoop_mix();
11125 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11126}
11127
Glenn Kasten63238ef2015-03-02 15:50:29 -080011128} // namespace android