blob: 1f010b3c0c2b76284ec1c34bfcf3219403f78672 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
Vlad Popab042ee62022-10-20 18:05:00 +020020// #define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <memory>
Andy Hungb68f5eb2019-12-03 16:49:17 -080027#include <sstream>
Eric Tan7b651152018-07-13 10:17:19 -070028#include <string>
Glenn Kastenad8510a2015-02-17 16:24:07 -080029#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080030#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080031#include <sys/syscall.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070032#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080033#include <cutils/properties.h>
Vlad Popae8d99472022-06-30 16:02:48 +020034#include <binder/PersistableBundle.h>
jiabinc52b1ff2019-10-31 17:20:42 -070035#include <media/AudioContainers.h>
36#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070037#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070038#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080039#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070040#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080041#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080042#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043
44#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070045#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010046#include <audio_utils/Balance.h>
Vlad Popab042ee62022-10-20 18:05:00 +020047#include <audio_utils/MelProcessor.h>
jiabinf6eb4c32020-02-25 14:06:25 -080048#include <audio_utils/Metadata.h>
jiabin245cdd92018-12-07 17:55:15 -080049#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080050#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080051#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080052#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070053#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070054#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070055#include <system/audio_effects/effect_aec.h>
Eric Laurentb3f315a2021-07-13 15:09:05 +020056#include <system/audio_effects/effect_downmix.h>
57#include <system/audio_effects/effect_ns.h>
Eric Laurent1c5e2e32021-08-18 18:50:28 +020058#include <system/audio_effects/effect_spatializer.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070059#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080060
61// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070062#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080063#include <media/nbaio/AudioStreamOutSink.h>
64#include <media/nbaio/MonoPipe.h>
65#include <media/nbaio/MonoPipeReader.h>
66#include <media/nbaio/Pipe.h>
67#include <media/nbaio/PipeReader.h>
68#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080069#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070070#include <mediautils/Process.h>
Eric Laurent81784c32012-11-19 14:55:58 -080071
Mikhail Naganov2996f672019-04-18 12:29:59 -070072#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080073#include <powermanager/PowerManager.h>
74
Kevin Rocard7588ff42018-01-08 11:11:30 -080075#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070076#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080077
Eric Laurent81784c32012-11-19 14:55:58 -080078#include "AudioFlinger.h"
Andy Hung71742ab2023-07-07 13:47:37 -070079#include "Threads.h"
80
Andy Hungab7ef302018-05-15 19:35:29 -070081#include <mediautils/SchedulingPolicyService.h>
82#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080083
Eric Laurent81784c32012-11-19 14:55:58 -080084#ifdef ADD_BATTERY_DATA
85#include <media/IMediaPlayerService.h>
86#include <media/IMediaDeathNotifier.h>
87#endif
88
Eric Laurent81784c32012-11-19 14:55:58 -080089#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070090#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080091#include <cpustats/ThreadCpuUsage.h>
92#endif
93
Andy Hungbef3a1e2023-05-23 17:36:46 -070094#include <fastpath/AutoPark.h>
Glenn Kastenc05b8d72016-03-24 09:48:17 -070095
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080096#include <pthread.h>
Andy Hung21ff9672023-07-18 20:54:44 -070097#include <afutils/DumpTryLock.h>
Andy Hungc5106312023-07-19 16:56:19 -070098#include <afutils/Permission.h>
Andy Hungb776e372023-05-24 11:53:47 -070099#include <afutils/TypedLogger.h>
Andy Hung9554ec02023-07-20 21:23:42 -0700100#include <afutils/Vibrator.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800101
Eric Laurent81784c32012-11-19 14:55:58 -0800102// ----------------------------------------------------------------------------
103
104// Note: the following macro is used for extremely verbose logging message. In
105// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
106// 0; but one side effect of this is to turn all LOGV's as well. Some messages
107// are so verbose that we want to suppress them even when we have ALOG_ASSERT
108// turned on. Do not uncomment the #def below unless you really know what you
109// are doing and want to see all of the extremely verbose messages.
110//#define VERY_VERY_VERBOSE_LOGGING
111#ifdef VERY_VERY_VERBOSE_LOGGING
112#define ALOGVV ALOGV
113#else
114#define ALOGVV(a...) do { } while(0)
115#endif
116
Andy Hung6770c6f2015-04-07 13:43:36 -0700117// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700118#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700119
Andy Hung6770c6f2015-04-07 13:43:36 -0700120template <typename T>
121static inline T min(const T& a, const T& b)
122{
123 return a < b ? a : b;
124}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700125
Eric Laurent81784c32012-11-19 14:55:58 -0800126namespace android {
127
Andy Hung71742ab2023-07-07 13:47:37 -0700128using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700129using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000130using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700131
Eric Laurent81784c32012-11-19 14:55:58 -0800132// retry counts for buffer fill timeout
133// 50 * ~20msecs = 1 second
134static const int8_t kMaxTrackRetries = 50;
135static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700136
Eric Laurent81784c32012-11-19 14:55:58 -0800137// allow less retry attempts on direct output thread.
138// direct outputs can be a scarce resource in audio hardware and should
139// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700140// Notes:
141// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
142// in case the data write is bursty for the AudioTrack. The application
143// should endeavor to write at least once every kMaxTrackRetriesDirectMs
144// to prevent an underrun situation. If the data is bursty, then
145// the application can also throttle the data sent to be even.
146// 2) For compressed audio data, any data present in the AudioTrack buffer
147// will be sent and reset the retry count. This delivers data as
148// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
149// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
150// of data to be available, then any remaining data is delivered.
151// This is required to ensure the last bit of data is delivered before underrun.
152//
153// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
154// or the size of the HAL period for proportional / linear PCM tracks.
155static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800156
157// don't warn about blocked writes or record buffer overflows more often than this
158static const nsecs_t kWarningThrottleNs = seconds(5);
159
160// RecordThread loop sleep time upon application overrun or audio HAL read error
161static const int kRecordThreadSleepUs = 5000;
162
Eric Laurent10351942014-05-08 18:49:52 -0700163// maximum time to wait in sendConfigEvent_l() for a status to be received
164static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800165
166// minimum sleep time for the mixer thread loop when tracks are active but in underrun
167static const uint32_t kMinThreadSleepTimeUs = 5000;
168// maximum divider applied to the active sleep time in the mixer thread loop
169static const uint32_t kMaxThreadSleepTimeShift = 2;
170
Andy Hung09a50072014-02-27 14:30:47 -0800171// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700172// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800173static const uint32_t kMinNormalSinkBufferSizeMs = 20;
174// maximum normal sink buffer size
175static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800176
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700177// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
178// FIXME This should be based on experimentally observed scheduling jitter
179static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
180
Eric Laurent972a1732013-09-04 09:42:59 -0700181// Offloaded output thread standby delay: allows track transition without going to standby
182static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
183
Eric Laurent51716182016-02-29 18:00:56 -0800184// Direct output thread minimum sleep time in idle or active(underrun) state
185static const nsecs_t kDirectMinSleepTimeUs = 10000;
186
Brian Lindahl9e661ad2022-07-27 18:01:07 +0200187// Minimum amount of time between checking to see if the timestamp is advancing
188// for underrun detection. If we check too frequently, we may not detect a
189// timestamp update and will falsely detect underrun.
190static const nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1000;
191
Glenn Kasten1b291842016-07-18 14:55:21 -0700192// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
193// balance between power consumption and latency, and allows threads to be scheduled reliably
194// by the CFS scheduler.
195// FIXME Express other hardcoded references to 20ms with references to this constant and move
196// it appropriately.
197#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800198
Eric Laurent81784c32012-11-19 14:55:58 -0800199// Whether to use fast mixer
200static const enum {
201 FastMixer_Never, // never initialize or use: for debugging only
202 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
203 // normal mixer multiplier is 1
204 FastMixer_Static, // initialize if needed, then use all the time if initialized,
205 // multiplier is calculated based on min & max normal mixer buffer size
206 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
207 // multiplier is calculated based on min & max normal mixer buffer size
208 // FIXME for FastMixer_Dynamic:
209 // Supporting this option will require fixing HALs that can't handle large writes.
210 // For example, one HAL implementation returns an error from a large write,
211 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
212 // We could either fix the HAL implementations, or provide a wrapper that breaks
213 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
214} kUseFastMixer = FastMixer_Static;
215
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700216// Whether to use fast capture
217static const enum {
218 FastCapture_Never, // never initialize or use: for debugging only
219 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
220 FastCapture_Static, // initialize if needed, then use all the time if initialized
221} kUseFastCapture = FastCapture_Static;
222
Eric Laurent81784c32012-11-19 14:55:58 -0800223// Priorities for requestPriority
224static const int kPriorityAudioApp = 2;
225static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700226static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800227
Glenn Kastenea38ee72016-04-18 11:08:01 -0700228// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
229// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
230// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700231
232// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800233static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800234
Glenn Kasten03490092014-05-27 12:30:54 -0700235// The minimum and maximum allowed values
236static const int kFastTrackMultiplierMin = 1;
237static const int kFastTrackMultiplierMax = 2;
238
239// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
240static int sFastTrackMultiplier = kFastTrackMultiplier;
241
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700242// See Thread::readOnlyHeap().
243// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
244// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
245// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700246static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700247
Andy Hung18bef9b2023-07-20 21:31:38 -0700248static constexpr nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
249
250static nsecs_t getStandbyTimeInNanos() {
251 static nsecs_t standbyTimeInNanos = []() {
252 const int ms = property_get_int32("ro.audio.flinger_standbytime_ms",
253 kDefaultStandbyTimeInNsecs / NANOS_PER_MILLISECOND);
254 ALOGI("%s: Using %d ms as standby time", __func__, ms);
255 return milliseconds(ms);
256 }();
257 return standbyTimeInNanos;
258}
259
Andy Hungf8ab4692023-07-20 21:44:14 -0700260// Set kEnableExtendedChannels to true to enable greater than stereo output
261// for the MixerThread and device sink. Number of channels allowed is
262// FCC_2 <= channels <= FCC_LIMIT.
263constexpr bool kEnableExtendedChannels = true;
264
265// Returns true if channel mask is permitted for the PCM sink in the MixerThread
266/* static */
267bool IAfThreadBase::isValidPcmSinkChannelMask(audio_channel_mask_t channelMask) {
268 switch (audio_channel_mask_get_representation(channelMask)) {
269 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
270 // Haptic channel mask is only applicable for channel position mask.
271 const uint32_t channelCount = audio_channel_count_from_out_mask(
272 static_cast<audio_channel_mask_t>(channelMask & ~AUDIO_CHANNEL_HAPTIC_ALL));
273 const uint32_t maxChannelCount = kEnableExtendedChannels
274 ? FCC_LIMIT : FCC_2;
275 if (channelCount < FCC_2 // mono is not supported at this time
276 || channelCount > maxChannelCount) {
277 return false;
278 }
279 // check that channelMask is the "canonical" one we expect for the channelCount.
280 return audio_channel_position_mask_is_out_canonical(channelMask);
281 }
282 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
283 if (kEnableExtendedChannels) {
284 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
285 if (channelCount >= FCC_2 // mono is not supported at this time
286 && channelCount <= FCC_LIMIT) {
287 return true;
288 }
289 }
290 return false;
291 default:
292 return false;
293 }
294}
295
296// Set kEnableExtendedPrecision to true to use extended precision in MixerThread
297constexpr bool kEnableExtendedPrecision = true;
298
299// Returns true if format is permitted for the PCM sink in the MixerThread
300/* static */
301bool IAfThreadBase::isValidPcmSinkFormat(audio_format_t format) {
302 switch (format) {
303 case AUDIO_FORMAT_PCM_16_BIT:
304 return true;
305 case AUDIO_FORMAT_PCM_FLOAT:
306 case AUDIO_FORMAT_PCM_24_BIT_PACKED:
307 case AUDIO_FORMAT_PCM_32_BIT:
308 case AUDIO_FORMAT_PCM_8_24_BIT:
309 return kEnableExtendedPrecision;
310 default:
311 return false;
312 }
313}
314
Eric Laurent81784c32012-11-19 14:55:58 -0800315// ----------------------------------------------------------------------------
316
Andy Hungb68f5eb2019-12-03 16:49:17 -0800317// TODO: move all toString helpers to audio.h
318// under #ifdef __cplusplus #endif
319static std::string patchSinksToString(const struct audio_patch *patch)
320{
321 std::stringstream ss;
322 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700323 if (i > 0) {
324 ss << "|";
325 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800326 ss << "(" << toString(patch->sinks[i].ext.device.type)
327 << ", " << patch->sinks[i].ext.device.address << ")";
328 }
329 return ss.str();
330}
331
332static std::string patchSourcesToString(const struct audio_patch *patch)
333{
334 std::stringstream ss;
335 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700336 if (i > 0) {
337 ss << "|";
338 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800339 ss << "(" << toString(patch->sources[i].ext.device.type)
340 << ", " << patch->sources[i].ext.device.address << ")";
341 }
342 return ss.str();
343}
344
Andy Hung4bd53e72022-11-17 17:21:45 -0800345static std::string toString(audio_latency_mode_t mode) {
346 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganova77d5552022-12-18 02:48:14 +0000347 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
348 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800349}
350
351// Could be made a template, but other toString overloads for std::vector are confused.
352static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
353 std::string s("{ ");
354 for (const auto& e : elements) {
355 s.append(toString(e));
356 s.append(" ");
357 }
358 s.append("}");
359 return s;
360}
361
Glenn Kasten03490092014-05-27 12:30:54 -0700362static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
363
364static void sFastTrackMultiplierInit()
365{
366 char value[PROPERTY_VALUE_MAX];
367 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
368 char *endptr;
369 unsigned long ul = strtoul(value, &endptr, 0);
370 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
371 sFastTrackMultiplier = (int) ul;
372 }
373 }
374}
375
376// ----------------------------------------------------------------------------
377
Eric Laurent81784c32012-11-19 14:55:58 -0800378#ifdef ADD_BATTERY_DATA
379// To collect the amplifier usage
380static void addBatteryData(uint32_t params) {
381 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
382 if (service == NULL) {
383 // it already logged
384 return;
385 }
386
387 service->addBatteryData(params);
388}
389#endif
390
Andy Hung3f0c9022016-01-15 17:49:46 -0800391// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
392struct {
393 // call when you acquire a partial wakelock
394 void acquire(const sp<IBinder> &wakeLockToken) {
395 pthread_mutex_lock(&mLock);
396 if (wakeLockToken.get() == nullptr) {
397 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
398 } else {
399 if (mCount == 0) {
400 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
401 }
402 ++mCount;
403 }
404 pthread_mutex_unlock(&mLock);
405 }
406
407 // call when you release a partial wakelock.
408 void release(const sp<IBinder> &wakeLockToken) {
409 if (wakeLockToken.get() == nullptr) {
410 return;
411 }
412 pthread_mutex_lock(&mLock);
413 if (--mCount < 0) {
414 ALOGE("negative wakelock count");
415 mCount = 0;
416 }
417 pthread_mutex_unlock(&mLock);
418 }
419
420 // retrieves the boottime timebase offset from monotonic.
421 int64_t getBoottimeOffset() {
422 pthread_mutex_lock(&mLock);
423 int64_t boottimeOffset = mBoottimeOffset;
424 pthread_mutex_unlock(&mLock);
425 return boottimeOffset;
426 }
427
428 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
429 // and the selected timebase.
430 // Currently only TIMEBASE_BOOTTIME is allowed.
431 //
432 // This only needs to be called upon acquiring the first partial wakelock
433 // after all other partial wakelocks are released.
434 //
435 // We do an empirical measurement of the offset rather than parsing
436 // /proc/timer_list since the latter is not a formal kernel ABI.
437 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
438 int clockbase;
439 switch (timebase) {
440 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
441 clockbase = SYSTEM_TIME_BOOTTIME;
442 break;
443 default:
444 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
445 break;
446 }
447 // try three times to get the clock offset, choose the one
448 // with the minimum gap in measurements.
449 const int tries = 3;
Andy Hung71ba4b32022-10-06 12:09:49 -0700450 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800451 for (int i = 0; i < tries; ++i) {
452 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
453 const nsecs_t tbase = systemTime(clockbase);
454 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
455 const nsecs_t gap = tmono2 - tmono;
456 if (i == 0 || gap < bestGap) {
457 bestGap = gap;
458 measured = tbase - ((tmono + tmono2) >> 1);
459 }
460 }
461
462 // to avoid micro-adjusting, we don't change the timebase
463 // unless it is significantly different.
464 //
465 // Assumption: It probably takes more than toleranceNs to
466 // suspend and resume the device.
467 static int64_t toleranceNs = 10000; // 10 us
468 if (llabs(*offset - measured) > toleranceNs) {
469 ALOGV("Adjusting timebase offset old: %lld new: %lld",
470 (long long)*offset, (long long)measured);
471 *offset = measured;
472 }
473 }
474
475 pthread_mutex_t mLock;
476 int32_t mCount;
477 int64_t mBoottimeOffset;
478} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800479
480// ----------------------------------------------------------------------------
481// CPU Stats
482// ----------------------------------------------------------------------------
483
484class CpuStats {
485public:
486 CpuStats();
487 void sample(const String8 &title);
488#ifdef DEBUG_CPU_USAGE
489private:
490 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700491 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800492
Andy Hung16698b82018-08-01 10:48:38 -0700493 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800494
495 int mCpuNum; // thread's current CPU number
496 int mCpukHz; // frequency of thread's current CPU in kHz
497#endif
498};
499
500CpuStats::CpuStats()
501#ifdef DEBUG_CPU_USAGE
502 : mCpuNum(-1), mCpukHz(-1)
503#endif
504{
505}
506
Glenn Kasten0f11b512014-01-31 16:18:54 -0800507void CpuStats::sample(const String8 &title
508#ifndef DEBUG_CPU_USAGE
509 __unused
510#endif
511 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800512#ifdef DEBUG_CPU_USAGE
513 // get current thread's delta CPU time in wall clock ns
514 double wcNs;
515 bool valid = mCpuUsage.sampleAndEnable(wcNs);
516
517 // record sample for wall clock statistics
518 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700519 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800520 }
521
522 // get the current CPU number
523 int cpuNum = sched_getcpu();
524
525 // get the current CPU frequency in kHz
526 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
527
528 // check if either CPU number or frequency changed
529 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
530 mCpuNum = cpuNum;
531 mCpukHz = cpukHz;
532 // ignore sample for purposes of cycles
533 valid = false;
534 }
535
536 // if no change in CPU number or frequency, then record sample for cycle statistics
537 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700538 const double cycles = wcNs * cpukHz * 0.000001;
539 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800540 }
541
Eric Tan5b13ff82018-07-27 11:20:17 -0700542 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800543 // mCpuUsage.elapsed() is expensive, so don't call it every loop
544 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700545 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800546 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700547 const double perLoop = elapsed / (double) n;
548 const double perLoop100 = perLoop * 0.01;
549 const double perLoop1k = perLoop * 0.001;
550 const double mean = mWcStats.getMean();
551 const double stddev = mWcStats.getStdDev();
552 const double minimum = mWcStats.getMin();
553 const double maximum = mWcStats.getMax();
554 const double meanCycles = mHzStats.getMean();
555 const double stddevCycles = mHzStats.getStdDev();
556 const double minCycles = mHzStats.getMin();
557 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800558 mCpuUsage.resetElapsed();
559 mWcStats.reset();
560 mHzStats.reset();
561 ALOGD("CPU usage for %s over past %.1f secs\n"
562 " (%u mixer loops at %.1f mean ms per loop):\n"
563 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
564 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
565 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000566 title.c_str(),
Eric Laurent81784c32012-11-19 14:55:58 -0800567 elapsed * .000000001, n, perLoop * .000001,
568 mean * .001,
569 stddev * .001,
570 minimum * .001,
571 maximum * .001,
572 mean / perLoop100,
573 stddev / perLoop100,
574 minimum / perLoop100,
575 maximum / perLoop100,
576 meanCycles / perLoop1k,
577 stddevCycles / perLoop1k,
578 minCycles / perLoop1k,
579 maxCycles / perLoop1k);
580
581 }
582 }
583#endif
584};
585
586// ----------------------------------------------------------------------------
587// ThreadBase
588// ----------------------------------------------------------------------------
589
Glenn Kasten97b7b752014-09-28 13:04:24 -0700590// static
Andy Hung71742ab2023-07-07 13:47:37 -0700591const char* ThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700592{
593 switch (type) {
594 case MIXER:
595 return "MIXER";
596 case DIRECT:
597 return "DIRECT";
598 case DUPLICATING:
599 return "DUPLICATING";
600 case RECORD:
601 return "RECORD";
602 case OFFLOAD:
603 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700604 case MMAP_PLAYBACK:
605 return "MMAP_PLAYBACK";
606 case MMAP_CAPTURE:
607 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200608 case SPATIALIZER:
609 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000610 case BIT_PERFECT:
611 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700612 default:
613 return "unknown";
614 }
615}
616
Andy Hung2cbc2722023-07-17 17:05:00 -0700617ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700618 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800619 : Thread(false /*canCallJava*/),
620 mType(type),
Andy Hung2cbc2722023-07-17 17:05:00 -0700621 mAfThreadCallback(afThreadCallback),
Andy Hungcf10d742020-04-28 15:38:24 -0700622 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
623 isOut),
624 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700625 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800626 // are set by PlaybackThread::readOutputParameters_l() or
627 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700628 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700629 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700630 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800631 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700632 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800633 mSystemReady(systemReady),
634 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800635{
Andy Hungcf10d742020-04-28 15:38:24 -0700636 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700637 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800638}
639
Andy Hung71742ab2023-07-07 13:47:37 -0700640ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800641{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700642 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700643 mConfigEvents.clear();
644
Eric Laurent81784c32012-11-19 14:55:58 -0800645 // do not lock the mutex in destructor
646 releaseWakeLock_l();
647 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800648 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800649 binder->unlinkToDeath(mDeathRecipient);
650 }
Andy Hungd0979812019-02-21 15:51:44 -0800651
652 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800653}
654
Andy Hung71742ab2023-07-07 13:47:37 -0700655status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700656{
657 status_t status = initCheck();
658 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800659 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700660 } else {
661 ALOGE("No working audio driver found.");
662 }
663 return status;
664}
665
Andy Hung71742ab2023-07-07 13:47:37 -0700666void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800667{
668 ALOGV("ThreadBase::exit");
669 // do any cleanup required for exit to succeed
670 preExit();
671 {
672 // This lock prevents the following race in thread (uniprocessor for illustration):
673 // if (!exitPending()) {
674 // // context switch from here to exit()
675 // // exit() calls requestExit(), what exitPending() observes
676 // // exit() calls signal(), which is dropped since no waiters
677 // // context switch back from exit() to here
678 // mWaitWorkCV.wait(...);
679 // // now thread is hung
680 // }
681 AutoMutex lock(mLock);
682 requestExit();
683 mWaitWorkCV.broadcast();
684 }
685 // When Thread::requestExitAndWait is made virtual and this method is renamed to
686 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
687 requestExitAndWait();
688}
689
Andy Hung71742ab2023-07-07 13:47:37 -0700690status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800691{
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000692 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800693 Mutex::Autolock _l(mLock);
694
Eric Laurent10351942014-05-08 18:49:52 -0700695 return sendSetParameterConfigEvent_l(keyValuePairs);
696}
697
698// sendConfigEvent_l() must be called with ThreadBase::mLock held
699// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hung71742ab2023-07-07 13:47:37 -0700700status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung71ba4b32022-10-06 12:09:49 -0700701NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700702{
703 status_t status = NO_ERROR;
704
Eric Laurent72e3f392015-05-20 14:43:50 -0700705 if (event->mRequiresSystemReady && !mSystemReady) {
706 event->mWaitStatus = false;
707 mPendingConfigEvents.add(event);
708 return status;
709 }
Eric Laurent10351942014-05-08 18:49:52 -0700710 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700711 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800712 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700713 mLock.unlock();
714 {
715 Mutex::Autolock _l(event->mLock);
716 while (event->mWaitStatus) {
717 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
718 event->mStatus = TIMED_OUT;
719 event->mWaitStatus = false;
720 }
721 }
722 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800723 }
Eric Laurent10351942014-05-08 18:49:52 -0700724 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800725 return status;
726}
727
Andy Hung71742ab2023-07-07 13:47:37 -0700728void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700729 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800730{
731 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700732 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800733}
734
735// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -0700736void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700737 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800738{
Andy Hungd0979812019-02-21 15:51:44 -0800739 // The audio statistics history is exponentially weighted to forget events
740 // about five or more seconds in the past. In order to have
741 // crisper statistics for mediametrics, we reset the statistics on
742 // an IoConfigEvent, to reflect different properties for a new device.
743 mIoJitterMs.reset();
744 mLatencyMs.reset();
745 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000746 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100747 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800748
Eric Laurent09f1ed22019-04-24 17:45:17 -0700749 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700750 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800751}
752
Andy Hung71742ab2023-07-07 13:47:37 -0700753void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700754{
755 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800756 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700757}
758
Eric Laurent81784c32012-11-19 14:55:58 -0800759// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -0700760void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800761 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800762{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800763 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700764 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800765}
766
Eric Laurent10351942014-05-08 18:49:52 -0700767// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -0700768status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800769{
Andy Hung2ddee192015-12-18 17:34:44 -0800770 sp<ConfigEvent> configEvent;
771 AudioParameter param(keyValuePair);
772 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700773 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800774 setMasterMono_l(value != 0);
775 if (param.size() == 1) {
776 return NO_ERROR; // should be a solo parameter - we don't pass down
777 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700778 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800779 configEvent = new SetParameterConfigEvent(param.toString());
780 } else {
781 configEvent = new SetParameterConfigEvent(keyValuePair);
782 }
Eric Laurent10351942014-05-08 18:49:52 -0700783 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700784}
785
Andy Hung71742ab2023-07-07 13:47:37 -0700786status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700787 const struct audio_patch *patch,
788 audio_patch_handle_t *handle)
789{
790 Mutex::Autolock _l(mLock);
791 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
792 status_t status = sendConfigEvent_l(configEvent);
793 if (status == NO_ERROR) {
794 CreateAudioPatchConfigEventData *data =
795 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
796 *handle = data->mHandle;
797 }
798 return status;
799}
800
Andy Hung71742ab2023-07-07 13:47:37 -0700801status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700802 const audio_patch_handle_t handle)
803{
804 Mutex::Autolock _l(mLock);
805 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
806 return sendConfigEvent_l(configEvent);
807}
808
Andy Hung71742ab2023-07-07 13:47:37 -0700809status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700810 const DeviceDescriptorBaseVector& outDevices)
811{
812 if (type() != RECORD) {
813 // The update out device operation is only for record thread.
814 return INVALID_OPERATION;
815 }
816 Mutex::Autolock _l(mLock);
817 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
818 return sendConfigEvent_l(configEvent);
819}
820
Andy Hung71742ab2023-07-07 13:47:37 -0700821void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200822{
823 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
824 sp<ConfigEvent> configEvent =
825 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
826 sendConfigEvent_l(configEvent);
827}
Eric Laurent1c333e22014-05-20 10:48:17 -0700828
Andy Hung71742ab2023-07-07 13:47:37 -0700829void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200830{
831 Mutex::Autolock _l(mLock);
832 sendCheckOutputStageEffectsEvent_l();
833}
834
Andy Hung71742ab2023-07-07 13:47:37 -0700835void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200836{
837 sp<ConfigEvent> configEvent =
838 (ConfigEvent *)new CheckOutputStageEffectsEvent();
839 sendConfigEvent_l(configEvent);
840}
841
Andy Hung71742ab2023-07-07 13:47:37 -0700842void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent6f9534f2022-05-03 18:15:04 +0200843{
844 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
845 sendConfigEvent_l(configEvent);
846}
847
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700848// post condition: mConfigEvents.isEmpty()
Andy Hung71742ab2023-07-07 13:47:37 -0700849void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700850{
Eric Laurent10351942014-05-08 18:49:52 -0700851 bool configChanged = false;
852
Eric Laurent81784c32012-11-19 14:55:58 -0800853 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700854 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700855 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800856 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700857 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700858 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700859 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
860 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800861 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700862 true /*asynchronous*/);
863 if (err != 0) {
864 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700865 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700866 }
867 } break;
868 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700869 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700870 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700871 } break;
872 case CFG_EVENT_SET_PARAMETER: {
873 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
874 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
875 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700876 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000877 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700878 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700879 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700880 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700881 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700882 CreateAudioPatchConfigEventData *data =
883 (CreateAudioPatchConfigEventData *)event->mData.get();
884 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700885 const DeviceTypeSet newDevices = getDeviceTypes();
Eric Laurent52568142022-10-28 11:23:28 +0200886 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700887 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
888 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
889 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700890 } break;
891 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700892 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700893 ReleaseAudioPatchConfigEventData *data =
894 (ReleaseAudioPatchConfigEventData *)event->mData.get();
895 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700896 const DeviceTypeSet newDevices = getDeviceTypes();
Eric Laurent52568142022-10-28 11:23:28 +0200897 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700898 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
899 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
900 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
901 } break;
902 case CFG_EVENT_UPDATE_OUT_DEVICE: {
903 UpdateOutDevicesConfigEventData *data =
904 (UpdateOutDevicesConfigEventData *)event->mData.get();
905 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700906 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200907 case CFG_EVENT_RESIZE_BUFFER: {
908 ResizeBufferConfigEventData *data =
909 (ResizeBufferConfigEventData *)event->mData.get();
910 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
911 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200912
913 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
914 setCheckOutputStageEffects();
915 } break;
916
Eric Laurent6f9534f2022-05-03 18:15:04 +0200917 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
918 onHalLatencyModesChanged_l();
919 } break;
920
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700921 default:
Eric Laurent10351942014-05-08 18:49:52 -0700922 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700923 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800924 }
Eric Laurent10351942014-05-08 18:49:52 -0700925 {
926 Mutex::Autolock _l(event->mLock);
927 if (event->mWaitStatus) {
928 event->mWaitStatus = false;
929 event->mCond.signal();
930 }
931 }
932 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
933 }
934
935 if (configChanged) {
936 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800937 }
Eric Laurent81784c32012-11-19 14:55:58 -0800938}
939
Marco Nelissenb2208842014-02-07 14:00:50 -0800940String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
941 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700942 const audio_channel_representation_t representation =
943 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700944
945 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800946 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700947 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
948 if (output) {
949 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
950 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
951 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700952 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700953 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
954 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
955 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
956 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
957 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
958 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
959 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
960 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
961 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
962 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
963 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
964 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700965 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
966 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
967 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
968 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
969 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
970 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
971 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700972 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700973 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
974 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700975 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
976 } else {
977 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
978 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
979 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
980 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
981 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
982 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
983 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
984 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
985 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
986 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
987 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
988 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700989 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
990 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
991 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700992 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700993 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
994 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700995 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
996 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
997 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
998 }
999 const int len = s.length();
1000 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001001 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001002 s.unlockBuffer(len - 2); // remove trailing ", "
1003 }
1004 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001005 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001006 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1007 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1008 return s;
1009 default:
1010 s.appendFormat("unknown mask, representation:%d bits:%#x",
1011 representation, audio_channel_mask_get_bits(mask));
1012 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001013 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001014}
1015
Andy Hung71742ab2023-07-07 13:47:37 -07001016void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung71ba4b32022-10-06 12:09:49 -07001017NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001018{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001019 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1020 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1021
Andy Hung21ff9672023-07-18 20:54:44 -07001022 const bool locked = afutils::dumpTryLock(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08001023 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001024 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001025 }
1026
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001027 dumpBase_l(fd, args);
1028 dumpInternals_l(fd, args);
1029 dumpTracks_l(fd, args);
1030 dumpEffectChains_l(fd, args);
1031
1032 if (locked) {
1033 mLock.unlock();
1034 }
1035
1036 dprintf(fd, " Local log:\n");
1037 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001038
1039 // --all does the statistics
1040 bool dumpAll = false;
1041 for (const auto &arg : args) {
1042 if (arg == String16("--all")) {
1043 dumpAll = true;
1044 }
1045 }
1046 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001047 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001048 if (!sched.empty()) {
1049 (void)write(fd, sched.c_str(), sched.size());
1050 }
1051 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001052}
1053
Andy Hung71742ab2023-07-07 13:47:37 -07001054void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001055{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001056 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001057 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001058 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001059 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001060 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001061 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001062 dprintf(fd, " Channel count: %u\n", mChannelCount);
1063 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00001064 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001065 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001066 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001067 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001068 size_t numConfig = mConfigEvents.size();
1069 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001070 const size_t SIZE = 256;
1071 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001072 for (size_t i = 0; i < numConfig; i++) {
1073 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001074 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001075 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001076 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001077 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001078 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001079 }
Andy Hung293558a2017-03-21 12:19:20 -07001080 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001081 dprintf(fd, " Output devices: %s (%s)\n",
1082 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
1083 dprintf(fd, " Input device: %#x (%s)\n",
1084 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001085 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001086
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001087 // Dump timestamp statistics for the Thread types that support it.
1088 if (mType == RECORD
1089 || mType == MIXER
1090 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001091 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001092 || mType == OFFLOAD
1093 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001094 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -07001095 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001096 }
1097
Andy Hung446f4df2019-02-21 12:26:41 -08001098 if (mLastIoBeginNs > 0) { // MMAP may not set this
1099 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1100 isOutput() ? "write" : "read",
1101 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1102 }
1103
1104 if (mProcessTimeMs.getN() > 0) {
1105 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1106 }
1107
1108 if (mIoJitterMs.getN() > 0) {
1109 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1110 isOutput() ? "write" : "read",
1111 mIoJitterMs.toString().c_str());
1112 }
1113
Andy Hunge6c37112019-02-26 17:38:10 -08001114 if (mLatencyMs.getN() > 0) {
1115 dprintf(fd, " Threadloop %s latency stats: %s\n",
1116 isOutput() ? "write" : "read",
1117 mLatencyMs.toString().c_str());
1118 }
Robert Wu06db0a32021-08-10 19:05:34 +00001119
1120 if (mMonopipePipeDepthStats.getN() > 0) {
1121 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1122 isOutput() ? "write" : "read",
1123 mMonopipePipeDepthStats.toString().c_str());
1124 }
Eric Laurent81784c32012-11-19 14:55:58 -08001125}
1126
Andy Hung71742ab2023-07-07 13:47:37 -07001127void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001128{
1129 const size_t SIZE = 256;
1130 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001131
Marco Nelissenb2208842014-02-07 14:00:50 -08001132 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001133 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001134 write(fd, buffer, strlen(buffer));
1135
Marco Nelissenb2208842014-02-07 14:00:50 -08001136 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hungbd72c542023-06-20 18:56:17 -07001137 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001138 if (chain != 0) {
1139 chain->dump(fd, args);
1140 }
1141 }
1142}
1143
Andy Hung71742ab2023-07-07 13:47:37 -07001144void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001145{
1146 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07001147 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001148}
1149
Andy Hung71742ab2023-07-07 13:47:37 -07001150String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001151{
1152 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001153 case MIXER:
1154 return String16("AudioMix");
1155 case DIRECT:
1156 return String16("AudioDirectOut");
1157 case DUPLICATING:
1158 return String16("AudioDup");
1159 case RECORD:
1160 return String16("AudioIn");
1161 case OFFLOAD:
1162 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001163 case MMAP_PLAYBACK:
1164 return String16("MmapPlayback");
1165 case MMAP_CAPTURE:
1166 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001167 case SPATIALIZER:
1168 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001169 default:
1170 ALOG_ASSERT(false);
1171 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001172 }
1173}
1174
Andy Hung71742ab2023-07-07 13:47:37 -07001175void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001176{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001177 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001178 if (mPowerManager != 0) {
1179 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001180 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001181 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1182 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001183 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001184 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001185 {} /* workSource */,
1186 {} /* historyTag */);
1187 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001188 mWakeLockToken = binder;
1189 }
Chris Ye6597d732020-02-28 22:38:25 -08001190 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001191 }
Wei Jia3f273d12015-11-24 09:06:49 -08001192
Andy Hung3f0c9022016-01-15 17:49:46 -08001193 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001194 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1195 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001196}
1197
Andy Hung71742ab2023-07-07 13:47:37 -07001198void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001199{
1200 Mutex::Autolock _l(mLock);
1201 releaseWakeLock_l();
1202}
1203
Andy Hung71742ab2023-07-07 13:47:37 -07001204void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001205{
Andy Hung3f0c9022016-01-15 17:49:46 -08001206 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001207 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001208 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001209 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001210 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001211 }
1212 mWakeLockToken.clear();
1213 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001214}
1215
Andy Hung71742ab2023-07-07 13:47:37 -07001216void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001217 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001218 // use checkService() to avoid blocking if power service is not up yet
1219 sp<IBinder> binder =
1220 defaultServiceManager()->checkService(String16("power"));
1221 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001222 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001223 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001224 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001225 binder->linkToDeath(mDeathRecipient);
1226 }
1227 }
1228}
1229
Andy Hung71742ab2023-07-07 13:47:37 -07001230void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001231 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001232
1233#if !LOG_NDEBUG
1234 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001235 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001236 s << uid << " ";
1237 }
1238 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1239#endif
1240
Andy Hung438e7572015-12-14 15:51:17 -08001241 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1242 if (mSystemReady) {
1243 ALOGE("no wake lock to update, but system ready!");
1244 } else {
1245 ALOGW("no wake lock to update, system not ready yet");
1246 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001247 return;
1248 }
1249 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001250 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001251 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1252 mWakeLockToken, uidsAsInt);
1253 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001254 }
1255}
1256
Andy Hung71742ab2023-07-07 13:47:37 -07001257void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001258{
1259 Mutex::Autolock _l(mLock);
1260 releaseWakeLock_l();
1261 mPowerManager.clear();
1262}
1263
Andy Hung71742ab2023-07-07 13:47:37 -07001264void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001265 const DeviceDescriptorBaseVector& outDevices __unused)
1266{
1267 ALOGE("%s should only be called in RecordThread", __func__);
1268}
1269
Andy Hung71742ab2023-07-07 13:47:37 -07001270void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001271{
1272 ALOGE("%s should only be called in RecordThread", __func__);
1273}
1274
Andy Hung71742ab2023-07-07 13:47:37 -07001275void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001276{
1277 sp<ThreadBase> thread = mThread.promote();
1278 if (thread != 0) {
1279 thread->clearPowerManager();
1280 }
1281 ALOGW("power manager service died !!!");
1282}
1283
Andy Hung71742ab2023-07-07 13:47:37 -07001284void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001285 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001286{
Andy Hungbd72c542023-06-20 18:56:17 -07001287 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001288 if (chain != 0) {
1289 if (type != NULL) {
1290 chain->setEffectSuspended_l(type, suspend);
1291 } else {
1292 chain->setEffectSuspendedAll_l(suspend);
1293 }
1294 }
1295
1296 updateSuspendedSessions_l(type, suspend, sessionId);
1297}
1298
Andy Hung71742ab2023-07-07 13:47:37 -07001299void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001300{
1301 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1302 if (index < 0) {
1303 return;
1304 }
1305
1306 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1307 mSuspendedSessions.valueAt(index);
1308
1309 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001310 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001311 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hungbd72c542023-06-20 18:56:17 -07001312 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001313 chain->setEffectSuspendedAll_l(true);
1314 } else {
1315 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1316 desc->mType.timeLow);
1317 chain->setEffectSuspended_l(&desc->mType, true);
1318 }
1319 }
1320 }
1321}
1322
Andy Hung71742ab2023-07-07 13:47:37 -07001323void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001324 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001325 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001326{
1327 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1328
1329 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1330
1331 if (suspend) {
1332 if (index >= 0) {
1333 sessionEffects = mSuspendedSessions.valueAt(index);
1334 } else {
1335 mSuspendedSessions.add(sessionId, sessionEffects);
1336 }
1337 } else {
1338 if (index < 0) {
1339 return;
1340 }
1341 sessionEffects = mSuspendedSessions.valueAt(index);
1342 }
1343
1344
Andy Hungbd72c542023-06-20 18:56:17 -07001345 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001346 if (type != NULL) {
1347 key = type->timeLow;
1348 }
1349 index = sessionEffects.indexOfKey(key);
1350
1351 sp<SuspendedSessionDesc> desc;
1352 if (suspend) {
1353 if (index >= 0) {
1354 desc = sessionEffects.valueAt(index);
1355 } else {
1356 desc = new SuspendedSessionDesc();
1357 if (type != NULL) {
1358 desc->mType = *type;
1359 }
1360 sessionEffects.add(key, desc);
1361 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1362 }
1363 desc->mRefCount++;
1364 } else {
1365 if (index < 0) {
1366 return;
1367 }
1368 desc = sessionEffects.valueAt(index);
1369 if (--desc->mRefCount == 0) {
1370 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1371 sessionEffects.removeItemsAt(index);
1372 if (sessionEffects.isEmpty()) {
1373 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1374 sessionId);
1375 mSuspendedSessions.removeItem(sessionId);
1376 }
1377 }
1378 }
1379 if (!sessionEffects.isEmpty()) {
1380 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1381 }
1382}
1383
Andy Hung71742ab2023-07-07 13:47:37 -07001384void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001385 audio_session_t sessionId,
Andy Hung71ba4b32022-10-06 12:09:49 -07001386 bool threadLocked)
1387NO_THREAD_SAFETY_ANALYSIS // manual locking
1388{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001389 if (!threadLocked) {
1390 mLock.lock();
1391 }
Eric Laurent81784c32012-11-19 14:55:58 -08001392
Eric Laurent81784c32012-11-19 14:55:58 -08001393 if (mType != RECORD) {
1394 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1395 // another session. This gives the priority to well behaved effect control panels
1396 // and applications not using global effects.
1397 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1398 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001399 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001400 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1401 }
1402 }
1403
Eric Laurent6b446ce2019-12-13 10:56:31 -08001404 if (!threadLocked) {
1405 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001406 }
1407}
1408
Eric Laurent4c415062016-06-17 16:14:16 -07001409// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07001410status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001411 const effect_descriptor_t *desc, audio_session_t sessionId)
1412{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001413 // No global output effect sessions on record threads
1414 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1415 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001416 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1417 desc->name, mThreadName);
1418 return BAD_VALUE;
1419 }
1420 // only pre processing effects on record thread
1421 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1422 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1423 desc->name, mThreadName);
1424 return BAD_VALUE;
1425 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001426
1427 // always allow effects without processing load or latency
1428 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1429 return NO_ERROR;
1430 }
1431
Eric Laurent4c415062016-06-17 16:14:16 -07001432 audio_input_flags_t flags = mInput->flags;
1433 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1434 if (flags & AUDIO_INPUT_FLAG_RAW) {
1435 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1436 desc->name, mThreadName);
1437 return BAD_VALUE;
1438 }
1439 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1440 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1441 desc->name, mThreadName);
1442 return BAD_VALUE;
1443 }
1444 }
jiabineb3bda02020-06-30 14:07:03 -07001445
Andy Hungbd72c542023-06-20 18:56:17 -07001446 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001447 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1448 return BAD_VALUE;
1449 }
Eric Laurent4c415062016-06-17 16:14:16 -07001450 return NO_ERROR;
1451}
1452
1453// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07001454status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001455 const effect_descriptor_t *desc, audio_session_t sessionId)
1456{
1457 // no preprocessing on playback threads
1458 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001459 ALOGW("%s: pre processing effect %s created on playback"
1460 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001461 return BAD_VALUE;
1462 }
1463
Eric Laurent3e4de772017-07-16 16:55:08 -07001464 // always allow effects without processing load or latency
1465 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1466 return NO_ERROR;
1467 }
1468
Andy Hungbd72c542023-06-20 18:56:17 -07001469 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
jiabineb3bda02020-06-30 14:07:03 -07001470 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1471 __func__);
1472 return BAD_VALUE;
1473 }
1474
Eric Laurentf690c462021-09-17 14:47:03 +02001475 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1476 && mType != SPATIALIZER) {
1477 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1478 __func__, mType);
1479 return BAD_VALUE;
1480 }
1481
Eric Laurent4c415062016-06-17 16:14:16 -07001482 switch (mType) {
1483 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001484 audio_output_flags_t flags = mOutput->flags;
1485 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1486 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1487 // global effects are applied only to non fast tracks if they are SW
1488 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1489 break;
1490 }
1491 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1492 // only post processing on output stage session
1493 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001494 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1495 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001496 return BAD_VALUE;
1497 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001498 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1499 // only post processing on output stage session
1500 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001501 ALOGW("%s: non post processing effect %s not allowed on device session",
1502 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001503 return BAD_VALUE;
1504 }
Eric Laurent4c415062016-06-17 16:14:16 -07001505 } else {
1506 // no restriction on effects applied on non fast tracks
1507 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1508 break;
1509 }
1510 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001511
Eric Laurent4c415062016-06-17 16:14:16 -07001512 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001513 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001514 return BAD_VALUE;
1515 }
1516 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001517 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1518 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001519 return BAD_VALUE;
1520 }
1521 }
1522 } break;
1523 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001524 // nothing actionable on offload threads, if the effect:
1525 // - is offloadable: the effect can be created
1526 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1527 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001528 break;
1529 case DIRECT:
1530 // Reject any effect on Direct output threads for now, since the format of
1531 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001532 ALOGW("%s: effect %s on DIRECT output thread %s",
1533 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001534 return BAD_VALUE;
1535 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001536 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001537 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1538 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001539 return BAD_VALUE;
1540 }
1541 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001542 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1543 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001544 return BAD_VALUE;
1545 }
1546 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001547 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1548 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001549 return BAD_VALUE;
1550 }
1551 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001552 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001553 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1554 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1555 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1556 // are supported and added after the spatializer.
1557 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1558 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1559 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001560 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001561 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1562 // only post processing , downmixer or spatializer effects on output stage session
1563 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1564 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1565 break;
1566 }
1567 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1568 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1569 __func__, desc->name);
1570 return BAD_VALUE;
1571 }
1572 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1573 // only post processing on output stage session
1574 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1575 ALOGW("%s: non post processing effect %s not allowed on device session",
1576 __func__, desc->name);
1577 return BAD_VALUE;
1578 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001579 }
1580 break;
jiabinc658e452022-10-21 20:52:21 +00001581 case BIT_PERFECT:
1582 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1583 // Allow HW accelerated effects of tunnel type
1584 break;
1585 }
1586 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1587 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1588 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1589 // 3) there is any bit-perfect track with the given session id.
1590 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1591 sessionId == AUDIO_SESSION_DEVICE) {
1592 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1593 __func__, desc->name, mThreadName);
1594 return BAD_VALUE;
1595 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1596 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1597 __func__, desc->name, sessionId);
1598 return BAD_VALUE;
1599 }
1600 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001601 default:
1602 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1603 }
1604
1605 return NO_ERROR;
1606}
1607
Eric Laurent81784c32012-11-19 14:55:58 -08001608// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07001609sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hungd65869f2023-06-27 17:05:02 -07001610 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001611 const sp<IEffectClient>& effectClient,
1612 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001613 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001614 effect_descriptor_t *desc,
1615 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001616 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001617 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001618 bool probe,
1619 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001620{
Andy Hungbd72c542023-06-20 18:56:17 -07001621 sp<IAfEffectModule> effect;
1622 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001623 status_t lStatus;
Andy Hungbd72c542023-06-20 18:56:17 -07001624 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001625 bool chainCreated = false;
1626 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001627 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001628
1629 lStatus = initCheck();
1630 if (lStatus != NO_ERROR) {
1631 ALOGW("createEffect_l() Audio driver not initialized.");
1632 goto Exit;
1633 }
1634
Eric Laurent81784c32012-11-19 14:55:58 -08001635 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1636
1637 { // scope for mLock
1638 Mutex::Autolock _l(mLock);
1639
Eric Laurent4c415062016-06-17 16:14:16 -07001640 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001641 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001642 goto Exit;
1643 }
1644
Eric Laurent81784c32012-11-19 14:55:58 -08001645 // check for existing effect chain with the requested audio session
1646 chain = getEffectChain_l(sessionId);
1647 if (chain == 0) {
1648 // create a new chain for this session
1649 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Andy Hungbd72c542023-06-20 18:56:17 -07001650 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001651 addEffectChain_l(chain);
1652 chain->setStrategy(getStrategyForSession_l(sessionId));
1653 chainCreated = true;
1654 } else {
1655 effect = chain->getEffectFromDesc_l(desc);
1656 }
1657
1658 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1659
1660 if (effect == 0) {
Andy Hung2cbc2722023-07-17 17:05:00 -07001661 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001662 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001663 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001664 if (lStatus != NO_ERROR) {
1665 goto Exit;
1666 }
1667 effectCreated = true;
1668
jiabinc52b1ff2019-10-31 17:20:42 -07001669 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001670 effect->setDevices(outDeviceTypeAddrs());
1671 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung2cbc2722023-07-17 17:05:00 -07001672 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001673 effect->setAudioSource(mAudioSource);
1674 }
jiabin1319f5a2021-03-30 22:21:24 +00001675 if (effect->isHapticGenerator()) {
1676 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1677 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001678 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung2cbc2722023-07-17 17:05:00 -07001679 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001680 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001681 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001682 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001683 }
1684 }
Eric Laurent81784c32012-11-19 14:55:58 -08001685 // create effect handle and connect it to effect module
Andy Hungbd72c542023-06-20 18:56:17 -07001686 handle = IAfEffectHandle::create(
1687 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001688 lStatus = handle->initCheck();
1689 if (lStatus == OK) {
1690 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001691 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001692 }
Eric Laurent81784c32012-11-19 14:55:58 -08001693 if (enabled != NULL) {
1694 *enabled = (int)effect->isEnabled();
1695 }
1696 }
1697
1698Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001699 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001700 Mutex::Autolock _l(mLock);
1701 if (effectCreated) {
1702 chain->removeEffect_l(effect);
1703 }
Eric Laurent81784c32012-11-19 14:55:58 -08001704 if (chainCreated) {
1705 removeEffectChain_l(chain);
1706 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001707 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001708 }
1709
Glenn Kasten9156ef32013-08-06 15:39:08 -07001710 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001711 return handle;
1712}
1713
Andy Hung71742ab2023-07-07 13:47:37 -07001714void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001715 bool unpinIfLast)
1716{
1717 bool remove = false;
Andy Hungbd72c542023-06-20 18:56:17 -07001718 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001719 {
1720 Mutex::Autolock _l(mLock);
Andy Hungbd72c542023-06-20 18:56:17 -07001721 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001722 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001723 return;
1724 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001725 effect = effectBase->asEffectModule();
1726 if (effect == nullptr) {
1727 return;
1728 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001729 // restore suspended effects if the disconnected handle was enabled and the last one.
1730 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1731 if (remove) {
1732 removeEffect_l(effect, true);
1733 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001734 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001735 }
1736 if (remove) {
Andy Hung2cbc2722023-07-17 17:05:00 -07001737 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001738 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001739 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001740 }
1741 }
1742}
1743
Andy Hung71742ab2023-07-07 13:47:37 -07001744void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001745 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001746 Mutex::Autolock _l(mLock);
1747 broadcast_l();
1748 }
1749 if (!effect->isOffloadable()) {
1750 if (mType == ThreadBase::OFFLOAD) {
1751 PlaybackThread *t = (PlaybackThread *)this;
1752 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1753 }
1754 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung2cbc2722023-07-17 17:05:00 -07001755 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001756 }
1757 }
1758}
1759
Andy Hung71742ab2023-07-07 13:47:37 -07001760void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001761 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001762 Mutex::Autolock _l(mLock);
1763 broadcast_l();
1764 }
1765}
1766
Andy Hung71742ab2023-07-07 13:47:37 -07001767sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung4989d312023-06-29 21:19:25 -07001768 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001769{
1770 Mutex::Autolock _l(mLock);
1771 return getEffect_l(sessionId, effectId);
1772}
1773
Andy Hung71742ab2023-07-07 13:47:37 -07001774sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung4989d312023-06-29 21:19:25 -07001775 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001776{
Andy Hungbd72c542023-06-20 18:56:17 -07001777 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001778 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1779}
1780
Andy Hung71742ab2023-07-07 13:47:37 -07001781std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001782{
Andy Hungbd72c542023-06-20 18:56:17 -07001783 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent6c796322019-04-09 14:13:17 -07001784 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1785}
1786
Eric Laurent81784c32012-11-19 14:55:58 -08001787// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1788// PlaybackThread::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07001789status_t ThreadBase::addEffect_l(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001790{
1791 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001792 audio_session_t sessionId = effect->sessionId();
Andy Hungbd72c542023-06-20 18:56:17 -07001793 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001794 bool chainCreated = false;
1795
Eric Laurent5baf2af2013-09-12 17:37:00 -07001796 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001797 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001798 this, effect->desc().name, effect->desc().flags);
1799
Eric Laurent81784c32012-11-19 14:55:58 -08001800 if (chain == 0) {
1801 // create a new chain for this session
1802 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Andy Hungbd72c542023-06-20 18:56:17 -07001803 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001804 addEffectChain_l(chain);
1805 chain->setStrategy(getStrategyForSession_l(sessionId));
1806 chainCreated = true;
1807 }
1808 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1809
1810 if (chain->getEffectFromId_l(effect->id()) != 0) {
1811 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1812 this, effect->desc().name, chain.get());
1813 return BAD_VALUE;
1814 }
1815
Eric Laurent5baf2af2013-09-12 17:37:00 -07001816 effect->setOffloaded(mType == OFFLOAD, mId);
1817
Eric Laurent81784c32012-11-19 14:55:58 -08001818 status_t status = chain->addEffect_l(effect);
1819 if (status != NO_ERROR) {
1820 if (chainCreated) {
1821 removeEffectChain_l(chain);
1822 }
1823 return status;
1824 }
1825
jiabin8f278ee2019-11-11 12:16:27 -08001826 effect->setDevices(outDeviceTypeAddrs());
1827 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung2cbc2722023-07-17 17:05:00 -07001828 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001829 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001830
Eric Laurent81784c32012-11-19 14:55:58 -08001831 return NO_ERROR;
1832}
1833
Andy Hung71742ab2023-07-07 13:47:37 -07001834void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001835
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001836 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001837 effect_descriptor_t desc = effect->desc();
1838 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1839 detachAuxEffect_l(effect->id());
1840 }
1841
Andy Hungbd72c542023-06-20 18:56:17 -07001842 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001843 if (chain != 0) {
1844 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001845 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001846 removeEffectChain_l(chain);
1847 }
1848 } else {
1849 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1850 }
1851}
1852
Andy Hung71742ab2023-07-07 13:47:37 -07001853void ThreadBase::lockEffectChains_l(
Andy Hungbd72c542023-06-20 18:56:17 -07001854 Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung71ba4b32022-10-06 12:09:49 -07001855NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001856{
1857 effectChains = mEffectChains;
1858 for (size_t i = 0; i < mEffectChains.size(); i++) {
1859 mEffectChains[i]->lock();
1860 }
1861}
1862
Andy Hung71742ab2023-07-07 13:47:37 -07001863void ThreadBase::unlockEffectChains(
Andy Hungbd72c542023-06-20 18:56:17 -07001864 const Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung71ba4b32022-10-06 12:09:49 -07001865NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001866{
1867 for (size_t i = 0; i < effectChains.size(); i++) {
1868 effectChains[i]->unlock();
1869 }
1870}
1871
Andy Hung71742ab2023-07-07 13:47:37 -07001872sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001873{
1874 Mutex::Autolock _l(mLock);
1875 return getEffectChain_l(sessionId);
1876}
1877
Andy Hung71742ab2023-07-07 13:47:37 -07001878sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001879 const
Eric Laurent81784c32012-11-19 14:55:58 -08001880{
1881 size_t size = mEffectChains.size();
1882 for (size_t i = 0; i < size; i++) {
1883 if (mEffectChains[i]->sessionId() == sessionId) {
1884 return mEffectChains[i];
1885 }
1886 }
1887 return 0;
1888}
1889
Andy Hung71742ab2023-07-07 13:47:37 -07001890void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001891{
1892 Mutex::Autolock _l(mLock);
1893 size_t size = mEffectChains.size();
1894 for (size_t i = 0; i < size; i++) {
1895 mEffectChains[i]->setMode_l(mode);
1896 }
1897}
1898
Andy Hung71742ab2023-07-07 13:47:37 -07001899void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001900{
1901 config->type = AUDIO_PORT_TYPE_MIX;
1902 config->ext.mix.handle = mId;
1903 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001904 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001905 config->channel_mask = mChannelMask;
1906 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1907 AUDIO_PORT_CONFIG_FORMAT;
1908}
1909
Andy Hung71742ab2023-07-07 13:47:37 -07001910void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001911{
1912 Mutex::Autolock _l(mLock);
1913 if (mSystemReady) {
1914 return;
1915 }
1916 mSystemReady = true;
1917
1918 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1919 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1920 }
1921 mPendingConfigEvents.clear();
1922}
1923
Andy Hungdae27702016-10-31 14:01:16 -07001924template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001925ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001926 ssize_t index = mActiveTracks.indexOf(track);
1927 if (index >= 0) {
1928 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1929 return index;
1930 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001931 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001932 mActiveTracksGeneration++;
1933 mLatestActiveTrack = track;
1934 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001935 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001936 return mActiveTracks.add(track);
1937}
1938
1939template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001940ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001941 ssize_t index = mActiveTracks.remove(track);
1942 if (index < 0) {
1943 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1944 return index;
1945 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001946 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001947 mActiveTracksGeneration++;
1948 --mBatteryCounter[track->uid()].second;
1949 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001950 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001951#ifdef TEE_SINK
1952 track->dumpTee(-1 /* fd */, "_REMOVE");
1953#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001954 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001955 return index;
1956}
1957
1958template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001959void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001960 for (const sp<T> &track : mActiveTracks) {
1961 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001962 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001963 }
1964 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001965 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001966 mActiveTracks.clear();
1967 mLatestActiveTrack.clear();
1968 mBatteryCounter.clear();
1969}
1970
1971template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001972void ThreadBase::ActiveTracks<T>::updatePowerState(
Andy Hung71ba4b32022-10-06 12:09:49 -07001973 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001974 // Updates ActiveTracks client uids to the thread wakelock.
1975 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1976 thread->updateWakeLockUids_l(getWakeLockUids());
1977 mLastActiveTracksGeneration = mActiveTracksGeneration;
1978 }
1979
1980 // Updates BatteryNotifier uids
1981 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1982 const uid_t uid = it->first;
1983 ssize_t &previous = it->second.first;
1984 ssize_t &current = it->second.second;
1985 if (current > 0) {
1986 if (previous == 0) {
1987 BatteryNotifier::getInstance().noteStartAudio(uid);
1988 }
1989 previous = current;
1990 ++it;
1991 } else if (current == 0) {
1992 if (previous > 0) {
1993 BatteryNotifier::getInstance().noteStopAudio(uid);
1994 }
1995 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1996 } else /* (current < 0) */ {
1997 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1998 }
1999 }
2000}
Eric Laurent83b88082014-06-20 18:31:16 -07002001
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002002template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07002003bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002004 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07002005 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002006
2007 for (const sp<T> &track : mActiveTracks) {
2008 // Do not short-circuit as all hasChanged states must be reset
2009 // as all the metadata are going to be sent
2010 hasChanged |= track->readAndClearHasChanged();
2011 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002012 return hasChanged;
2013}
2014
2015template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07002016void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002017 const char *funcName, const sp<T> &track) const {
2018 if (mLocalLog != nullptr) {
2019 String8 result;
2020 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002021 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002022 }
2023}
2024
Andy Hung71742ab2023-07-07 13:47:37 -07002025void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002026{
2027 // Thread could be blocked waiting for async
2028 // so signal it to handle state changes immediately
2029 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2030 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2031 mSignalPending = true;
2032 mWaitWorkCV.broadcast();
2033}
2034
Andy Hungd0979812019-02-21 15:51:44 -08002035// Call only from threadLoop() or when it is idle.
2036// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hung71742ab2023-07-07 13:47:37 -07002037void ThreadBase::sendStatistics(bool force)
Andy Hungd0979812019-02-21 15:51:44 -08002038{
2039 // Do not log if we have no stats.
2040 // We choose the timestamp verifier because it is the most likely item to be present.
2041 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2042 if (nstats == 0) {
2043 return;
2044 }
2045
2046 // Don't log more frequently than once per 12 hours.
2047 // We use BOOTTIME to include suspend time.
2048 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2049 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2050 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2051 return;
2052 }
2053
2054 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2055 mLastRecordedTimeNs = timeNs;
2056
Ray Essickf27e9872019-12-07 06:28:46 -08002057 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002058
2059#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2060
2061 // thread configuration
2062 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2063 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2064 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2065 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2066 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2067 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2068 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07002069 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
2070 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002071
2072 // thread statistics
2073 if (mIoJitterMs.getN() > 0) {
2074 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2075 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2076 }
2077 if (mProcessTimeMs.getN() > 0) {
2078 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2079 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2080 }
2081 const auto tsjitter = mTimestampVerifier.getJitterMs();
2082 if (tsjitter.getN() > 0) {
2083 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2084 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2085 }
2086 if (mLatencyMs.getN() > 0) {
2087 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2088 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2089 }
Robert Wu06db0a32021-08-10 19:05:34 +00002090 if (mMonopipePipeDepthStats.getN() > 0) {
2091 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2092 mMonopipePipeDepthStats.getMean());
2093 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2094 mMonopipePipeDepthStats.getStdDev());
2095 }
Andy Hungd0979812019-02-21 15:51:44 -08002096
2097 item->selfrecord();
2098}
2099
Andy Hung71742ab2023-07-07 13:47:37 -07002100product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002101{
Andy Hung2cbc2722023-07-17 17:05:00 -07002102 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002103 return PRODUCT_STRATEGY_NONE;
2104 }
2105 return AudioSystem::getStrategyForStream(stream);
2106}
2107
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002108// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002109void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002110 const sp<audio_utils::MelProcessor>& /*processor*/)
2111{
2112 // Do nothing
2113 ALOGW("%s: ThreadBase does not support CSD", __func__);
2114}
2115
2116// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002117void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002118{
2119 // Do nothing
2120 ALOGW("%s: ThreadBase does not support CSD", __func__);
2121}
2122
Eric Laurent81784c32012-11-19 14:55:58 -08002123// ----------------------------------------------------------------------------
2124// Playback
2125// ----------------------------------------------------------------------------
2126
Andy Hung2cbc2722023-07-17 17:05:00 -07002127PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002128 AudioStreamOut* output,
2129 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002130 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002131 bool systemReady,
2132 audio_config_base_t *mixerConfig)
Andy Hung2cbc2722023-07-17 17:05:00 -07002133 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002134 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hungf8ab4692023-07-20 21:44:14 -07002135 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002136 mMixerBuffer(NULL),
2137 mMixerBufferSize(0),
2138 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2139 mMixerBufferValid(false),
Andy Hungf8ab4692023-07-20 21:44:14 -07002140 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002141 mEffectBuffer(NULL),
2142 mEffectBufferSize(0),
2143 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2144 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002145 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002146 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002147 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002148 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002149 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002150 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002151 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002152 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002153 mMixerStatus(MIXER_IDLE),
2154 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung18bef9b2023-07-20 21:31:38 -07002155 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002156 mBytesRemaining(0),
2157 mCurrentWriteLength(0),
2158 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002159 mWriteAckSequence(0),
2160 mDrainSequence(0),
Andy Hung01b29482023-07-19 16:22:58 -07002161 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002162 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002163 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002164 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002165 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl9e661ad2022-07-27 18:01:07 +02002166 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002167 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002168{
Glenn Kastend7dca052015-03-05 16:05:54 -08002169 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung2cbc2722023-07-17 17:05:00 -07002170 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002171
2172 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2173 // it would be safer to explicitly pass initial masterVolume/masterMute as
2174 // parameter.
2175 //
2176 // If the HAL we are using has support for master volume or master mute,
2177 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2178 // and the mute set to false).
Andy Hung2cbc2722023-07-17 17:05:00 -07002179 mMasterVolume = afThreadCallback->masterVolume_l();
2180 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002181 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002182 if (mOutput->audioHwDev->canSetMasterVolume()) {
2183 mMasterVolume = 1.0;
2184 }
2185
2186 if (mOutput->audioHwDev->canSetMasterMute()) {
2187 mMasterMute = false;
2188 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002189 mIsMsdDevice = strcmp(
2190 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002191 }
2192
Eric Laurentf1f22e72021-07-13 14:04:14 +02002193 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2194 mMixerChannelMask = mixerConfig->channel_mask;
2195 }
2196
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002197 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002198
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002199 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002200 && mMixerChannelMask != mChannelMask) {
2201 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2202 mChannelMask, mMixerChannelMask);
2203 }
2204
Andy Hungc8fddf32018-08-08 18:32:37 -07002205 // TODO: We may also match on address as well as device type for
2206 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002207 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002208 // TODO: This property should be ensure that only contains one single device type.
2209 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2210 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002211 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2212 : AUDIO_DEVICE_NONE));
2213 }
2214
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002215 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2216 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002217 mStreamTypes[stream].volume = 0.0f;
Andy Hung2cbc2722023-07-17 17:05:00 -07002218 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002219 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002220 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002221 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2222 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002223 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2224 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002225}
2226
Andy Hung71742ab2023-07-07 13:47:37 -07002227PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002228{
Andy Hung2cbc2722023-07-17 17:05:00 -07002229 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002230 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002231 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002232 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002233 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002234}
2235
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002236// Thread virtuals
2237
Andy Hung71742ab2023-07-07 13:47:37 -07002238void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002239{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002240 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002241 ALOGE("The stream is not open yet"); // This should not happen.
2242 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002243 // Callbacks take strong or weak pointers as a parameter.
2244 // Since PlaybackThread passes itself as a callback handler, it can only
2245 // be done outside of the constructor. Creating weak and especially strong
2246 // pointers to a refcounted object in its own constructor is strongly
2247 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2248 // Even if a function takes a weak pointer, it is possible that it will
2249 // need to convert it to a strong pointer down the line.
2250 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2251 mOutput->stream->setCallback(this) == OK) {
2252 mUseAsyncWrite = true;
Andy Hung71742ab2023-07-07 13:47:37 -07002253 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002254 }
2255
jiabinf6eb4c32020-02-25 14:06:25 -08002256 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002257 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002258 }
2259 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002260 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002261 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002262}
2263
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002264// ThreadBase virtuals
Andy Hung71742ab2023-07-07 13:47:37 -07002265void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002266{
2267 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002268 status_t result = mOutput->stream->exit();
2269 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002270}
2271
Andy Hung71742ab2023-07-07 13:47:37 -07002272void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002273{
Eric Laurent81784c32012-11-19 14:55:58 -08002274 String8 result;
2275
Marco Nelissenb2208842014-02-07 14:00:50 -08002276 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002277 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2278 const stream_type_t *st = &mStreamTypes[i];
2279 if (i > 0) {
2280 result.appendFormat(", ");
2281 }
2282 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2283 if (st->mute) {
2284 result.append("M");
2285 }
2286 }
2287 result.append("\n");
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002288 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002289 result.clear();
2290
Eric Laurent81784c32012-11-19 14:55:58 -08002291 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2292 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002293 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002294 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002295
2296 size_t numtracks = mTracks.size();
2297 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002298 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002299 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002300 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002301 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002302 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002303 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002304 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002305 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002306 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002307 if (track != 0) {
2308 bool active = mActiveTracks.indexOf(track) >= 0;
2309 if (active) {
2310 numactiveseen++;
2311 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002312 result.append(prefix);
2313 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002314 }
2315 }
2316 } else {
2317 result.append("\n");
2318 }
2319 if (numactiveseen != numactive) {
2320 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002321 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002322 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002323 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002324 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002325 for (size_t i = 0; i < numactive; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002326 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002327 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002328 result.append(prefix);
2329 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002330 }
2331 }
2332 }
2333
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002334 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002335}
2336
Andy Hung71742ab2023-07-07 13:47:37 -07002337void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002338{
Andy Hung04cb8f72020-03-20 13:44:33 -07002339 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002340 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002341 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2342 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002343 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2344 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2345 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2346 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002347 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002348 dprintf(fd, " Total writes: %d\n", mNumWrites);
2349 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2350 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2351 dprintf(fd, " Suspend count: %d\n", mSuspended);
2352 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2353 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2354 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2355 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002356 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002357 AudioStreamOut *output = mOutput;
2358 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002359 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002360 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002361 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2362 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2363 if (mPipeSink.get() != nullptr) {
2364 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2365 }
2366 if (output != nullptr) {
2367 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002368 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002369 }
Eric Laurent81784c32012-11-19 14:55:58 -08002370}
2371
Eric Laurent81784c32012-11-19 14:55:58 -08002372// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002373sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hungd65869f2023-06-27 17:05:02 -07002374 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002375 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002376 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002377 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002378 audio_format_t format,
2379 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002380 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002381 size_t *pNotificationFrameCount,
2382 uint32_t notificationsPerBuffer,
2383 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002384 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002385 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002386 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002387 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002388 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002389 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002390 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002391 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002392 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002393 bool isSpatialized,
2394 bool isBitPerfect)
Eric Laurent81784c32012-11-19 14:55:58 -08002395{
Glenn Kasten74935e42013-12-19 08:56:45 -08002396 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002397 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung3ff4b552023-06-26 19:20:57 -07002398 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002399 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002400 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002401 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002402 uint32_t sampleRate;
2403
2404 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2405 lStatus = BAD_VALUE;
2406 goto Exit;
2407 }
Eric Laurent21da6472017-11-09 16:29:26 -08002408
2409 if (*pSampleRate == 0) {
2410 *pSampleRate = mSampleRate;
2411 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002412 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002413
2414 // special case for FAST flag considered OK if fast mixer is present
2415 if (hasFastMixer()) {
2416 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2417 }
2418
2419 // Check if requested flags are compatible with output stream flags
2420 if ((*flags & outputFlags) != *flags) {
2421 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2422 *flags, outputFlags);
2423 *flags = (audio_output_flags_t)(*flags & outputFlags);
2424 }
Eric Laurent81784c32012-11-19 14:55:58 -08002425
jiabinc658e452022-10-21 20:52:21 +00002426 if (isBitPerfect) {
Andy Hungbd72c542023-06-20 18:56:17 -07002427 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002428 if (chain.get() != nullptr) {
2429 // Bit-perfect is required according to the configuration and preferred mixer
2430 // attributes, but it is not in the output flag from the client's request. Explicitly
2431 // adding bit-perfect flag to check the compatibility
2432 audio_output_flags_t flagsToCheck =
2433 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2434 chain->checkOutputFlagCompatibility(&flagsToCheck);
2435 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2436 ALOGE("%s cannot create track as there is data-processing effect attached to "
2437 "given session id(%d)", __func__, sessionId);
2438 lStatus = BAD_VALUE;
2439 goto Exit;
2440 }
2441 *flags = flagsToCheck;
2442 }
2443 }
2444
Eric Laurent81784c32012-11-19 14:55:58 -08002445 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002446 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002447 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002448 // PCM data
2449 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002450 // TODO: extract as a data library function that checks that a computationally
2451 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002452 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002453 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2454 (channelMask == AUDIO_CHANNEL_OUT_MONO
2455 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002456 // hardware sample rate
2457 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002458 // normal mixer has an associated fast mixer
2459 hasFastMixer() &&
2460 // there are sufficient fast track slots available
2461 (mFastTrackAvailMask != 0)
2462 // FIXME test that MixerThread for this fast track has a capable output HAL
2463 // FIXME add a permission test also?
2464 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002465 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2466 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002467 // read the fast track multiplier property the first time it is needed
2468 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2469 if (ok != 0) {
2470 ALOGE("%s pthread_once failed: %d", __func__, ok);
2471 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002472 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002473 }
Eric Laurent4c415062016-06-17 16:14:16 -07002474
2475 // check compatibility with audio effects.
2476 { // scope for mLock
2477 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002478 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002479 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002480 AUDIO_SESSION_OUTPUT_STAGE,
2481 AUDIO_SESSION_OUTPUT_MIX,
2482 sessionId,
2483 }) {
Andy Hungbd72c542023-06-20 18:56:17 -07002484 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002485 if (chain.get() != nullptr) {
2486 audio_output_flags_t old = *flags;
2487 chain->checkOutputFlagCompatibility(flags);
2488 if (old != *flags) {
2489 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2490 (int)session, (int)old, (int)*flags);
2491 }
Eric Laurent4c415062016-06-17 16:14:16 -07002492 }
2493 }
2494 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002495 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002496 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2497 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002498 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002499 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002500 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002501 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002502 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002503 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002504 audio_is_linear_pcm(format), channelMask, sampleRate,
2505 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002506 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002507 }
2508 }
Eric Laurent21da6472017-11-09 16:29:26 -08002509
2510 if (!audio_has_proportional_frames(format)) {
2511 if (sharedBuffer != 0) {
2512 // Same comment as below about ignoring frameCount parameter for set()
2513 frameCount = sharedBuffer->size();
2514 } else if (frameCount == 0) {
2515 frameCount = mNormalFrameCount;
2516 }
2517 if (notificationFrameCount != frameCount) {
2518 notificationFrameCount = frameCount;
2519 }
2520 } else if (sharedBuffer != 0) {
2521 // FIXME: Ensure client side memory buffers need
2522 // not have additional alignment beyond sample
2523 // (e.g. 16 bit stereo accessed as 32 bit frame).
2524 size_t alignment = audio_bytes_per_sample(format);
2525 if (alignment & 1) {
2526 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2527 alignment = 1;
2528 }
2529 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2530 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2531 if (channelCount > 1) {
2532 // More than 2 channels does not require stronger alignment than stereo
2533 alignment <<= 1;
2534 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002535 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002536 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002537 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002538 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002539 goto Exit;
2540 }
Eric Laurent21da6472017-11-09 16:29:26 -08002541
2542 // When initializing a shared buffer AudioTrack via constructors,
2543 // there's no frameCount parameter.
2544 // But when initializing a shared buffer AudioTrack via set(),
2545 // there _is_ a frameCount parameter. We silently ignore it.
2546 frameCount = sharedBuffer->size() / frameSize;
2547 } else {
2548 size_t minFrameCount = 0;
2549 // For fast tracks we try to respect the application's request for notifications per buffer.
2550 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2551 if (notificationsPerBuffer > 0) {
2552 // Avoid possible arithmetic overflow during multiplication.
2553 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2554 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2555 notificationsPerBuffer, mFrameCount);
2556 } else {
2557 minFrameCount = mFrameCount * notificationsPerBuffer;
2558 }
2559 }
2560 } else {
2561 // For normal PCM streaming tracks, update minimum frame count.
2562 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2563 // cover audio hardware latency.
2564 // This is probably too conservative, but legacy application code may depend on it.
2565 // If you change this calculation, also review the start threshold which is related.
2566 uint32_t latencyMs = latency_l();
2567 if (latencyMs == 0) {
2568 ALOGE("Error when retrieving output stream latency");
2569 lStatus = UNKNOWN_ERROR;
2570 goto Exit;
2571 }
2572
2573 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2574 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2575
Eric Laurent81784c32012-11-19 14:55:58 -08002576 }
Eric Laurent21da6472017-11-09 16:29:26 -08002577 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002578 frameCount = minFrameCount;
2579 }
Eric Laurent81784c32012-11-19 14:55:58 -08002580 }
Eric Laurent21da6472017-11-09 16:29:26 -08002581
2582 // Make sure that application is notified with sufficient margin before underrun.
2583 // The client can divide the AudioTrack buffer into sub-buffers,
2584 // and expresses its desire to server as the notification frame count.
2585 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2586 size_t maxNotificationFrames;
2587 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2588 // notify every HAL buffer, regardless of the size of the track buffer
2589 maxNotificationFrames = mFrameCount;
2590 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002591 // Triple buffer the notification period for a triple buffered mixer period;
2592 // otherwise, double buffering for the notification period is fine.
2593 //
2594 // TODO: This should be moved to AudioTrack to modify the notification period
2595 // on AudioTrack::setBufferSizeInFrames() changes.
2596 const int nBuffering =
2597 (uint64_t{frameCount} * mSampleRate)
2598 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2599
Eric Laurent21da6472017-11-09 16:29:26 -08002600 maxNotificationFrames = frameCount / nBuffering;
2601 // If client requested a fast track but this was denied, then use the smaller maximum.
2602 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2603 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2604 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2605 maxNotificationFrames = maxNotificationFramesFastDenied;
2606 }
2607 }
2608 }
2609 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2610 if (notificationFrameCount == 0) {
2611 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2612 maxNotificationFrames, frameCount);
2613 } else {
2614 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2615 notificationFrameCount, maxNotificationFrames, frameCount);
2616 }
2617 notificationFrameCount = maxNotificationFrames;
2618 }
2619 }
2620
Glenn Kasten74935e42013-12-19 08:56:45 -08002621 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002622 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002623
Glenn Kastenc3df8382014-03-13 15:05:25 -07002624 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002625 case BIT_PERFECT:
2626 if (isBitPerfect) {
2627 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2628 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2629 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2630 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2631 mChannelMask);
2632 lStatus = BAD_VALUE;
2633 goto Exit;
2634 }
2635 }
2636 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002637
2638 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002639 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002640 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002641 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2642 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002643 sampleRate, format, channelMask, mOutput, mFormat);
2644 lStatus = BAD_VALUE;
2645 goto Exit;
2646 }
2647 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002648 break;
2649
2650 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002651 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002652 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2653 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002654 sampleRate, format, channelMask, mOutput, mFormat);
2655 lStatus = BAD_VALUE;
2656 goto Exit;
2657 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002658 break;
2659
2660 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002661 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002662 ALOGE("createTrack_l() Bad parameter: format %#x \""
2663 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002664 format, mOutput, mFormat);
2665 lStatus = BAD_VALUE;
2666 goto Exit;
2667 }
Andy Hungcd044842014-08-07 11:04:34 -07002668 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002669 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2670 lStatus = BAD_VALUE;
2671 goto Exit;
2672 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002673 break;
2674
Eric Laurent81784c32012-11-19 14:55:58 -08002675 }
2676
2677 lStatus = initCheck();
2678 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002679 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002680 goto Exit;
2681 }
2682
2683 { // scope for mLock
2684 Mutex::Autolock _l(mLock);
2685
2686 // all tracks in same audio session must share the same routing strategy otherwise
2687 // conflicts will happen when tracks are moved from one output to another by audio policy
2688 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002689 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002690 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002691 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002692 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002693 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002694 if (sessionId == t->sessionId() && strategy != actual) {
2695 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2696 strategy, actual);
2697 lStatus = BAD_VALUE;
2698 goto Exit;
2699 }
2700 }
2701 }
2702
yucliuc9c49cd2020-07-13 16:25:21 -07002703 // Set DIRECT flag if current thread is DirectOutputThread. This can
2704 // happen when the playback is rerouted to direct output thread by
2705 // dynamic audio policy.
2706 // Do NOT report the flag changes back to client, since the client
2707 // doesn't explicitly request a direct flag.
2708 audio_output_flags_t trackFlags = *flags;
2709 if (mType == DIRECT) {
2710 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2711 }
2712
Andy Hung3ff4b552023-06-26 19:20:57 -07002713 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002714 channelMask, frameCount,
2715 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002716 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung3ff4b552023-06-26 19:20:57 -07002717 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002718 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002719
Glenn Kasten03003332013-08-06 15:40:54 -07002720 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2721 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002722 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002723 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002724 goto Exit;
2725 }
2726 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002727 {
2728 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2729 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002730 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002731 }
2732 }
Eric Laurent81784c32012-11-19 14:55:58 -08002733
Andy Hungbd72c542023-06-20 18:56:17 -07002734 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002735 if (chain != 0) {
2736 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2737 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002738 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002739 chain->incTrackCnt();
2740 }
2741
Eric Laurent05067782016-06-01 18:27:28 -07002742 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002743 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2744 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2745 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002746 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002747 }
2748 }
2749
2750 lStatus = NO_ERROR;
2751
2752Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002753 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002754 return track;
2755}
2756
Andy Hung1bc088a2018-02-09 15:57:31 -08002757template<typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07002758ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002759{
Andy Hungc0691382018-09-12 18:01:57 -07002760 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002761 const ssize_t index = mTracks.remove(track);
2762 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002763 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002764 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002765 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002766 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002767 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002768 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002769 }
2770 return index;
2771}
2772
Andy Hung71742ab2023-07-07 13:47:37 -07002773uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002774{
2775 return latency;
2776}
2777
Andy Hung71742ab2023-07-07 13:47:37 -07002778uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002779{
2780 Mutex::Autolock _l(mLock);
2781 return latency_l();
2782}
Andy Hung71742ab2023-07-07 13:47:37 -07002783uint32_t PlaybackThread::latency_l() const
Eric Laurent81784c32012-11-19 14:55:58 -08002784{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002785 uint32_t latency;
2786 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2787 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002788 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002789 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002790}
2791
Andy Hung71742ab2023-07-07 13:47:37 -07002792void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002793{
2794 Mutex::Autolock _l(mLock);
2795 // Don't apply master volume in SW if our HAL can do it for us.
2796 if (mOutput && mOutput->audioHwDev &&
2797 mOutput->audioHwDev->canSetMasterVolume()) {
2798 mMasterVolume = 1.0;
2799 } else {
2800 mMasterVolume = value;
2801 }
2802}
2803
Andy Hung71742ab2023-07-07 13:47:37 -07002804void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002805{
2806 mMasterBalance.store(balance);
2807}
2808
Andy Hung71742ab2023-07-07 13:47:37 -07002809void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002810{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002811 if (isDuplicating()) {
2812 return;
2813 }
Eric Laurent81784c32012-11-19 14:55:58 -08002814 Mutex::Autolock _l(mLock);
2815 // Don't apply master mute in SW if our HAL can do it for us.
2816 if (mOutput && mOutput->audioHwDev &&
2817 mOutput->audioHwDev->canSetMasterMute()) {
2818 mMasterMute = false;
2819 } else {
2820 mMasterMute = muted;
2821 }
2822}
2823
Andy Hung71742ab2023-07-07 13:47:37 -07002824void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002825{
2826 Mutex::Autolock _l(mLock);
2827 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002828 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002829}
2830
Andy Hung71742ab2023-07-07 13:47:37 -07002831void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002832{
2833 Mutex::Autolock _l(mLock);
2834 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002835 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002836}
2837
Andy Hung71742ab2023-07-07 13:47:37 -07002838float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002839{
2840 Mutex::Autolock _l(mLock);
2841 return mStreamTypes[stream].volume;
2842}
2843
Andy Hung71742ab2023-07-07 13:47:37 -07002844void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002845{
2846 mOutput->stream->setVolume(left, right);
2847}
2848
Eric Laurent81784c32012-11-19 14:55:58 -08002849// addTrack_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07002850status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Andy Hung71ba4b32022-10-06 12:09:49 -07002851NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent81784c32012-11-19 14:55:58 -08002852{
2853 status_t status = ALREADY_EXISTS;
2854
Eric Laurent81784c32012-11-19 14:55:58 -08002855 if (mActiveTracks.indexOf(track) < 0) {
2856 // the track is newly added, make sure it fills up all its
2857 // buffers before playing. This is to ensure the client will
2858 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002859 if (track->isExternalTrack()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002860 IAfTrackBase::track_state state = track->state();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002861 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002862 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002863 mLock.lock();
2864 // abort track was stopped/paused while we released the lock
Andy Hung3ff4b552023-06-26 19:20:57 -07002865 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002866 if (status == NO_ERROR) {
2867 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002868 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002869 mLock.lock();
2870 }
2871 return INVALID_OPERATION;
2872 }
2873 // abort if start is rejected by audio policy manager
2874 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002875 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2876 // current playback thread is reopened, which may happen when clients set preferred
2877 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2878 // immediately.
2879 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002880 }
2881#ifdef ADD_BATTERY_DATA
2882 // to track the speaker usage
2883 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2884#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002885 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002886 }
2887
Eric Laurent51716182016-02-29 18:00:56 -08002888 // set retry count for buffer fill
2889 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002890 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002891 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002892 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07002893 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002894 }
Andy Hung3ff4b552023-06-26 19:20:57 -07002895 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002896 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07002897 track->retryCount() = kMaxTrackStartupRetries;
2898 track->fillingStatus() =
2899 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002900 }
2901
Andy Hungbd72c542023-06-20 18:56:17 -07002902 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002903 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2904 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2905 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002906 // Unlock due to VibratorService will lock for this call and will
2907 // call Tracks.mute/unmute which also require thread's lock.
2908 mLock.unlock();
Andy Hung9554ec02023-07-20 21:23:42 -07002909 const os::HapticScale intensity = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002910 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002911 std::optional<media::AudioVibratorInfo> vibratorInfo;
2912 {
2913 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2914 // used to play this track.
Andy Hung2cbc2722023-07-17 17:05:00 -07002915 Mutex::Autolock _l(mAfThreadCallback->mutex());
2916 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002917 }
jiabin57303cc2018-12-18 15:45:57 -08002918 mLock.lock();
Simon Bowden62823412022-10-17 14:52:26 +00002919 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002920 if (vibratorInfo) {
2921 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2922 }
2923
jiabin57303cc2018-12-18 15:45:57 -08002924 // Haptic playback should be enabled by vibrator service.
2925 if (track->getHapticPlaybackEnabled()) {
2926 // Disable haptic playback of all active track to ensure only
2927 // one track playing haptic if current track should play haptic.
2928 for (const auto &t : mActiveTracks) {
2929 t->setHapticPlaybackEnabled(false);
2930 }
jiabin245cdd92018-12-07 17:55:15 -08002931 }
jiabine70bc7f2020-06-30 22:07:55 -07002932
2933 // Set haptic intensity for effect
2934 if (chain != nullptr) {
2935 chain->setHapticIntensity_l(track->id(), intensity);
2936 }
jiabin245cdd92018-12-07 17:55:15 -08002937 }
2938
Andy Hung3ff4b552023-06-26 19:20:57 -07002939 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002940 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002941 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002942 if (chain != 0) {
2943 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2944 track->sessionId());
2945 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002946 }
2947
Andy Hungc2b11cb2020-04-22 09:04:01 -07002948 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002949 status = NO_ERROR;
2950 }
2951
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002952 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002953 return status;
2954}
2955
Andy Hung71742ab2023-07-07 13:47:37 -07002956bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002957{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002958 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002959 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002960 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung3ff4b552023-06-26 19:20:57 -07002961 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002962 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002963 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002964 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002965 if (track->isPausePending()) {
2966 track->pauseAck();
2967 }
Andy Hung3ff4b552023-06-26 19:20:57 -07002968 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002969 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002970
2971 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002972}
2973
Andy Hung71742ab2023-07-07 13:47:37 -07002974void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002975{
2976 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002977
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002978 String8 result;
2979 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002980 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002981
Eric Laurent81784c32012-11-19 14:55:58 -08002982 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002983 {
2984 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2985 mAudioTrackCallbacks.erase(track);
2986 }
Eric Laurent81784c32012-11-19 14:55:58 -08002987 if (track->isFastTrack()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002988 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002989 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002990 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2991 mFastTrackAvailMask |= 1 << index;
2992 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung3ff4b552023-06-26 19:20:57 -07002993 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002994 }
Andy Hungbd72c542023-06-20 18:56:17 -07002995 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002996 if (chain != 0) {
2997 chain->decTrackCnt();
2998 }
2999}
3000
Andy Hung71742ab2023-07-07 13:47:37 -07003001String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003002{
Eric Laurent81784c32012-11-19 14:55:58 -08003003 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003004 String8 out_s8;
3005 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3006 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003007 }
Andy Hung71ba4b32022-10-06 12:09:49 -07003008 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003009}
3010
Andy Hung71742ab2023-07-07 13:47:37 -07003011status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003012 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003013 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003014 return NO_INIT;
3015 }
3016 return mOutput->stream->selectPresentation(presentationId, programId);
3017}
3018
Andy Hung71742ab2023-07-07 13:47:37 -07003019void PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003020 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003021 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003022 sp<AudioIoDescriptor> desc;
3023 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003024 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003025 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003026 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003027 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003028 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3029 mSampleRate, mFormat, mChannelMask,
3030 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3031 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003032 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003033 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003034 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003035 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003036 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003037 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003038 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003039 break;
3040 }
Andy Hung2cbc2722023-07-17 17:05:00 -07003041 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003042}
3043
Andy Hung71742ab2023-07-07 13:47:37 -07003044void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003045{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003046 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003047}
3048
Andy Hung71742ab2023-07-07 13:47:37 -07003049void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003050{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003051 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003052}
3053
Andy Hung71742ab2023-07-07 13:47:37 -07003054void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003055{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003056 mCallbackThread->setAsyncError();
3057}
3058
Andy Hung71742ab2023-07-07 13:47:37 -07003059void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08003060 const std::basic_string<uint8_t>& metadataBs)
3061{
Andy Hung71742ab2023-07-07 13:47:37 -07003062 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003063 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hung71742ab2023-07-07 13:47:37 -07003064 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003065 if (playbackThread == nullptr) {
3066 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3067 return;
3068 }
3069
jiabinf6eb4c32020-02-25 14:06:25 -08003070 audio_utils::metadata::Data metadata =
3071 audio_utils::metadata::dataFromByteString(metadataBs);
3072 if (metadata.empty()) {
3073 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3074 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3075 (int)metadataBs.size());
3076 return;
3077 }
3078
3079 audio_utils::metadata::ByteString metaDataStr =
3080 audio_utils::metadata::byteStringFromData(metadata);
3081 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
3082 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07003083 for (const auto& callbackPair : mAudioTrackCallbacks) {
3084 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003085 }
3086 }).detach();
3087}
3088
Andy Hung71742ab2023-07-07 13:47:37 -07003089void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003090{
3091 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003092 // reject out of sequence requests
3093 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3094 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003095 mWaitWorkCV.signal();
3096 }
3097}
3098
Andy Hung71742ab2023-07-07 13:47:37 -07003099void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003100{
3101 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003102 // reject out of sequence requests
3103 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003104 // Register discontinuity when HW drain is completed because that can cause
3105 // the timestamp frame position to reset to 0 for direct and offload threads.
3106 // (Out of sequence requests are ignored, since the discontinuity would be handled
3107 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003108 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003109 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003110 mWaitWorkCV.signal();
3111 }
3112}
3113
Andy Hung71742ab2023-07-07 13:47:37 -07003114void PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003115{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003116 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003117 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3118 mSampleRate = audioConfig.sample_rate;
3119 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003120 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003121 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003122 }
Andy Hungf8ab4692023-07-20 21:44:14 -07003123 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003124 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3125 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003126 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003127
3128 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3129 mMixerChannelMask = mChannelMask;
3130 }
3131
Andy Hunge5412692014-05-16 11:25:07 -07003132 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003133 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003134
Eric Laurentf1f22e72021-07-13 14:04:14 +02003135 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3136
Phil Burkca5e6142015-07-14 09:42:29 -07003137 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003138 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003139 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003140 // Get format from the shim, which will be different than the HAL format
3141 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003142 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003143 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003144 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003145 }
Andy Hungf8ab4692023-07-20 21:44:14 -07003146 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003147 LOG_FATAL("HAL format %#x not supported for mixed output",
3148 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003149 }
Phil Burk062e67a2015-02-11 13:40:50 -08003150 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003151 result = mOutput->stream->getBufferSize(&mBufferSize);
3152 LOG_ALWAYS_FATAL_IF(result != OK,
3153 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003154 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003155 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003156 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003157 mFrameCount);
3158 }
3159
Eric Laurentd1f69b02014-12-15 14:33:13 -08003160 mHwSupportsPause = false;
3161 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003162 bool supportsPause = false, supportsResume = false;
3163 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3164 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003165 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003166 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003167 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003168 } else if (supportsResume) {
3169 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003170 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003171 }
3172 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003173 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3174 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3175 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003176
Andy Hungfbfc3952015-01-15 13:33:51 -08003177 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3178 // For best precision, we use float instead of the associated output
3179 // device format (typically PCM 16 bit).
3180
3181 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3182 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3183 mBufferSize = mFrameSize * mFrameCount;
3184
3185 // TODO: We currently use the associated output device channel mask and sample rate.
3186 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3187 // (if a valid mask) to avoid premature downmix.
3188 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3189 // instead of the output device sample rate to avoid loss of high frequency information.
3190 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3191 }
3192
Andy Hung09a50072014-02-27 14:30:47 -08003193 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003194 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003195 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003196 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3197 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003198 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3199 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003200
Eric Laurent81784c32012-11-19 14:55:58 -08003201 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3202 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3203 maxNormalFrameCount = maxNormalFrameCount & ~15;
3204 if (maxNormalFrameCount < minNormalFrameCount) {
3205 maxNormalFrameCount = minNormalFrameCount;
3206 }
3207 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3208 if (multiplier <= 1.0) {
3209 multiplier = 1.0;
3210 } else if (multiplier <= 2.0) {
3211 if (2 * mFrameCount <= maxNormalFrameCount) {
3212 multiplier = 2.0;
3213 } else {
3214 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3215 }
3216 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003217 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003218 }
3219 }
3220 mNormalFrameCount = multiplier * mFrameCount;
3221 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003222 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003223 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3224 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003225 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003226 mNormalFrameCount);
3227
Andy Hung08fb1742015-05-31 23:22:10 -07003228 // Check if we want to throttle the processing to no more than 2x normal rate
3229 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003230 mThreadThrottleTimeMs = 0;
3231 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003232 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3233
Andy Hung010a1a12014-03-13 13:57:33 -07003234 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3235 // Originally this was int16_t[] array, need to remove legacy implications.
3236 free(mSinkBuffer);
3237 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003238
Andy Hung5b10a202014-03-13 13:59:29 -07003239 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3240 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3241 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003242 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003243
Andy Hung69aed5f2014-02-25 17:24:40 -08003244 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3245 // drives the output.
3246 free(mMixerBuffer);
3247 mMixerBuffer = NULL;
3248 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003249 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003250 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003251 * audio_bytes_per_sample(mMixerBufferFormat);
3252 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3253 }
Andy Hung98ef9782014-03-04 14:46:50 -08003254 free(mEffectBuffer);
3255 mEffectBuffer = NULL;
3256 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003257 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003258 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003259 * audio_bytes_per_sample(mEffectBufferFormat);
3260 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3261 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003262
Eric Laurentb62d0362021-10-26 17:40:18 +02003263 if (mType == SPATIALIZER) {
3264 free(mPostSpatializerBuffer);
3265 mPostSpatializerBuffer = nullptr;
3266 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3267 * audio_bytes_per_sample(mEffectBufferFormat);
3268 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3269 }
3270
Mikhail Naganov55773032020-10-01 15:08:13 -07003271 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3272 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003273 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3274 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003275 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003276
Eric Laurent81784c32012-11-19 14:55:58 -08003277 // force reconfiguration of effect chains and engines to take new buffer size and audio
3278 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003279 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003280 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3281 // matter.
3282 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
Andy Hungbd72c542023-06-20 18:56:17 -07003283 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003284 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung2cbc2722023-07-17 17:05:00 -07003285 mAfThreadCallback->moveEffectChain_l(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003286 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003287 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003288
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003289 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003290 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003291 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3292 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3293 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3294 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3295 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3296 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3297 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3298 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3299 (int32_t)mHapticChannelMask)
3300 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3301 (int32_t)mHapticChannelCount)
3302 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3303 formatToString(mHALFormat).c_str())
3304 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3305 (int32_t)mFrameCount) // sic - added HAL
3306 ;
3307 uint32_t latencyMs;
3308 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3309 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3310 }
3311 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003312}
3313
Andy Hung71742ab2023-07-07 13:47:37 -07003314ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003315{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003316 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003317 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003318 }
3319 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003320 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung3ff4b552023-06-26 19:20:57 -07003321 for (const sp<IAfTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -07003322 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003323 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003324 }
Kevin Rocard12381092018-04-11 09:19:59 -07003325 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003326 MetadataUpdate change;
3327 change.playbackMetadataUpdate = metadata.tracks;
3328 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003329}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003330
Andy Hung71742ab2023-07-07 13:47:37 -07003331void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003332 const StreamOutHalInterface::SourceMetadata& metadata)
3333{
3334 mOutput->stream->updateSourceMetadata(metadata);
3335};
3336
Andy Hung71742ab2023-07-07 13:47:37 -07003337status_t PlaybackThread::getRenderPosition(
Andy Hung4989d312023-06-29 21:19:25 -07003338 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003339{
3340 if (halFrames == NULL || dspFrames == NULL) {
3341 return BAD_VALUE;
3342 }
3343 Mutex::Autolock _l(mLock);
3344 if (initCheck() != NO_ERROR) {
3345 return INVALID_OPERATION;
3346 }
Andy Hung818e7a32016-02-16 18:08:07 -08003347 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003348 *halFrames = framesWritten;
3349
3350 if (isSuspended()) {
3351 // return an estimation of rendered frames when the output is suspended
3352 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003353 *dspFrames = (uint32_t)
3354 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003355 return NO_ERROR;
3356 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003357 status_t status;
3358 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003359 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003360 *dspFrames = (size_t)frames;
3361 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003362 }
3363}
3364
Andy Hung71742ab2023-07-07 13:47:37 -07003365product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003366{
3367 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3368 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3369 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003370 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003371 }
3372 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003373 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003374 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003375 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003376 }
3377 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003378 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003379}
3380
3381
Andy Hung71742ab2023-07-07 13:47:37 -07003382AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003383{
3384 Mutex::Autolock _l(mLock);
3385 return mOutput;
3386}
3387
Andy Hung71742ab2023-07-07 13:47:37 -07003388AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003389{
3390 Mutex::Autolock _l(mLock);
3391 AudioStreamOut *output = mOutput;
3392 mOutput = NULL;
3393 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3394 // must push a NULL and wait for ack
3395 mOutputSink.clear();
3396 mPipeSink.clear();
3397 mNormalSink.clear();
3398 return output;
3399}
3400
3401// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hung71742ab2023-07-07 13:47:37 -07003402sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003403{
3404 if (mOutput == NULL) {
3405 return NULL;
3406 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003407 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003408}
3409
Andy Hung71742ab2023-07-07 13:47:37 -07003410uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003411{
3412 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3413}
3414
Andy Hung71742ab2023-07-07 13:47:37 -07003415status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003416{
3417 if (!isValidSyncEvent(event)) {
3418 return BAD_VALUE;
3419 }
3420
3421 Mutex::Autolock _l(mLock);
3422
3423 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003424 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003425 if (event->triggerSession() == track->sessionId()) {
3426 (void) track->setSyncEvent(event);
3427 return NO_ERROR;
3428 }
3429 }
3430
3431 return NAME_NOT_FOUND;
3432}
3433
Andy Hung71742ab2023-07-07 13:47:37 -07003434bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003435{
3436 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3437}
3438
Andy Hung71742ab2023-07-07 13:47:37 -07003439void PlaybackThread::threadLoop_removeTracks(
Andy Hung3ff4b552023-06-26 19:20:57 -07003440 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003441{
Andy Hungfe726a62018-09-27 15:17:25 -07003442 // Miscellaneous track cleanup when removed from the active list,
3443 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003444#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003445 for (const auto& track : tracksToRemove) {
3446 if (track->isExternalTrack()) {
3447 // to track the speaker usage
3448 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003449 }
3450 }
Andy Hungfe726a62018-09-27 15:17:25 -07003451#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003452}
3453
Andy Hung71742ab2023-07-07 13:47:37 -07003454void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003455{
3456 if (!mMasterMute) {
3457 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003458 if (mOutDeviceTypeAddrs.empty()) {
3459 ALOGD("ro.audio.silent is ignored since no output device is set");
3460 return;
3461 }
jiabinc52b1ff2019-10-31 17:20:42 -07003462 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003463 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3464 return;
3465 }
Eric Laurent81784c32012-11-19 14:55:58 -08003466 if (property_get("ro.audio.silent", value, "0") > 0) {
3467 char *endptr;
3468 unsigned long ul = strtoul(value, &endptr, 0);
3469 if (*endptr == '\0' && ul != 0) {
3470 ALOGD("Silence is golden");
3471 // The setprop command will not allow a property to be changed after
3472 // the first time it is set, so we don't have to worry about un-muting.
3473 setMasterMute_l(true);
3474 }
3475 }
3476 }
3477}
3478
3479// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung71742ab2023-07-07 13:47:37 -07003480ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003481{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003482 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003483 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003484 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003485 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003486
3487 // If an NBAIO sink is present, use it to write the normal mixer's submix
3488 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003489
Andy Hung010a1a12014-03-13 13:57:33 -07003490 const size_t count = mBytesRemaining / mFrameSize;
3491
Simon Wilson2d590962012-11-29 15:18:50 -08003492 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003493 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung01b29482023-07-19 16:22:58 -07003494 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003495 if (screenState != mScreenState) {
3496 mScreenState = screenState;
3497 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3498 if (pipe != NULL) {
3499 pipe->setAvgFrames((mScreenState & 1) ?
3500 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3501 }
3502 }
Andy Hung010a1a12014-03-13 13:57:33 -07003503 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003504 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003505
Eric Laurent81784c32012-11-19 14:55:58 -08003506 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003507 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003508
Andy Hung8946a282018-04-19 20:04:56 -07003509#ifdef TEE_SINK
3510 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3511#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003512 } else {
3513 bytesWritten = framesWritten;
3514 }
3515 // otherwise use the HAL / AudioStreamOut directly
3516 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003517 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003518
Eric Laurentbfb1b832013-01-07 09:53:42 -08003519 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003520 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3521 mWriteAckSequence += 2;
3522 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003523 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003524 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003525 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003526 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003527 // FIXME We should have an implementation of timestamps for direct output threads.
3528 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003529 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003530 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003531
Eric Laurentbfb1b832013-01-07 09:53:42 -08003532 if (mUseAsyncWrite &&
3533 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3534 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003535 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003536 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003537 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003538 }
Eric Laurent81784c32012-11-19 14:55:58 -08003539 }
3540
Eric Laurent81784c32012-11-19 14:55:58 -08003541 mNumWrites++;
3542 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003543 if (mStandby) {
3544 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003545 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003546 mStandby = false;
3547 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003548 return bytesWritten;
3549}
3550
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003551// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07003552void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003553 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003554{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003555 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003556 if (outputSink != nullptr) {
3557 outputSink->startMelComputation(processor);
3558 }
Vlad Popab042ee62022-10-20 18:05:00 +02003559}
3560
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003561// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07003562void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003563{
3564 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003565 if (outputSink != nullptr) {
3566 outputSink->stopMelComputation();
3567 }
Vlad Popab042ee62022-10-20 18:05:00 +02003568}
3569
Andy Hung71742ab2023-07-07 13:47:37 -07003570void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003571{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003572 bool supportsDrain = false;
3573 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003574 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3575 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003576 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3577 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003578 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003579 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003580 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003581 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003582 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003583 }
3584}
3585
Andy Hung71742ab2023-07-07 13:47:37 -07003586void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003587{
Eric Laurent275e8e92014-11-30 15:14:47 -08003588 {
3589 Mutex::Autolock _l(mLock);
3590 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003591 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003592 track->invalidate();
3593 }
Andy Hungdae27702016-10-31 14:01:16 -07003594 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3595 // After we exit there are no more track changes sent to BatteryNotifier
3596 // because that requires an active threadLoop.
3597 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3598 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003599 }
Eric Laurent81784c32012-11-19 14:55:58 -08003600}
3601
3602/*
3603The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003604 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003605 - mActiveSleepTimeUs from activeSleepTimeUs()
3606 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003607 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3608 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003609 - maxPeriod from frame count and sample rate (MIXER only)
3610
3611The parameters that affect these derived values are:
3612 - frame count
3613 - frame size
3614 - sample rate
3615 - device type: A2DP or not
3616 - device latency
3617 - format: PCM or not
3618 - active sleep time
3619 - idle sleep time
3620*/
3621
Andy Hung71742ab2023-07-07 13:47:37 -07003622void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003623{
Andy Hung25c2dac2014-02-27 14:56:00 -08003624 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003625 mActiveSleepTimeUs = activeSleepTimeUs();
3626 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003627
Andy Hung18bef9b2023-07-20 21:31:38 -07003628 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003629
Eric Laurent42537be2016-01-08 17:16:42 -08003630 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3631 // truncating audio when going to standby.
jiabinc52b1ff2019-10-31 17:20:42 -07003632 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003633 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3634 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3635 }
3636 }
Eric Laurent81784c32012-11-19 14:55:58 -08003637}
3638
Andy Hung71742ab2023-07-07 13:47:37 -07003639bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003640{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003641 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003642 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003643 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003644 size_t size = mTracks.size();
3645 for (size_t i = 0; i < size; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003646 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003647 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003648 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003649 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003650 }
3651 }
Eric Laurent13084622016-05-17 10:51:49 -07003652 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003653}
3654
Andy Hung71742ab2023-07-07 13:47:37 -07003655void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003656{
3657 Mutex::Autolock _l(mLock);
3658 invalidateTracks_l(streamType);
3659}
3660
Andy Hung71742ab2023-07-07 13:47:37 -07003661void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003662 Mutex::Autolock _l(mLock);
3663 invalidateTracks_l(portIds);
3664}
3665
Andy Hung71742ab2023-07-07 13:47:37 -07003666bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003667 bool trackMatch = false;
3668 const size_t size = mTracks.size();
3669 for (size_t i = 0; i < size; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003670 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003671 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3672 t->invalidate();
3673 portIds.erase(t->portId());
3674 trackMatch = true;
3675 }
3676 if (portIds.empty()) {
3677 break;
3678 }
3679 }
3680 return trackMatch;
3681}
3682
jiabinf042b9b2021-05-07 23:46:28 +00003683// getTrackById_l must be called with holding thread lock
Andy Hung71742ab2023-07-07 13:47:37 -07003684IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003685 audio_port_handle_t trackPortId) {
3686 for (size_t i = 0; i < mTracks.size(); i++) {
3687 if (mTracks[i]->portId() == trackPortId) {
3688 return mTracks[i].get();
3689 }
3690 }
3691 return nullptr;
3692}
3693
Andy Hung71742ab2023-07-07 13:47:37 -07003694status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003695{
Glenn Kastend848eb42016-03-08 13:42:11 -08003696 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003697 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003698 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003699
Andy Hungd3639922022-04-28 18:00:49 -07003700 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003701 if (!audio_is_global_session(session)) {
3702 // player sessions on a spatializer output will use a dedicated input buffer and
3703 // will either output multi channel to mEffectBuffer if the track is spatilaized
3704 // or stereo to mPostSpatializerBuffer if not spatialized.
3705 uint32_t channelMask;
3706 bool isSessionSpatialized =
3707 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3708 if (isSessionSpatialized) {
3709 channelMask = mMixerChannelMask;
3710 } else {
3711 channelMask = mChannelMask;
3712 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003713 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003714 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung2cbc2722023-07-17 17:05:00 -07003715 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003716 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003717 &halInBuffer);
3718 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003719
Andy Hung2cbc2722023-07-17 17:05:00 -07003720 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003721 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3722 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3723 &halOutBuffer);
3724 if (result != OK) return result;
3725
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003726 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003727
Mikhail Naganov022b9952017-01-04 16:36:51 -08003728 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3729 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003730 } else {
3731 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3732 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3733 // mPostSpatializerBuffer as output buffer
3734 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung2cbc2722023-07-17 17:05:00 -07003735 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003736 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3737 if (result != OK) return result;
Andy Hung2cbc2722023-07-17 17:05:00 -07003738 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003739 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3740 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003741
Eric Laurentb62d0362021-10-26 17:40:18 +02003742 if (session == AUDIO_SESSION_DEVICE) {
3743 halInBuffer = halOutBuffer;
3744 }
3745 }
3746 } else {
Andy Hung2cbc2722023-07-17 17:05:00 -07003747 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003748 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3749 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3750 &halInBuffer);
3751 if (result != OK) return result;
3752 halOutBuffer = halInBuffer;
3753 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3754 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003755 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003756 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003757 // Only one effect chain can be present in direct output thread and it uses
3758 // the sink buffer as input
3759 if (mType != DIRECT) {
3760 size_t numSamples = mNormalFrameCount
3761 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3762 + mHapticChannelCount);
Andy Hung2cbc2722023-07-17 17:05:00 -07003763 const status_t allocateStatus =
3764 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003765 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003766 &halInBuffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07003767 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003768
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003769 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003770 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3771 buffer, session);
3772 }
3773 }
3774 }
3775
3776 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003777 // Attach all tracks with same session ID to this chain.
3778 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003779 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003780 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003781 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3782 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003783 track->setMainBuffer(buffer);
3784 chain->incTrackCnt();
3785 }
3786 }
3787
3788 // indicate all active tracks in the chain
Andy Hung3ff4b552023-06-26 19:20:57 -07003789 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003790 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003791 ALOGV("addEffectChain_l() activating track %p on session %d",
3792 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003793 chain->incActiveTrackCnt();
3794 }
3795 }
3796 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003797
Eric Laurentaaa44472014-09-12 17:41:50 -07003798 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003799 chain->setInBuffer(halInBuffer);
3800 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003801 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3802 // chains list in order to be processed last as it contains output device effects.
3803 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3804 // processing effects specific to an output stream before effects applied to all streams
3805 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003806 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3807 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003808 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003809 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003810 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003811 // Effect chain for other sessions are inserted at beginning of effect
3812 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003813 // sessions is not important.
3814 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003815 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3816 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003817 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003818 size_t size = mEffectChains.size();
3819 size_t i = 0;
3820 for (i = 0; i < size; i++) {
3821 if (mEffectChains[i]->sessionId() < session) {
3822 break;
3823 }
3824 }
3825 mEffectChains.insertAt(chain, i);
3826 checkSuspendOnAddEffectChain_l(chain);
3827
3828 return NO_ERROR;
3829}
3830
Andy Hung71742ab2023-07-07 13:47:37 -07003831size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003832{
Glenn Kastend848eb42016-03-08 13:42:11 -08003833 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003834
3835 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3836
3837 for (size_t i = 0; i < mEffectChains.size(); i++) {
3838 if (chain == mEffectChains[i]) {
3839 mEffectChains.removeAt(i);
3840 // detach all active tracks from the chain
Andy Hung3ff4b552023-06-26 19:20:57 -07003841 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003842 if (session == track->sessionId()) {
3843 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3844 chain.get(), session);
3845 chain->decActiveTrackCnt();
3846 }
3847 }
3848
3849 // detach all tracks with same session ID from this chain
Andy Hung71ba4b32022-10-06 12:09:49 -07003850 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003851 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003852 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003853 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003854 chain->decTrackCnt();
3855 }
3856 }
3857 break;
3858 }
3859 }
3860 return mEffectChains.size();
3861}
3862
Andy Hung71742ab2023-07-07 13:47:37 -07003863status_t PlaybackThread::attachAuxEffect(
Andy Hung3ff4b552023-06-26 19:20:57 -07003864 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003865{
3866 Mutex::Autolock _l(mLock);
3867 return attachAuxEffect_l(track, EffectId);
3868}
3869
Andy Hung71742ab2023-07-07 13:47:37 -07003870status_t PlaybackThread::attachAuxEffect_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07003871 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003872{
3873 status_t status = NO_ERROR;
3874
3875 if (EffectId == 0) {
3876 track->setAuxBuffer(0, NULL);
3877 } else {
3878 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hungbd72c542023-06-20 18:56:17 -07003879 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003880 if (effect != 0) {
3881 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3882 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3883 } else {
3884 status = INVALID_OPERATION;
3885 }
3886 } else {
3887 status = BAD_VALUE;
3888 }
3889 }
3890 return status;
3891}
3892
Andy Hung71742ab2023-07-07 13:47:37 -07003893void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003894{
3895 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003896 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003897 if (track->auxEffectId() == effectId) {
3898 attachAuxEffect_l(track, 0);
3899 }
3900 }
3901}
3902
Andy Hung71742ab2023-07-07 13:47:37 -07003903bool PlaybackThread::threadLoop()
Andy Hung71ba4b32022-10-06 12:09:49 -07003904NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003905{
Andy Hung4bf583b2023-05-30 18:10:23 -07003906 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003907
Andy Hung3ff4b552023-06-26 19:20:57 -07003908 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003909
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003910 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003911 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003912
3913 // MIXER
3914 nsecs_t lastWarning = 0;
3915
3916 // DUPLICATING
3917 // FIXME could this be made local to while loop?
3918 writeFrames = 0;
3919
3920 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003921 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003922
Andy Hungd3639922022-04-28 18:00:49 -07003923 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003924 sleepTimeShift = 0;
3925 }
3926
3927 CpuStats cpuStats;
3928 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3929
3930 acquireWakeLock();
3931
Glenn Kasteneef598c2017-04-03 14:41:13 -07003932 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3933 // thread associated with this PlaybackThread.
3934 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3935 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003936 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3937 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003938 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003939 const char *logString = NULL;
3940
rago1bb90822017-05-02 18:31:48 -07003941 // Estimated time for next buffer to be written to hal. This is used only on
3942 // suspended mode (for now) to help schedule the wait time until next iteration.
3943 nsecs_t timeLoopNextNs = 0;
3944
Eric Laurent664539d2013-09-23 18:24:31 -07003945 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003946
Andy Hung2dbffc22018-08-08 18:50:41 -07003947 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003948
Eric Laurentb3f315a2021-07-13 15:09:05 +02003949 sendCheckOutputStageEffectsEvent();
3950
Andy Hung446f4df2019-02-21 12:26:41 -08003951 // loopCount is used for statistics and diagnostics.
3952 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003953 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003954 // Log merge requests are performed during AudioFlinger binder transactions, but
3955 // that does not cover audio playback. It's requested here for that reason.
Andy Hung2cbc2722023-07-17 17:05:00 -07003956 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003957
Eric Laurent81784c32012-11-19 14:55:58 -08003958 cpuStats.sample(myName);
3959
Andy Hungbd72c542023-06-20 18:56:17 -07003960 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003961 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003962 bool isHapticSessionSpatialized = false;
Andy Hung3ff4b552023-06-26 19:20:57 -07003963 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003964
Andy Hung2dbffc22018-08-08 18:50:41 -07003965 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3966 //
jiabinc52b1ff2019-10-31 17:20:42 -07003967 // Note: we access outDeviceTypes() outside of mLock.
3968 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003969 // Here, we try for the AF lock, but do not block on it as the latency
3970 // is more informational.
Andy Hung2cbc2722023-07-17 17:05:00 -07003971 if (mAfThreadCallback->mutex().tryLock() == NO_ERROR) {
Andy Hungd63e79d2023-07-13 16:52:46 -07003972 std::vector<SoftwarePatch> swPatches;
Andy Hung71ba4b32022-10-06 12:09:49 -07003973 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07003974 status_t status = INVALID_OPERATION;
3975 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung2cbc2722023-07-17 17:05:00 -07003976 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungd63e79d2023-07-13 16:52:46 -07003977 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07003978 && swPatches.size() > 0) {
3979 status = swPatches[0].getLatencyMs_l(&latencyMs);
3980 downstreamPatchHandle = swPatches[0].getPatchHandle();
3981 }
3982 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003983 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003984 lastDownstreamPatchHandle = downstreamPatchHandle;
3985 }
3986 if (status == OK) {
3987 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003988 // latency of 5 seconds).
3989 const double minLatency = 0., maxLatency = 5000.;
3990 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003991 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003992 } else {
3993 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung71ba4b32022-10-06 12:09:49 -07003994 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07003995 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003996 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003997 }
Andy Hung2cbc2722023-07-17 17:05:00 -07003998 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07003999 }
4000 } else {
4001 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4002 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004003 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004004 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4005 }
4006 }
4007
Eric Laurentb3f315a2021-07-13 15:09:05 +02004008 if (mCheckOutputStageEffects.exchange(false)) {
4009 checkOutputStageEffects();
4010 }
4011
Vlad Popa7e81cea2023-01-19 16:34:16 +01004012 MetadataUpdate metadataUpdate;
Eric Laurent81784c32012-11-19 14:55:58 -08004013 { // scope for mLock
4014
4015 Mutex::Autolock _l(mLock);
4016
Eric Laurent021cf962014-05-13 10:18:14 -07004017 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004018 if (mCheckOutputStageEffects.load()) {
4019 continue;
4020 }
Eric Laurent10351942014-05-08 18:49:52 -07004021
Glenn Kasteneef598c2017-04-03 14:41:13 -07004022 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08004023 if (logString != NULL) {
4024 mNBLogWriter->logTimestamp();
4025 mNBLogWriter->log(logString);
4026 logString = NULL;
4027 }
4028
Dean Wheatley12473e92021-03-18 23:00:55 +11004029 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004030
Eric Laurent81784c32012-11-19 14:55:58 -08004031 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004032 if (mSignalPending) {
4033 // A signal was raised while we were unlocked
4034 mSignalPending = false;
4035 } else if (waitingAsyncCallback_l()) {
4036 if (exitPending()) {
4037 break;
4038 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004039 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004040 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004041 releaseWakeLock_l();
4042 released = true;
4043 }
Andy Hung10cbff12017-02-21 17:30:14 -08004044
4045 const int64_t waitNs = computeWaitTimeNs_l();
4046 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
4047 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
4048 if (status == TIMED_OUT) {
4049 mSignalPending = true; // if timeout recheck everything
4050 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004051 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004052 if (released) {
4053 acquireWakeLock_l();
4054 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004055 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4056 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004057
4058 continue;
4059 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004060 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004061 isSuspended()) {
4062 // put audio hardware into standby after short delay
4063 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004064
4065 threadLoop_standby();
4066
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004067 // This is where we go into standby
4068 if (!mStandby) {
4069 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004070 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004071 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004072 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004073 }
Andy Hungd0979812019-02-21 15:51:44 -08004074 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004075 }
4076
Eric Tan39ec8d62018-07-24 09:49:29 -07004077 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004078 // we're about to wait, flush the binder command buffer
4079 IPCThreadState::self()->flushCommands();
4080
4081 clearOutputTracks();
4082
4083 if (exitPending()) {
4084 break;
4085 }
4086
4087 releaseWakeLock_l();
4088 // wait until we have something to do...
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00004089 ALOGV("%s going to sleep", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004090 mWaitWorkCV.wait(mLock);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00004091 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004092 acquireWakeLock_l();
4093
4094 mMixerStatus = MIXER_IDLE;
4095 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4096 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004097 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004098 checkSilentMode_l();
4099
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004100 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4101 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004102 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004103 sleepTimeShift = 0;
4104 }
4105
4106 continue;
4107 }
4108 }
Eric Laurent81784c32012-11-19 14:55:58 -08004109 // mMixerStatusIgnoringFastTracks is also updated internally
4110 mMixerStatus = prepareTracks_l(&tracksToRemove);
4111
Andy Hungdae27702016-10-31 14:01:16 -07004112 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004113
Vlad Popa7e81cea2023-01-19 16:34:16 +01004114 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004115
Eric Laurent81784c32012-11-19 14:55:58 -08004116 // prevent any changes in effect chain list and in each effect chain
4117 // during mixing and effect process as the audio buffers could be deleted
4118 // or modified if an effect is created or deleted
4119 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004120
4121 // Determine which session to pick up haptic data.
4122 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004123 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004124 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004125 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004126 for (const auto& track : mActiveTracks) {
Andy Hungbd72c542023-06-20 18:56:17 -07004127 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004128 if (effectChain != nullptr
4129 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004130 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004131 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004132 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004133 break;
4134 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004135 if (activeHapticSessionId == AUDIO_SESSION_NONE
4136 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004137 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004138 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004139 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004140 }
4141 }
4142 }
4143
Andy Hungc1646382019-04-30 16:12:10 -07004144 // Acquire a local copy of active tracks with lock (release w/o lock).
4145 //
4146 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4147 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4148 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4149 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent6f9534f2022-05-03 18:15:04 +02004150
4151 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004152
Jiabin Huangfb476842022-12-06 03:18:10 +00004153 for (const auto &track : mActiveTracks ) {
4154 track->updateTeePatches();
4155 }
4156
Eric Laurent19952e12023-04-20 10:08:29 +02004157 // signal actual start of output stream when the render position reported by the kernel
4158 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004159 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4160 && (mKernelPositionOnStandby
4161 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004162 mHalStarted = true;
4163 mWaitHalStartCV.broadcast();
4164 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004165 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004166
Eric Laurentbfb1b832013-01-07 09:53:42 -08004167 if (mBytesRemaining == 0) {
4168 mCurrentWriteLength = 0;
4169 if (mMixerStatus == MIXER_TRACKS_READY) {
4170 // threadLoop_mix() sets mCurrentWriteLength
4171 threadLoop_mix();
4172 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4173 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004174 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004175 // must be written to HAL
4176 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004177 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004178 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004179
4180 // Tally underrun frames as we are inserting 0s here.
4181 for (const auto& track : activeTracks) {
Andy Hung3ff4b552023-06-26 19:20:57 -07004182 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004183 && !track->isStopped()
4184 && !track->isPaused()
4185 && !track->isTerminated()) {
4186 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4187 __func__, track->id(), track->getTrackStateAsString(),
4188 mNormalFrameCount);
Andy Hung3ff4b552023-06-26 19:20:57 -07004189 track->audioTrackServerProxy()->tallyUnderrunFrames(
4190 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004191 }
4192 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004193 }
4194 }
Andy Hung98ef9782014-03-04 14:46:50 -08004195 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004196 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004197 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004198 // or mSinkBuffer (if there are no effects and there is no data already copied to
4199 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004200 //
4201 // This is done pre-effects computation; if effects change to
4202 // support higher precision, this needs to move.
4203 //
4204 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004205 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004206 uint32_t mixerChannelCount = mEffectBufferValid ?
4207 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004208 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004209 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4210 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4211
David Li88ee0902022-06-22 10:01:21 +08004212 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4213 // do these processes after effects are applied.
4214 if (!mEffectBufferValid) {
4215 // mono blend occurs for mixer threads only (not direct or offloaded)
4216 // and is handled here if we're going directly to the sink.
4217 if (requireMonoBlend()) {
4218 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4219 mNormalFrameCount, true /*limit*/);
4220 }
Andy Hung2ddee192015-12-18 17:34:44 -08004221
David Li88ee0902022-06-22 10:01:21 +08004222 if (!hasFastMixer()) {
4223 // Balance must take effect after mono conversion.
4224 // We do it here if there is no FastMixer.
4225 // mBalance detects zero balance within the class for speed
4226 // (not needed here).
4227 mBalance.setBalance(mMasterBalance.load());
4228 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4229 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004230 }
4231
Andy Hung98ef9782014-03-04 14:46:50 -08004232 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004233 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004234
4235 // If we're going directly to the sink and there are haptic channels,
4236 // we should adjust channels as the sample data is partially interleaved
4237 // in this case.
4238 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4239 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4240 mChannelCount + mHapticChannelCount,
4241 audio_bytes_per_sample(format),
4242 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4243 }
Andy Hung98ef9782014-03-04 14:46:50 -08004244 }
4245
Eric Laurentbfb1b832013-01-07 09:53:42 -08004246 mBytesRemaining = mCurrentWriteLength;
4247 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004248 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4249 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4250 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4251 mBytesWritten += mBytesRemaining;
4252 mFramesWritten += framesRemaining;
4253 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004254 mBytesRemaining = 0;
4255 }
Eric Laurent81784c32012-11-19 14:55:58 -08004256
Eric Laurentbfb1b832013-01-07 09:53:42 -08004257 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004258 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004259 for (size_t i = 0; i < effectChains.size(); i ++) {
4260 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004261 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004262 if (activeHapticSessionId != AUDIO_SESSION_NONE
4263 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004264 // Haptic data is active in this case, copy it directly from
4265 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004266 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4267 audio_channel_count_from_out_mask(mMixerChannelMask) :
4268 mChannelCount;
4269 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4270 hapticSessionChannelCount = mChannelCount;
4271 }
4272
jiabin47affe52019-04-04 18:02:07 -07004273 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004274 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004275 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004276 memcpy_by_audio_format(
4277 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004278 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004279 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004280 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004281 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004282 }
Eric Laurent81784c32012-11-19 14:55:58 -08004283 }
4284 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004285 // Process effect chains for offloaded thread even if no audio
4286 // was read from audio track: process only updates effect state
4287 // and thus does have to be synchronized with audio writes but may have
4288 // to be called while waiting for async write callback
4289 if (mType == OFFLOAD) {
4290 for (size_t i = 0; i < effectChains.size(); i ++) {
4291 effectChains[i]->process_l();
4292 }
4293 }
Eric Laurent81784c32012-11-19 14:55:58 -08004294
Andy Hung98ef9782014-03-04 14:46:50 -08004295 // Only if the Effects buffer is enabled and there is data in the
4296 // Effects buffer (buffer valid), we need to
4297 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004298 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004299 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004300 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004301 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004302 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004303 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004304 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004305 }
4306
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004307 if (!hasFastMixer()) {
4308 // Balance must take effect after mono conversion.
4309 // We do it here if there is no FastMixer.
4310 // mBalance detects zero balance within the class for speed (not needed here).
4311 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004312 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004313 }
4314
Eric Laurentb62d0362021-10-26 17:40:18 +02004315 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4316 // mPostSpatializerBuffer if the haptics track is spatialized.
4317 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4318 // For other thread types, the haptics channels are already in mEffectBuffer.
4319 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4320 const size_t srcBufferSize = mNormalFrameCount *
4321 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4322 mEffectBufferFormat);
4323 const size_t dstBufferSize = mNormalFrameCount
4324 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4325
4326 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4327 mEffectBufferFormat,
4328 (uint8_t*)mEffectBuffer + srcBufferSize,
4329 mEffectBufferFormat,
4330 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004331 }
Atneya Nair68436cf2022-09-19 17:51:37 -07004332 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4333 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4334 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4335 // Clamp PCM float values more than this distance from 0 to insulate
4336 // a HAL which doesn't handle NaN correctly.
4337 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4338 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4339 static_cast<const float*>(effectBuffer),
4340 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4341 } else {
4342 memcpy_by_audio_format(mSinkBuffer, mFormat,
4343 effectBuffer, mEffectBufferFormat, framesToCopy);
4344 }
jiabin245cdd92018-12-07 17:55:15 -08004345 // The sample data is partially interleaved when haptic channels exist,
4346 // we need to adjust channels here.
4347 if (mHapticChannelCount > 0) {
4348 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4349 mChannelCount + mHapticChannelCount,
4350 audio_bytes_per_sample(mFormat),
4351 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4352 }
Andy Hung98ef9782014-03-04 14:46:50 -08004353 }
4354
Eric Laurent81784c32012-11-19 14:55:58 -08004355 // enable changes in effect chain
4356 unlockEffectChains(effectChains);
4357
Vlad Popafce10862023-02-03 10:37:07 +01004358 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung2cbc2722023-07-17 17:05:00 -07004359 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004360 metadataUpdate.playbackMetadataUpdate);
4361 }
4362
Eric Laurentbfb1b832013-01-07 09:53:42 -08004363 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004364 // mSleepTimeUs == 0 means we must write to audio hardware
4365 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004366 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004367 // writePeriodNs is updated >= 0 when ret > 0.
4368 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004369 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004370 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004371 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004372 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004373 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004374 if (ret < 0) {
4375 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004376 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004377 mBytesWritten += ret;
4378 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004379 const int64_t frames = ret / mFrameSize;
4380 mFramesWritten += frames;
4381
4382 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4383 // process information relating to write time.
4384 if (audio_has_proportional_frames(mFormat)) {
4385 // we are in a continuous mixing cycle
4386 if (mMixerStatus == MIXER_TRACKS_READY &&
4387 loopCount == lastLoopCountWritten + 1) {
4388
4389 const double jitterMs =
4390 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4391 {frames, writePeriodNs},
4392 {0, 0} /* lastTimestamp */, mSampleRate);
4393 const double processMs =
4394 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4395
4396 Mutex::Autolock _l(mLock);
4397 mIoJitterMs.add(jitterMs);
4398 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004399
4400 if (mPipeSink.get() != nullptr) {
4401 // Using the Monopipe availableToWrite, we estimate the current
4402 // buffer size.
4403 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4404 const ssize_t
4405 availableToWrite = mPipeSink->availableToWrite();
4406 const size_t pipeFrames = monoPipe->maxFrames();
4407 const size_t
4408 remainingFrames = pipeFrames - max(availableToWrite, 0);
4409 mMonopipePipeDepthStats.add(remainingFrames);
4410 }
Andy Hung446f4df2019-02-21 12:26:41 -08004411 }
4412
4413 // write blocked detection
4414 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004415 if ((mType == MIXER || mType == SPATIALIZER)
4416 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004417 mNumDelayedWrites++;
4418 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4419 ATRACE_NAME("underrun");
4420 ALOGW("write blocked for %lld msecs, "
4421 "%d delayed writes, thread %d",
4422 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4423 mNumDelayedWrites, mId);
4424 lastWarning = lastIoEndNs;
4425 }
4426 }
4427 }
4428 // update timing info.
4429 mLastIoBeginNs = lastIoBeginNs;
4430 mLastIoEndNs = lastIoEndNs;
4431 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004432 }
4433 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4434 (mMixerStatus == MIXER_DRAIN_ALL)) {
4435 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004436 }
Andy Hungd3639922022-04-28 18:00:49 -07004437 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004438
4439 if (mThreadThrottle
4440 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004441 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004442 // Limit MixerThread data processing to no more than twice the
4443 // expected processing rate.
4444 //
4445 // This helps prevent underruns with NuPlayer and other applications
4446 // which may set up buffers that are close to the minimum size, or use
4447 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4448 //
4449 // The throttle smooths out sudden large data drains from the device,
4450 // e.g. when it comes out of standby, which often causes problems with
4451 // (1) mixer threads without a fast mixer (which has its own warm-up)
4452 // (2) minimum buffer sized tracks (even if the track is full,
4453 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004454 //
4455 // Total time spent in last processing cycle equals time spent in
4456 // 1. threadLoop_write, as well as time spent in
4457 // 2. threadLoop_mix (significant for heavy mixing, especially
4458 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004459
Andy Hung446f4df2019-02-21 12:26:41 -08004460 // it's OK if deltaMs is an overestimate.
4461
4462 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004463
Ivan Lozanoea04d392017-11-07 14:37:07 -08004464 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004465 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004466 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004467
Andy Hung08fb1742015-05-31 23:22:10 -07004468 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004469 // notify of throttle start on verbose log
4470 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4471 "mixer(%p) throttle begin:"
4472 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004473 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004474 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004475 // Throttle must be attributed to the previous mixer loop's write time
4476 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004477 // This also ensures proper timing statistics.
4478 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004479 } else {
4480 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4481 if (diff > 0) {
4482 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004483 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004484 ALOGD_IF(!isSingleDeviceType(
4485 outDeviceTypes(), audio_is_a2dp_out_device) &&
4486 !isSingleDeviceType(
4487 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004488 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004489 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4490 }
Andy Hung08fb1742015-05-31 23:22:10 -07004491 }
4492 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004493 }
Eric Laurent81784c32012-11-19 14:55:58 -08004494
Eric Laurentbfb1b832013-01-07 09:53:42 -08004495 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004496 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004497 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004498 // suspended requires accurate metering of sleep time.
4499 if (isSuspended()) {
4500 // advance by expected sleepTime
4501 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4502 const nsecs_t nowNs = systemTime();
4503
4504 // compute expected next time vs current time.
4505 // (negative deltas are treated as delays).
4506 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4507 if (deltaNs < -kMaxNextBufferDelayNs) {
4508 // Delays longer than the max allowed trigger a reset.
4509 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4510 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4511 timeLoopNextNs = nowNs + deltaNs;
4512 } else if (deltaNs < 0) {
4513 // Delays within the max delay allowed: zero the delta/sleepTime
4514 // to help the system catch up in the next iteration(s)
4515 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4516 deltaNs = 0;
4517 }
4518 // update sleep time (which is >= 0)
4519 mSleepTimeUs = deltaNs / 1000;
4520 }
Eric Laurente93cc032016-05-05 10:15:10 -07004521 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4522 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004523 }
Glenn Kastene7754022014-10-31 12:11:26 -07004524 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004525 }
Eric Laurent81784c32012-11-19 14:55:58 -08004526 }
4527
4528 // Finally let go of removed track(s), without the lock held
4529 // since we can't guarantee the destructors won't acquire that
4530 // same lock. This will also mutate and push a new fast mixer state.
4531 threadLoop_removeTracks(tracksToRemove);
4532 tracksToRemove.clear();
4533
4534 // FIXME I don't understand the need for this here;
4535 // it was in the original code but maybe the
4536 // assignment in saveOutputTracks() makes this unnecessary?
4537 clearOutputTracks();
4538
4539 // Effect chains will be actually deleted here if they were removed from
4540 // mEffectChains list during mixing or effects processing
4541 effectChains.clear();
4542
4543 // FIXME Note that the above .clear() is no longer necessary since effectChains
4544 // is now local to this block, but will keep it for now (at least until merge done).
4545 }
4546
Eric Laurentbfb1b832013-01-07 09:53:42 -08004547 threadLoop_exit();
4548
Eric Laurentcf817a22014-08-04 20:36:31 -07004549 if (!mStandby) {
4550 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004551 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004552 }
4553
4554 releaseWakeLock();
4555
4556 ALOGV("Thread %p type %d exiting", this, mType);
4557 return false;
4558}
4559
Andy Hung71742ab2023-07-07 13:47:37 -07004560void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004561{
Dean Wheatley12473e92021-03-18 23:00:55 +11004562 if (mStandby) {
4563 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4564 return;
4565 } else if (mHwPaused) {
4566 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4567 return;
4568 }
4569
4570 // Gather the framesReleased counters for all active tracks,
4571 // and associate with the sink frames written out. We need
4572 // this to convert the sink timestamp to the track timestamp.
4573 bool kernelLocationUpdate = false;
4574 ExtendedTimestamp timestamp; // use private copy to fetch
4575
4576 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4577 // HAL may be draining some small duration buffered data for fade out.
4578 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4579 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4580 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4581 mSampleRate);
4582
4583 if (isTimestampCorrectionEnabled()) {
4584 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4585 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4586 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4587 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4588 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4589 = correctedTimestamp.mFrames;
4590 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4591 = correctedTimestamp.mTimeNs;
4592 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4593 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4594 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4595
4596 // Note: Downstream latency only added if timestamp correction enabled.
4597 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4598 const int64_t newPosition =
4599 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4600 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4601 // prevent retrograde
4602 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4603 newPosition,
4604 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4605 - mSuspendedFrames));
4606 }
4607 }
4608
4609 // We always fetch the timestamp here because often the downstream
4610 // sink will block while writing.
4611
4612 // We keep track of the last valid kernel position in case we are in underrun
4613 // and the normal mixer period is the same as the fast mixer period, or there
4614 // is some error from the HAL.
4615 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4616 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4617 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4618 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4619 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4620
4621 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4622 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4623 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4624 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4625 }
4626
4627 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4628 kernelLocationUpdate = true;
4629 } else {
4630 ALOGVV("getTimestamp error - no valid kernel position");
4631 }
4632
4633 // copy over kernel info
4634 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4635 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4636 + mSuspendedFrames; // add frames discarded when suspended
4637 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4638 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4639 } else {
4640 mTimestampVerifier.error();
4641 }
4642
4643 // mFramesWritten for non-offloaded tracks are contiguous
4644 // even after standby() is called. This is useful for the track frame
4645 // to sink frame mapping.
4646 bool serverLocationUpdate = false;
4647 if (mFramesWritten != mLastFramesWritten) {
4648 serverLocationUpdate = true;
4649 mLastFramesWritten = mFramesWritten;
4650 }
4651 // Only update timestamps if there is a meaningful change.
4652 // Either the kernel timestamp must be valid or we have written something.
4653 if (kernelLocationUpdate || serverLocationUpdate) {
4654 if (serverLocationUpdate) {
4655 // use the time before we called the HAL write - it is a bit more accurate
4656 // to when the server last read data than the current time here.
4657 //
4658 // If we haven't written anything, mLastIoBeginNs will be -1
4659 // and we use systemTime().
4660 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4661 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4662 ? systemTime() : mLastIoBeginNs;
4663 }
4664
Andy Hung3ff4b552023-06-26 19:20:57 -07004665 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004666 if (!t->isFastTrack()) {
4667 t->updateTrackFrameInfo(
Andy Hung3ff4b552023-06-26 19:20:57 -07004668 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004669 mFramesWritten,
4670 mSampleRate,
4671 mTimestamp);
4672 }
4673 }
4674 }
4675
4676 if (audio_has_proportional_frames(mFormat)) {
4677 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4678 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4679 mLatencyMs.add(latencyMs);
4680 }
4681 }
4682#if 0
4683 // logFormat example
4684 if (z % 100 == 0) {
4685 timespec ts;
4686 clock_gettime(CLOCK_MONOTONIC, &ts);
4687 LOGT("This is an integer %d, this is a float %f, this is my "
4688 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4689 LOGT("A deceptive null-terminated string %\0");
4690 }
4691 ++z;
4692#endif
4693}
4694
Eric Laurentbfb1b832013-01-07 09:53:42 -08004695// removeTracks_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07004696void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hung71ba4b32022-10-06 12:09:49 -07004697NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurentbfb1b832013-01-07 09:53:42 -08004698{
Andy Hungfe726a62018-09-27 15:17:25 -07004699 for (const auto& track : tracksToRemove) {
4700 mActiveTracks.remove(track);
4701 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hungbd72c542023-06-20 18:56:17 -07004702 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004703 if (chain != 0) {
4704 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4705 __func__, track->id(), chain.get(), track->sessionId());
4706 chain->decActiveTrackCnt();
4707 }
4708 // If an external client track, inform APM we're no longer active, and remove if needed.
4709 // We do this under lock so that the state is consistent if the Track is destroyed.
4710 if (track->isExternalTrack()) {
4711 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004712 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004713 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004714 }
4715 }
Andy Hungfe726a62018-09-27 15:17:25 -07004716 if (track->isTerminated()) {
4717 // remove from our tracks vector
4718 removeTrack_l(track);
4719 }
jiabineb3bda02020-06-30 14:07:03 -07004720 if (mHapticChannelCount > 0 &&
4721 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4722 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004723 mLock.unlock();
4724 // Unlock due to VibratorService will lock for this call and will
4725 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung9554ec02023-07-20 21:23:42 -07004726 afutils::onExternalVibrationStop(track->getExternalVibration());
jiabin57303cc2018-12-18 15:45:57 -08004727 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004728
4729 // When the track is stop, set the haptic intensity as MUTE
4730 // for the HapticGenerator effect.
4731 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004732 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004733 }
jiabin245cdd92018-12-07 17:55:15 -08004734 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004735 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004736}
Eric Laurent81784c32012-11-19 14:55:58 -08004737
Andy Hung71742ab2023-07-07 13:47:37 -07004738status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004739{
4740 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004741 ExtendedTimestamp ets;
4742 status_t status = mNormalSink->getTimestamp(ets);
4743 if (status == NO_ERROR) {
4744 status = ets.getBestTimestamp(&timestamp);
4745 }
4746 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004747 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004748 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004749 collectTimestamps_l();
4750 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4751 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004752 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004753 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4754 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4755 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4756 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4757 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004758 }
4759 return INVALID_OPERATION;
4760}
Eric Laurent1c333e22014-05-20 10:48:17 -07004761
Eric Laurenteab90452019-06-24 15:17:46 -07004762// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4763// still applied by the mixer.
4764// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4765// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4766// if more than one track are active
Andy Hung71742ab2023-07-07 13:47:37 -07004767status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004768{
4769 status_t result = NO_ERROR;
4770 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4771 if (*volume != mLeftVolFloat) {
4772 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004773 // HAL can return INVALID_OPERATION if operation is not supported.
4774 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004775 "Error when setting output stream volume: %d", result);
4776 if (result == NO_ERROR) {
4777 mLeftVolFloat = *volume;
4778 }
4779 }
4780 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4781 // remove stream volume contribution from software volume.
4782 if (mLeftVolFloat == *volume) {
4783 *volume = 1.0f;
4784 }
4785 }
4786 return result;
4787}
4788
Andy Hung71742ab2023-07-07 13:47:37 -07004789status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004790 audio_patch_handle_t *handle)
4791{
Andy Hungf60abce2016-08-26 11:37:54 -07004792 status_t status;
4793 if (property_get_bool("af.patch_park", false /* default_value */)) {
4794 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4795 // or if HAL does not properly lock against access.
4796 AutoPark<FastMixer> park(mFastMixer);
4797 status = PlaybackThread::createAudioPatch_l(patch, handle);
4798 } else {
4799 status = PlaybackThread::createAudioPatch_l(patch, handle);
4800 }
Eric Laurentb0463942022-12-20 16:31:10 +01004801
4802 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004803 return status;
4804}
4805
Andy Hung71742ab2023-07-07 13:47:37 -07004806status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004807 audio_patch_handle_t *handle)
4808{
4809 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004810
4811 // store new device and send to effects
4812 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004813 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004814 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004815 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4816 && !mOutput->audioHwDev->supportsAudioPatches(),
4817 "Enumerated device type(%#x) must not be used "
4818 "as it does not support audio patches",
4819 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004820 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung71ba4b32022-10-06 12:09:49 -07004821 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4822 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004823 }
4824
François Gaffie0c280aa2018-07-25 10:02:15 +02004825 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004826#ifdef ADD_BATTERY_DATA
4827 // when changing the audio output device, call addBatteryData to notify
4828 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004829 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004830 uint32_t params = 0;
4831 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004832 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004833 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004834 }
4835
Eric Laurent054d9d32015-04-24 08:48:48 -07004836 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004837 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004838 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4839 }
4840
4841 if (params != 0) {
4842 addBatteryData(params);
4843 }
4844 }
4845#endif
4846
4847 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004848 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004849 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004850
jiabinc52b1ff2019-10-31 17:20:42 -07004851 // mPatch.num_sinks is not set when the thread is created so that
4852 // the first patch creation triggers an ioConfigChanged callback
4853 bool configChanged = (mPatch.num_sinks == 0) ||
4854 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004855 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004856 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004857 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004858
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004859 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004860 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4861 status = hwDevice->createAudioPatch(patch->num_sources,
4862 patch->sources,
4863 patch->num_sinks,
4864 patch->sinks,
4865 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004866 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004867 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004868 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004869 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004870 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004871
4872 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004873 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004874 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004875 // also dispatch to active AudioTracks for MediaMetrics
4876 for (const auto &track : mActiveTracks) {
4877 track->logEndInterval();
4878 track->logBeginInterval(patchSinksAsString);
4879 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004880
Eric Laurente8726fe2015-06-26 09:39:24 -07004881 if (configChanged) {
4882 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4883 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004884 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004885 mActiveTracks.setHasChanged();
4886
Eric Laurent1c333e22014-05-20 10:48:17 -07004887 return status;
4888}
4889
Andy Hung71742ab2023-07-07 13:47:37 -07004890status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004891{
Andy Hungf60abce2016-08-26 11:37:54 -07004892 status_t status;
4893 if (property_get_bool("af.patch_park", false /* default_value */)) {
4894 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4895 // or if HAL does not properly lock against access.
4896 AutoPark<FastMixer> park(mFastMixer);
4897 status = PlaybackThread::releaseAudioPatch_l(handle);
4898 } else {
4899 status = PlaybackThread::releaseAudioPatch_l(handle);
4900 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004901 return status;
4902}
4903
Andy Hung71742ab2023-07-07 13:47:37 -07004904status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004905{
4906 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004907
jiabinc52b1ff2019-10-31 17:20:42 -07004908 mPatch = audio_patch{};
4909 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004910
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004911 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004912 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4913 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004914 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004915 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004916 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004917 // Force meteadata update after a route change
4918 mActiveTracks.setHasChanged();
4919
Eric Laurent1c333e22014-05-20 10:48:17 -07004920 return status;
4921}
4922
Andy Hung71742ab2023-07-07 13:47:37 -07004923void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004924{
4925 Mutex::Autolock _l(mLock);
4926 mTracks.add(track);
4927}
4928
Andy Hung71742ab2023-07-07 13:47:37 -07004929void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004930{
4931 Mutex::Autolock _l(mLock);
4932 destroyTrack_l(track);
4933}
4934
Andy Hung71742ab2023-07-07 13:47:37 -07004935void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07004936{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004937 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004938 config->role = AUDIO_PORT_ROLE_SOURCE;
4939 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4940 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004941 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4942 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4943 config->flags.output = mOutput->flags;
4944 }
Eric Laurent83b88082014-06-20 18:31:16 -07004945}
4946
Eric Laurent81784c32012-11-19 14:55:58 -08004947// ----------------------------------------------------------------------------
4948
Andy Hung71742ab2023-07-07 13:47:37 -07004949/* static */
4950sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07004951 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hung71742ab2023-07-07 13:47:37 -07004952 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung2cbc2722023-07-17 17:05:00 -07004953 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hung71742ab2023-07-07 13:47:37 -07004954}
4955
Andy Hung2cbc2722023-07-17 17:05:00 -07004956MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004957 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung2cbc2722023-07-17 17:05:00 -07004958 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004959 // mAudioMixer below
4960 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01004961 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004962 mFastMixerFutex(0),
4963 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004964 // mOutputSink below
4965 // mPipeSink below
4966 // mNormalSink below
4967{
Andy Hung2cbc2722023-07-17 17:05:00 -07004968 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004969 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004970 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004971 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004972 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4973 mNormalFrameCount);
4974 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4975
Andy Hungfbfc3952015-01-15 13:33:51 -08004976 if (type == DUPLICATING) {
4977 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4978 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4979 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4980 return;
4981 }
Eric Laurent81784c32012-11-19 14:55:58 -08004982 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004983 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004984 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004985 const NBAIO_Format offers[1] = {Format_from_SR_C(
4986 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004987#if !LOG_NDEBUG
4988 ssize_t index =
4989#else
4990 (void)
4991#endif
4992 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004993 ALOG_ASSERT(index == 0);
4994
4995 // initialize fast mixer depending on configuration
4996 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00004997 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08004998 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004999 } else {
5000 switch (kUseFastMixer) {
5001 case FastMixer_Never:
5002 initFastMixer = false;
5003 break;
5004 case FastMixer_Always:
5005 initFastMixer = true;
5006 break;
5007 case FastMixer_Static:
5008 case FastMixer_Dynamic:
5009 initFastMixer = mFrameCount < mNormalFrameCount;
5010 break;
5011 }
5012 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5013 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5014 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005015 }
5016 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005017 audio_format_t fastMixerFormat;
5018 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5019 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5020 } else {
5021 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5022 }
5023 if (mFormat != fastMixerFormat) {
5024 // change our Sink format to accept our intermediate precision
5025 mFormat = fastMixerFormat;
5026 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005027 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005028 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5029 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5030 }
Eric Laurent81784c32012-11-19 14:55:58 -08005031
5032 // create a MonoPipe to connect our submix to FastMixer
5033 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005034
Andy Hung1258c1a2014-05-23 21:22:17 -07005035 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005036 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005037 format.mFormat = fastMixerFormat;
5038 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5039
Eric Laurent81784c32012-11-19 14:55:58 -08005040 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5041 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5042 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5043 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung71ba4b32022-10-06 12:09:49 -07005044 const NBAIO_Format offersFast[1] = {format};
5045 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005046#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005047 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005048#else
5049 (void)
5050#endif
Andy Hung71ba4b32022-10-06 12:09:49 -07005051 monoPipe->negotiate(offersFast, std::size(offersFast),
5052 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005053 ALOG_ASSERT(index == 0);
5054 monoPipe->setAvgFrames((mScreenState & 1) ?
5055 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5056 mPipeSink = monoPipe;
5057
Eric Laurent81784c32012-11-19 14:55:58 -08005058 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005059 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005060 FastMixerStateQueue *sq = mFastMixer->sq();
5061#ifdef STATE_QUEUE_DUMP
5062 sq->setObserverDump(&mStateQueueObserverDump);
5063 sq->setMutatorDump(&mStateQueueMutatorDump);
5064#endif
5065 FastMixerState *state = sq->begin();
5066 FastTrack *fastTrack = &state->mFastTracks[0];
5067 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5068 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5069 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005070 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5071 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5072 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005073 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005074 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07005075 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01005076 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005077 fastTrack->mGeneration++;
5078 state->mFastTracksGen++;
5079 state->mTrackMask = 1;
5080 // fast mixer will use the HAL output sink
5081 state->mOutputSink = mOutputSink.get();
5082 state->mOutputSinkGen++;
5083 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005084 // specify sink channel mask when haptic channel mask present as it can not
5085 // be calculated directly from channel count
5086 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005087 ? AUDIO_CHANNEL_NONE
5088 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005089 state->mCommand = FastMixerState::COLD_IDLE;
5090 // already done in constructor initialization list
5091 //mFastMixerFutex = 0;
5092 state->mColdFutexAddr = &mFastMixerFutex;
5093 state->mColdGen++;
5094 state->mDumpState = &mFastMixerDumpState;
Andy Hung2cbc2722023-07-17 17:05:00 -07005095 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005096 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005097 sq->end();
5098 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5099
Eric Tan0513b5d2018-09-17 10:32:48 -07005100 NBLog::thread_info_t info;
5101 info.id = mId;
5102 info.type = NBLog::FASTMIXER;
5103 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5104
Eric Laurent81784c32012-11-19 14:55:58 -08005105 // start the fast mixer
5106 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5107 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005108 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005109 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005110
5111#ifdef AUDIO_WATCHDOG
5112 // create and start the watchdog
5113 mAudioWatchdog = new AudioWatchdog();
5114 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5115 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5116 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005117 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005118#endif
Andy Hung8946a282018-04-19 20:04:56 -07005119 } else {
5120#ifdef TEE_SINK
5121 // Only use the MixerThread tee if there is no FastMixer.
5122 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5123 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5124#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005125 }
5126
5127 switch (kUseFastMixer) {
5128 case FastMixer_Never:
5129 case FastMixer_Dynamic:
5130 mNormalSink = mOutputSink;
5131 break;
5132 case FastMixer_Always:
5133 mNormalSink = mPipeSink;
5134 break;
5135 case FastMixer_Static:
5136 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5137 break;
5138 }
5139}
5140
Andy Hung71742ab2023-07-07 13:47:37 -07005141MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005142{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005143 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005144 FastMixerStateQueue *sq = mFastMixer->sq();
5145 FastMixerState *state = sq->begin();
5146 if (state->mCommand == FastMixerState::COLD_IDLE) {
5147 int32_t old = android_atomic_inc(&mFastMixerFutex);
5148 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005149 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005150 }
5151 }
5152 state->mCommand = FastMixerState::EXIT;
5153 sq->end();
5154 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5155 mFastMixer->join();
5156 // Though the fast mixer thread has exited, it's state queue is still valid.
5157 // We'll use that extract the final state which contains one remaining fast track
5158 // corresponding to our sub-mix.
5159 state = sq->begin();
5160 ALOG_ASSERT(state->mTrackMask == 1);
5161 FastTrack *fastTrack = &state->mFastTracks[0];
5162 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5163 delete fastTrack->mBufferProvider;
5164 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005165 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005166#ifdef AUDIO_WATCHDOG
5167 if (mAudioWatchdog != 0) {
5168 mAudioWatchdog->requestExit();
5169 mAudioWatchdog->requestExitAndWait();
5170 mAudioWatchdog.clear();
5171 }
5172#endif
5173 }
Andy Hung2cbc2722023-07-17 17:05:00 -07005174 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005175 delete mAudioMixer;
5176}
5177
Andy Hung71742ab2023-07-07 13:47:37 -07005178void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005179 PlaybackThread::onFirstRef();
5180
5181 Mutex::Autolock _l(mLock);
5182 if (mOutput != nullptr && mOutput->stream != nullptr) {
5183 status_t status = mOutput->stream->setLatencyModeCallback(this);
5184 if (status != INVALID_OPERATION) {
5185 updateHalSupportedLatencyModes_l();
5186 }
5187 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5188 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5189 mBluetoothLatencyModesEnabled.store(
5190 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5191 }
5192}
Eric Laurent81784c32012-11-19 14:55:58 -08005193
Andy Hung71742ab2023-07-07 13:47:37 -07005194uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005195{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005196 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005197 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5198 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5199 }
5200 return latency;
5201}
5202
Andy Hung71742ab2023-07-07 13:47:37 -07005203ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005204{
5205 // FIXME we should only do one push per cycle; confirm this is true
5206 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005207 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005208 FastMixerStateQueue *sq = mFastMixer->sq();
5209 FastMixerState *state = sq->begin();
5210 if (state->mCommand != FastMixerState::MIX_WRITE &&
5211 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5212 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005213
5214 // FIXME workaround for first HAL write being CPU bound on some devices
5215 ATRACE_BEGIN("write");
5216 mOutput->write((char *)mSinkBuffer, 0);
5217 ATRACE_END();
5218
Eric Laurent81784c32012-11-19 14:55:58 -08005219 int32_t old = android_atomic_inc(&mFastMixerFutex);
5220 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005221 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005222 }
5223#ifdef AUDIO_WATCHDOG
5224 if (mAudioWatchdog != 0) {
5225 mAudioWatchdog->resume();
5226 }
5227#endif
5228 }
5229 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005230#ifdef FAST_THREAD_STATISTICS
Andy Hung2cbc2722023-07-17 17:05:00 -07005231 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005232 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005233#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005234 sq->end();
5235 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5236 if (kUseFastMixer == FastMixer_Dynamic) {
5237 mNormalSink = mPipeSink;
5238 }
5239 } else {
5240 sq->end(false /*didModify*/);
5241 }
5242 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005243 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005244}
5245
Andy Hung71742ab2023-07-07 13:47:37 -07005246void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005247{
5248 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005249 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005250 FastMixerStateQueue *sq = mFastMixer->sq();
5251 FastMixerState *state = sq->begin();
5252 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005253 // Report any frames trapped in the Monopipe
5254 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5255 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5256 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5257 "monoPipeWritten:%lld monoPipeLeft:%lld",
5258 (long long)mFramesWritten, (long long)mSuspendedFrames,
5259 (long long)mPipeSink->framesWritten(), pipeFrames);
5260 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5261
Eric Laurent81784c32012-11-19 14:55:58 -08005262 state->mCommand = FastMixerState::COLD_IDLE;
5263 state->mColdFutexAddr = &mFastMixerFutex;
5264 state->mColdGen++;
5265 mFastMixerFutex = 0;
5266 sq->end();
5267 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5268 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5269 if (kUseFastMixer == FastMixer_Dynamic) {
5270 mNormalSink = mOutputSink;
5271 }
5272#ifdef AUDIO_WATCHDOG
5273 if (mAudioWatchdog != 0) {
5274 mAudioWatchdog->pause();
5275 }
5276#endif
5277 } else {
5278 sq->end(false /*didModify*/);
5279 }
5280 }
5281 PlaybackThread::threadLoop_standby();
5282}
5283
Andy Hung71742ab2023-07-07 13:47:37 -07005284bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005285{
5286 return false;
5287}
5288
Andy Hung71742ab2023-07-07 13:47:37 -07005289bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005290{
5291 return !mStandby;
5292}
5293
Andy Hung71742ab2023-07-07 13:47:37 -07005294bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005295{
5296 Mutex::Autolock _l(mLock);
5297 return waitingAsyncCallback_l();
5298}
5299
Eric Laurent81784c32012-11-19 14:55:58 -08005300// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung71742ab2023-07-07 13:47:37 -07005301void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005302{
5303 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005304 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005305 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005306 // discard any pending drain or write ack by incrementing sequence
5307 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5308 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005309 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005310 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5311 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005312 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005313 mHwPaused = false;
Eric Laurent6f9534f2022-05-03 18:15:04 +02005314 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005315}
5316
Andy Hung71742ab2023-07-07 13:47:37 -07005317void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005318{
5319 ALOGV("signal playback thread");
5320 broadcast_l();
5321}
5322
Andy Hung71742ab2023-07-07 13:47:37 -07005323void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005324{
5325 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5326 invalidateTracks((audio_stream_type_t)i);
5327 }
5328}
5329
Andy Hung71742ab2023-07-07 13:47:37 -07005330void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005331{
Eric Laurent81784c32012-11-19 14:55:58 -08005332 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005333 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005334 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005335 // increase sleep time progressively when application underrun condition clears.
5336 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5337 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5338 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005339 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005340 sleepTimeShift--;
5341 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005342 mSleepTimeUs = 0;
5343 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005344 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005345
Eric Laurent81784c32012-11-19 14:55:58 -08005346}
5347
Andy Hung71742ab2023-07-07 13:47:37 -07005348void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005349{
5350 // If no tracks are ready, sleep once for the duration of an output
5351 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005352 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005353 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005354 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5355 // Using the Monopipe availableToWrite, we estimate the
5356 // sleep time to retry for more data (before we underrun).
5357 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5358 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5359 const size_t pipeFrames = monoPipe->maxFrames();
5360 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5361 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5362 const size_t framesDelay = std::min(
5363 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5364 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5365 pipeFrames, framesLeft, framesDelay);
5366 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5367 } else {
5368 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5369 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5370 mSleepTimeUs = kMinThreadSleepTimeUs;
5371 }
5372 // reduce sleep time in case of consecutive application underruns to avoid
5373 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5374 // duration we would end up writing less data than needed by the audio HAL if
5375 // the condition persists.
5376 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5377 sleepTimeShift++;
5378 }
Eric Laurent81784c32012-11-19 14:55:58 -08005379 }
5380 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005381 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005382 }
5383 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005384 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5385 // before effects processing or output.
5386 if (mMixerBufferValid) {
5387 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005388 if (mType == SPATIALIZER) {
5389 memset(mSinkBuffer, 0, mSinkBufferSize);
5390 }
Andy Hung98ef9782014-03-04 14:46:50 -08005391 } else {
5392 memset(mSinkBuffer, 0, mSinkBufferSize);
5393 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005394 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005395 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5396 "anticipated start");
5397 }
5398 // TODO add standby time extension fct of effect tail
5399}
5400
5401// prepareTracks_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07005402PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07005403 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005404{
Andy Hungc0691382018-09-12 18:01:57 -07005405 // clean up deleted track ids in AudioMixer before allocating new tracks
5406 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5407 // for each trackId, destroy it in the AudioMixer
5408 if (mAudioMixer->exists(trackId)) {
5409 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005410 }
5411 });
Andy Hungc0691382018-09-12 18:01:57 -07005412 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005413
5414 mixer_state mixerStatus = MIXER_IDLE;
5415 // find out which tracks need to be processed
5416 size_t count = mActiveTracks.size();
5417 size_t mixedTracks = 0;
5418 size_t tracksWithEffect = 0;
5419 // counts only _active_ fast tracks
5420 size_t fastTracks = 0;
5421 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5422
5423 float masterVolume = mMasterVolume;
5424 bool masterMute = mMasterMute;
5425
5426 if (masterMute) {
5427 masterVolume = 0;
5428 }
5429 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hungbd72c542023-06-20 18:56:17 -07005430 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005431 if (chain != 0) {
5432 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5433 chain->setVolume_l(&v, &v);
5434 masterVolume = (float)((v + (1 << 23)) >> 24);
5435 chain.clear();
5436 }
5437
5438 // prepare a new state to push
5439 FastMixerStateQueue *sq = NULL;
5440 FastMixerState *state = NULL;
5441 bool didModify = false;
5442 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005443 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005444 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005445 sq = mFastMixer->sq();
5446 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005447 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005448 }
5449
Andy Hung69aed5f2014-02-25 17:24:40 -08005450 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005451 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005452
Andy Hungbd3b2b02018-05-21 10:53:11 -07005453 // DeferredOperations handles statistics after setting mixerStatus.
5454 class DeferredOperations {
5455 public:
Andy Hungea840382020-05-05 21:50:17 -07005456 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5457 : mMixerStatus(mixerStatus)
5458 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005459
5460 // when leaving scope, tally frames properly.
5461 ~DeferredOperations() {
5462 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5463 // because that is when the underrun occurs.
5464 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005465 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005466 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005467 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005468 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005469 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005470 }
5471 }
Andy Hungea840382020-05-05 21:50:17 -07005472 // send the max underrun frames for this mixer period
5473 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005474 }
5475
5476 // tallyUnderrunFrames() is called to update the track counters
5477 // with the number of underrun frames for a particular mixer period.
5478 // We defer tallying until we know the final mixer status.
Andy Hung3ff4b552023-06-26 19:20:57 -07005479 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005480 mUnderrunFrames.emplace_back(track, underrunFrames);
5481 }
5482
5483 private:
5484 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005485 ThreadMetrics * const mThreadMetrics;
Andy Hung3ff4b552023-06-26 19:20:57 -07005486 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005487 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005488 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005489
jiabin245cdd92018-12-07 17:55:15 -08005490 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005491 for (size_t i=0 ; i<count ; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005492 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005493
5494 // this const just means the local variable doesn't change
Andy Hung3ff4b552023-06-26 19:20:57 -07005495 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005496
5497 // process fast tracks
5498 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005499 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5500 "%s(%d): FastTrack(%d) present without FastMixer",
5501 __func__, id(), track->id());
5502
jiabin245cdd92018-12-07 17:55:15 -08005503 if (track->getHapticPlaybackEnabled()) {
5504 noFastHapticTrack = false;
5505 }
Eric Laurent81784c32012-11-19 14:55:58 -08005506
5507 // It's theoretically possible (though unlikely) for a fast track to be created
5508 // and then removed within the same normal mix cycle. This is not a problem, as
5509 // the track never becomes active so it's fast mixer slot is never touched.
5510 // The converse, of removing an (active) track and then creating a new track
5511 // at the identical fast mixer slot within the same normal mix cycle,
5512 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung3ff4b552023-06-26 19:20:57 -07005513 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005514 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005515 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5516 FastTrack *fastTrack = &state->mFastTracks[j];
5517
5518 // Determine whether the track is currently in underrun condition,
5519 // and whether it had a recent underrun.
5520 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5521 FastTrackUnderruns underruns = ftDump->mUnderruns;
5522 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung3ff4b552023-06-26 19:20:57 -07005523 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005524 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung3ff4b552023-06-26 19:20:57 -07005525 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005526 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung3ff4b552023-06-26 19:20:57 -07005527 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005528 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung3ff4b552023-06-26 19:20:57 -07005529 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005530 // don't count underruns that occur while stopping or pausing
5531 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005532 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005533 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5534 recentUnderruns > 0) {
5535 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005536 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005537 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005538 // Immediately account for FastTrack underruns.
Andy Hung3ff4b552023-06-26 19:20:57 -07005539 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005540
5541 // This is similar to the state machine for normal tracks,
5542 // with a few modifications for fast tracks.
5543 bool isActive = true;
Andy Hung3ff4b552023-06-26 19:20:57 -07005544 switch (track->state()) {
5545 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005546 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005547 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005548 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005549 }
5550 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005551 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005552 // ramp down is not yet implemented
5553 track->setPaused();
5554 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005555 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005556 // ramp up is not yet implemented
Andy Hung3ff4b552023-06-26 19:20:57 -07005557 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005558 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005559 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005560 if (recentFull > 0 || recentPartial > 0) {
5561 // track has provided at least some frames recently: reset retry count
Andy Hung3ff4b552023-06-26 19:20:57 -07005562 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005563 }
5564 if (recentUnderruns == 0) {
5565 // no recent underruns: stay active
5566 break;
5567 }
5568 // there has recently been an underrun of some kind
5569 if (track->sharedBuffer() == 0) {
5570 // were any of the recent underruns "empty" (no frames available)?
5571 if (recentEmpty == 0) {
5572 // no, then ignore the partial underruns as they are allowed indefinitely
5573 break;
5574 }
5575 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung3ff4b552023-06-26 19:20:57 -07005576 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005577 break;
5578 }
5579 // indicate to client process that the track was disabled because of underrun;
5580 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005581 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005582 // remove from active list, but state remains ACTIVE [confusing but true]
5583 isActive = false;
5584 break;
5585 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005586 FALLTHROUGH_INTENDED;
Andy Hung3ff4b552023-06-26 19:20:57 -07005587 case IAfTrackBase::STOPPING_2:
5588 case IAfTrackBase::PAUSED:
5589 case IAfTrackBase::STOPPED:
5590 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005591 // Check for presentation complete if track is inactive
5592 // We have consumed all the buffers of this track.
5593 // This would be incomplete if we auto-paused on underrun
5594 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005595 uint32_t latency = 0;
5596 status_t result = mOutput->stream->getLatency(&latency);
5597 ALOGE_IF(result != OK,
5598 "Error when retrieving output stream latency: %d", result);
5599 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005600 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005601 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5602 // track stays in active list until presentation is complete
5603 break;
5604 }
5605 }
5606 if (track->isStopping_2()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005607 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005608 }
5609 if (track->isStopped()) {
5610 // Can't reset directly, as fast mixer is still polling this track
5611 // track->reset();
5612 // So instead mark this track as needing to be reset after push with ack
5613 resetMask |= 1 << i;
5614 }
5615 isActive = false;
5616 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005617 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005618 default:
Andy Hung3ff4b552023-06-26 19:20:57 -07005619 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005620 }
5621
5622 if (isActive) {
5623 // was it previously inactive?
5624 if (!(state->mTrackMask & (1 << j))) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005625 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5626 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005627 fastTrack->mBufferProvider = eabp;
5628 fastTrack->mVolumeProvider = vp;
Andy Hung3ff4b552023-06-26 19:20:57 -07005629 fastTrack->mChannelMask = track->channelMask();
5630 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005631 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005632 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005633 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005634 fastTrack->mGeneration++;
5635 state->mTrackMask |= 1 << j;
5636 didModify = true;
5637 // no acknowledgement required for newly active tracks
5638 }
Andy Hung3ff4b552023-06-26 19:20:57 -07005639 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005640 float volume;
5641 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5642 volume = 0.f;
5643 } else {
5644 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5645 }
5646
5647 handleVoipVolume_l(&volume);
5648
Eric Laurent81784c32012-11-19 14:55:58 -08005649 // cache the combined master volume and stream type volume for fast mixer; this
5650 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005651 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005652 proxy->framesReleased()).first;
5653 volume *= vh;
Andy Hung3ff4b552023-06-26 19:20:57 -07005654 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005655 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005656 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5657 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005658
Andy Hung2cbc2722023-07-17 17:05:00 -07005659 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005660 /*muteState=*/{masterVolume == 0.f,
5661 mStreamTypes[track->streamType()].volume == 0.f,
5662 mStreamTypes[track->streamType()].mute,
5663 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005664 vlf == 0.f && vrf == 0.f,
5665 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005666
5667 vlf *= volume;
5668 vrf *= volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005669
jiabin76d94692022-12-15 21:51:21 +00005670 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005671 ++fastTracks;
5672 } else {
5673 // was it previously active?
5674 if (state->mTrackMask & (1 << j)) {
5675 fastTrack->mBufferProvider = NULL;
5676 fastTrack->mGeneration++;
5677 state->mTrackMask &= ~(1 << j);
5678 didModify = true;
5679 // If any fast tracks were removed, we must wait for acknowledgement
5680 // because we're about to decrement the last sp<> on those tracks.
5681 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5682 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005683 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5684 // AudioTrack may start (which may not be with a start() but with a write()
5685 // after underrun) and immediately paused or released. In that case the
5686 // FastTrack state hasn't had time to update.
5687 // TODO Remove the ALOGW when this theory is confirmed.
5688 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005689 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung3ff4b552023-06-26 19:20:57 -07005690 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005691 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005692 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005693 }
5694 tracksToRemove->add(track);
5695 // Avoids a misleading display in dumpsys
Andy Hung3ff4b552023-06-26 19:20:57 -07005696 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005697 }
jiabin245cdd92018-12-07 17:55:15 -08005698 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5699 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5700 didModify = true;
5701 }
Eric Laurent81784c32012-11-19 14:55:58 -08005702 continue;
5703 }
5704
5705 { // local variable scope to avoid goto warning
5706
5707 audio_track_cblk_t* cblk = track->cblk();
5708
5709 // The first time a track is added we wait
5710 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005711 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005712
5713 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005714 // use the trackId as the AudioMixer name.
5715 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005716 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005717 trackId,
Andy Hung3ff4b552023-06-26 19:20:57 -07005718 track->channelMask(),
5719 track->format(),
5720 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005721 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005722 ALOGW("%s(): AudioMixer cannot create track(%d)"
5723 " mask %#x, format %#x, sessionId %d",
5724 __func__, trackId,
Andy Hung3ff4b552023-06-26 19:20:57 -07005725 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005726 tracksToRemove->add(track);
5727 track->invalidate(); // consider it dead.
5728 continue;
5729 }
5730 }
5731
Eric Laurent81784c32012-11-19 14:55:58 -08005732 // make sure that we have enough frames to mix one full buffer.
5733 // enforce this condition only once to enable draining the buffer in case the client
5734 // app does not call stop() and relies on underrun to stop:
5735 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5736 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005737 size_t desiredFrames;
Andy Hung3ff4b552023-06-26 19:20:57 -07005738 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5739 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005740
5741 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005742 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005743 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5744 // add frames already consumed but not yet released by the resampler
5745 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005746 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005747
Eric Laurent81784c32012-11-19 14:55:58 -08005748 uint32_t minFrames = 1;
5749 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5750 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005751 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005752 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005753
5754 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005755 if (ATRACE_ENABLED()) {
5756 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005757 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005758 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005759 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005760 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005761 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005762 !track->isPaused() && !track->isTerminated())
5763 {
Andy Hungc0691382018-09-12 18:01:57 -07005764 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005765
5766 mixedTracks++;
5767
Andy Hung69aed5f2014-02-25 17:24:40 -08005768 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5769 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005770 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005771 if (track->mainBuffer() != mSinkBuffer &&
5772 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005773 if (mEffectBufferEnabled) {
5774 mEffectBufferValid = true; // Later can set directly.
5775 }
Eric Laurent81784c32012-11-19 14:55:58 -08005776 chain = getEffectChain_l(track->sessionId());
5777 // Delegate volume control to effect in track effect chain if needed
5778 if (chain != 0) {
5779 tracksWithEffect++;
5780 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005781 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005782 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005783 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005784 }
5785 }
5786
5787
5788 int param = AudioMixer::VOLUME;
Andy Hung3ff4b552023-06-26 19:20:57 -07005789 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005790 // no ramp for the first volume setting
Andy Hung3ff4b552023-06-26 19:20:57 -07005791 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5792 if (track->state() == IAfTrackBase::RESUMING) {
5793 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005794 // If a new track is paused immediately after start, do not ramp on resume.
5795 if (cblk->mServer != 0) {
5796 param = AudioMixer::RAMP_VOLUME;
5797 }
Eric Laurent81784c32012-11-19 14:55:58 -08005798 }
Andy Hungc0691382018-09-12 18:01:57 -07005799 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005800 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005801 // FIXME should not make a decision based on mServer
5802 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005803 // If the track is stopped before the first frame was mixed,
5804 // do not apply ramp
5805 param = AudioMixer::RAMP_VOLUME;
5806 }
5807
5808 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005809 uint32_t vl, vr; // in U8.24 integer format
5810 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005811 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005812 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005813 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung3ff4b552023-06-26 19:20:57 -07005814 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005815 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung3ff4b552023-06-26 19:20:57 -07005816 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005817
Eric Laurenteab90452019-06-24 15:17:46 -07005818 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5819 v = 0;
5820 }
5821
5822 handleVoipVolume_l(&v);
5823
5824 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005825 vl = vr = 0;
5826 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005827 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005828 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005829 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005830 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5831 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005832 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005833 if (vlf > GAIN_FLOAT_UNITY) {
5834 ALOGV("Track left volume out of range: %.3g", vlf);
5835 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005836 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005837 if (vrf > GAIN_FLOAT_UNITY) {
5838 ALOGV("Track right volume out of range: %.3g", vrf);
5839 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005840 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005841
Andy Hung2cbc2722023-07-17 17:05:00 -07005842 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005843 /*muteState=*/{masterVolume == 0.f,
5844 mStreamTypes[track->streamType()].volume == 0.f,
5845 mStreamTypes[track->streamType()].mute,
5846 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005847 vlf == 0.f && vrf == 0.f,
5848 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005849
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005850 // now apply the master volume and stream type volume and shaper volume
5851 vlf *= v * vh;
5852 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005853 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005854 // then derive vl and vr as U8.24 versions for the effect chain
5855 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5856 vl = (uint32_t) (scaleto8_24 * vlf);
5857 vr = (uint32_t) (scaleto8_24 * vrf);
5858 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005859 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005860 // send level comes from shared memory and so may be corrupt
5861 if (sendLevel > MAX_GAIN_INT) {
5862 ALOGV("Track send level out of range: %04X", sendLevel);
5863 sendLevel = MAX_GAIN_INT;
5864 }
Andy Hung6be49402014-05-30 10:42:03 -07005865 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5866 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005867 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005868
jiabin76d94692022-12-15 21:51:21 +00005869 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005870
Eric Laurent81784c32012-11-19 14:55:58 -08005871 // Delegate volume control to effect in track effect chain if needed
5872 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5873 // Do not ramp volume if volume is controlled by effect
5874 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005875 // Update remaining floating point volume levels
5876 vlf = (float)vl / (1 << 24);
5877 vrf = (float)vr / (1 << 24);
Andy Hung3ff4b552023-06-26 19:20:57 -07005878 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005879 } else {
5880 // force no volume ramp when volume controller was just disabled or removed
5881 // from effect chain to avoid volume spike
Andy Hung3ff4b552023-06-26 19:20:57 -07005882 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005883 param = AudioMixer::VOLUME;
5884 }
Andy Hung3ff4b552023-06-26 19:20:57 -07005885 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005886 }
5887
Eric Laurent81784c32012-11-19 14:55:58 -08005888 // XXX: these things DON'T need to be done each time
Andy Hung3ff4b552023-06-26 19:20:57 -07005889 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005890 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005891
Andy Hungc0691382018-09-12 18:01:57 -07005892 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5893 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5894 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005895 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005896 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005897 AudioMixer::TRACK,
5898 AudioMixer::FORMAT, (void *)track->format());
5899 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005900 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005901 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005902 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005903
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005904 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005905 mAudioMixer->setParameter(
5906 trackId,
5907 AudioMixer::TRACK,
5908 AudioMixer::MIXER_CHANNEL_MASK,
5909 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5910 } else {
5911 mAudioMixer->setParameter(
5912 trackId,
5913 AudioMixer::TRACK,
5914 AudioMixer::MIXER_CHANNEL_MASK,
5915 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5916 }
5917
Glenn Kastene3aa6592012-12-04 12:22:46 -08005918 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005919 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005920 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005921 if (reqSampleRate == 0) {
5922 reqSampleRate = mSampleRate;
5923 } else if (reqSampleRate > maxSampleRate) {
5924 reqSampleRate = maxSampleRate;
5925 }
Eric Laurent81784c32012-11-19 14:55:58 -08005926 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005927 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005928 AudioMixer::RESAMPLE,
5929 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005930 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005931
Andy Hung8edb8dc2015-03-26 19:13:55 -07005932 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005933 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005934 AudioMixer::TIMESTRETCH,
5935 AudioMixer::PLAYBACK_RATE,
Andy Hung71ba4b32022-10-06 12:09:49 -07005936 // cast away constness for this generic API.
5937 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005938
Andy Hung69aed5f2014-02-25 17:24:40 -08005939 /*
5940 * Select the appropriate output buffer for the track.
5941 *
Andy Hung98ef9782014-03-04 14:46:50 -08005942 * Tracks with effects go into their own effects chain buffer
5943 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005944 *
5945 * Other tracks can use mMixerBuffer for higher precision
5946 * channel accumulation. If this buffer is enabled
5947 * (mMixerBufferEnabled true), then selected tracks will accumulate
5948 * into it.
5949 *
5950 */
5951 if (mMixerBufferEnabled
5952 && (track->mainBuffer() == mSinkBuffer
5953 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005954 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005955 mAudioMixer->setParameter(
5956 trackId,
5957 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005958 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005959 mAudioMixer->setParameter(
5960 trackId,
5961 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005962 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005963 } else {
5964 mAudioMixer->setParameter(
5965 trackId,
5966 AudioMixer::TRACK,
5967 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5968 mAudioMixer->setParameter(
5969 trackId,
5970 AudioMixer::TRACK,
5971 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5972 // TODO: override track->mainBuffer()?
5973 mMixerBufferValid = true;
5974 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005975 } else {
5976 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005977 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005978 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07005979 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005980 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005981 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005982 AudioMixer::TRACK,
5983 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5984 }
Eric Laurent81784c32012-11-19 14:55:58 -08005985 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005986 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005987 AudioMixer::TRACK,
5988 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005989 mAudioMixer->setParameter(
5990 trackId,
5991 AudioMixer::TRACK,
5992 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005993 mAudioMixer->setParameter(
5994 trackId,
5995 AudioMixer::TRACK,
5996 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung3ff4b552023-06-26 19:20:57 -07005997 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005998 mAudioMixer->setParameter(
5999 trackId,
6000 AudioMixer::TRACK,
Andy Hung3ff4b552023-06-26 19:20:57 -07006001 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006002
6003 // reset retry count
Andy Hung3ff4b552023-06-26 19:20:57 -07006004 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006005
6006 // If one track is ready, set the mixer ready if:
6007 // - the mixer was not ready during previous round OR
6008 // - no other track is not ready
6009 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6010 mixerStatus != MIXER_TRACKS_ENABLED) {
6011 mixerStatus = MIXER_TRACKS_READY;
6012 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006013
6014 // Enable the next few lines to instrument a test for underrun log handling.
6015 // TODO: Remove when we have a better way of testing the underrun log.
6016#if 0
6017 static int i;
6018 if ((++i & 0xf) == 0) {
6019 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6020 }
6021#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006022 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006023 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006024 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006025 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6026 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006027 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006028 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006029 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006030
Eric Laurent81784c32012-11-19 14:55:58 -08006031 // clear effect chain input buffer if an active track underruns to avoid sending
6032 // previous audio buffer again to effects
6033 chain = getEffectChain_l(track->sessionId());
6034 if (chain != 0) {
6035 chain->clearInputBuffer();
6036 }
6037
Andy Hungc0691382018-09-12 18:01:57 -07006038 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006039 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6040 track->isStopped() || track->isPaused()) {
6041 // We have consumed all the buffers of this track.
6042 // Remove it from the list of active tracks.
6043 // TODO: use actual buffer filling status instead of latency when available from
6044 // audio HAL
6045 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006046 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006047 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6048 if (track->isStopped()) {
6049 track->reset();
6050 }
6051 tracksToRemove->add(track);
6052 }
6053 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006054 // No buffers for this track. Give it a few chances to
6055 // fill a buffer, then remove it from active list.
Andy Hung3ff4b552023-06-26 19:20:57 -07006056 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07006057 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
6058 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006059 tracksToRemove->add(track);
6060 // indicate to client process that the track was disabled because of underrun;
6061 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006062 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006063 // If one track is not ready, mark the mixer also not ready if:
6064 // - the mixer was ready during previous round OR
6065 // - no other track is ready
6066 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6067 mixerStatus != MIXER_TRACKS_READY) {
6068 mixerStatus = MIXER_TRACKS_ENABLED;
6069 }
6070 }
Andy Hungc0691382018-09-12 18:01:57 -07006071 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006072 }
6073
6074 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006075
6076 }
6077
jiabin245cdd92018-12-07 17:55:15 -08006078 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6079 // When there is no fast track playing haptic and FastMixer exists,
6080 // enabling the first FastTrack, which provides mixed data from normal
6081 // tracks, to play haptic data.
6082 FastTrack *fastTrack = &state->mFastTracks[0];
6083 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6084 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6085 didModify = true;
6086 }
6087 }
6088
Eric Laurent81784c32012-11-19 14:55:58 -08006089 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006090 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006091 if (didModify) {
6092 state->mFastTracksGen++;
6093 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6094 if (kUseFastMixer == FastMixer_Dynamic &&
6095 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6096 state->mCommand = FastMixerState::COLD_IDLE;
6097 state->mColdFutexAddr = &mFastMixerFutex;
6098 state->mColdGen++;
6099 mFastMixerFutex = 0;
6100 if (kUseFastMixer == FastMixer_Dynamic) {
6101 mNormalSink = mOutputSink;
6102 }
6103 // If we go into cold idle, need to wait for acknowledgement
6104 // so that fast mixer stops doing I/O.
6105 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6106 pauseAudioWatchdog = true;
6107 }
Eric Laurent81784c32012-11-19 14:55:58 -08006108 }
6109 if (sq != NULL) {
6110 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006111 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6112 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6113 // when bringing the output sink into standby.)
6114 //
6115 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6116 //
6117 // This occurs with BT suspend when we idle the FastMixer with
6118 // active tracks, which may be added or removed.
6119 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006120 }
6121#ifdef AUDIO_WATCHDOG
6122 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6123 mAudioWatchdog->pause();
6124 }
6125#endif
6126
6127 // Now perform the deferred reset on fast tracks that have stopped
6128 while (resetMask != 0) {
6129 size_t i = __builtin_ctz(resetMask);
6130 ALOG_ASSERT(i < count);
6131 resetMask &= ~(1 << i);
Andy Hung3ff4b552023-06-26 19:20:57 -07006132 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006133 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6134 track->reset();
6135 }
6136
Andy Hung80d03d22018-04-10 10:32:11 -07006137 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6138 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6139 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6140 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6141 // See also the implementation of destroyTrack_l().
6142 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006143 const int trackId = track->id();
6144 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6145 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006146 }
6147 }
6148
Eric Laurent81784c32012-11-19 14:55:58 -08006149 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006150 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006151
Eric Laurentb3f315a2021-07-13 15:09:05 +02006152 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6153 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006154 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006155 }
6156
6157 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006158 // as long as there are effects we should clear the effects buffer, to avoid
6159 // passing a non-clean buffer to the effect chain
6160 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006161 if (mType == SPATIALIZER) {
6162 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6163 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006164 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006165 // sink or mix buffer must be cleared if all tracks are connected to an
6166 // effect chain as in this case the mixer will not write to the sink or mix buffer
6167 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006168 // always clear sink buffer for spatializer output as the output of the spatializer
6169 // effect will be accumulated into it
6170 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6171 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006172 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006173 if (mMixerBufferValid) {
6174 memset(mMixerBuffer, 0, mMixerBufferSize);
6175 // TODO: In testing, mSinkBuffer below need not be cleared because
6176 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6177 // after mixing.
6178 //
6179 // To enforce this guarantee:
6180 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6181 // (mixedTracks == 0 && fastTracks > 0))
6182 // must imply MIXER_TRACKS_READY.
6183 // Later, we may clear buffers regardless, and skip much of this logic.
6184 }
Andy Hung98ef9782014-03-04 14:46:50 -08006185 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006186 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006187 }
6188
6189 // if any fast tracks, then status is ready
6190 mMixerStatusIgnoringFastTracks = mixerStatus;
6191 if (fastTracks > 0) {
6192 mixerStatus = MIXER_TRACKS_READY;
6193 }
6194 return mixerStatus;
6195}
6196
Eric Laurentad7dd962016-09-22 12:38:37 -07006197// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006198uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006199{
6200 uint32_t trackCount = 0;
6201 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006202 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006203 trackCount++;
6204 }
6205 }
6206 return trackCount;
6207}
6208
Andy Hung71742ab2023-07-07 13:47:37 -07006209bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006210{
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006211 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6212 // could falsely detect that the frame position has stalled due to underrun because we haven't
6213 // given the Audio HAL enough time to update.
6214 const nsecs_t nowNs = systemTime();
6215 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6216 return mLatchedValue;
6217 }
6218 mPreviousNs = nowNs;
6219 mLatchedValue = false;
6220 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006221 uint64_t position = 0;
6222 struct timespec unused;
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006223 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006224 if (ret == NO_ERROR) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006225 if (position != mPreviousPosition) {
6226 mPreviousPosition = position;
6227 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006228 }
6229 }
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006230 return mLatchedValue;
6231}
6232
Andy Hung71742ab2023-07-07 13:47:37 -07006233void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006234{
6235 mLatchedValue = true;
6236 mPreviousPosition = 0;
6237 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006238}
6239
Andy Hung1bc088a2018-02-09 15:57:31 -08006240// isTrackAllowed_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006241bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006242 audio_channel_mask_t channelMask, audio_format_t format,
6243 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006244{
Andy Hung1bc088a2018-02-09 15:57:31 -08006245 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6246 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006247 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006248 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006249 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006250 ALOGW("%s: invalid format: %#x", __func__, format);
6251 return false;
6252 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006253 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006254 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6255 return false;
6256 }
6257 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006258}
6259
Eric Laurent10351942014-05-08 18:49:52 -07006260// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006261bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006262 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006263{
Eric Laurent81784c32012-11-19 14:55:58 -08006264 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006265 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006266
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006267 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006268
Eric Laurent10351942014-05-08 18:49:52 -07006269 AudioParameter param = AudioParameter(keyValuePair);
6270 int value;
6271 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6272 reconfig = true;
6273 }
6274 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hungf8ab4692023-07-20 21:44:14 -07006275 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006276 status = BAD_VALUE;
6277 } else {
6278 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006279 reconfig = true;
6280 }
Eric Laurent10351942014-05-08 18:49:52 -07006281 }
6282 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hungf8ab4692023-07-20 21:44:14 -07006283 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006284 status = BAD_VALUE;
6285 } else {
6286 // no need to save value, since it's constant
6287 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006288 }
Eric Laurent10351942014-05-08 18:49:52 -07006289 }
6290 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6291 // do not accept frame count changes if tracks are open as the track buffer
6292 // size depends on frame count and correct behavior would not be guaranteed
6293 // if frame count is changed after track creation
6294 if (!mTracks.isEmpty()) {
6295 status = INVALID_OPERATION;
6296 } else {
6297 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006298 }
Eric Laurent10351942014-05-08 18:49:52 -07006299 }
6300 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006301 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006302 }
Eric Laurent81784c32012-11-19 14:55:58 -08006303
Eric Laurent10351942014-05-08 18:49:52 -07006304 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006305 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006306 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungb72a5502023-03-27 15:53:06 -07006307 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6308 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006309 mOutput->standby();
Andy Hungb72a5502023-03-27 15:53:06 -07006310 mThreadMetrics.logEndInterval();
6311 mThreadSnapshot.onEnd();
Andy Hungdda7aed2023-03-27 15:53:06 -07006312 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006313 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006314 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006315 }
Eric Laurent10351942014-05-08 18:49:52 -07006316 if (status == NO_ERROR && reconfig) {
6317 readOutputParameters_l();
6318 delete mAudioMixer;
6319 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006320 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006321 const int trackId = track->id();
Andy Hung71ba4b32022-10-06 12:09:49 -07006322 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006323 trackId,
Andy Hung3ff4b552023-06-26 19:20:57 -07006324 track->channelMask(),
6325 track->format(),
6326 track->sessionId());
Andy Hung71ba4b32022-10-06 12:09:49 -07006327 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006328 "%s(): AudioMixer cannot create track(%d)"
6329 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006330 __func__,
Andy Hung3ff4b552023-06-26 19:20:57 -07006331 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006332 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006333 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006334 }
Eric Laurent81784c32012-11-19 14:55:58 -08006335 }
6336
Dean Wheatley68918102021-03-19 22:09:19 +11006337 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006338}
6339
6340
Andy Hung71742ab2023-07-07 13:47:37 -07006341void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006342{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006343 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006344 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006345 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006346 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006347 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6348 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6349 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006350 if (hasFastMixer()) {
6351 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6352
6353 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6354 // while we are dumping it. It may be inconsistent, but it won't mutate!
6355 // This is a large object so we place it on the heap.
6356 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006357 const std::unique_ptr<FastMixerDumpState> copy =
6358 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006359 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006360
6361#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006362 // Similar for state queue
6363 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6364 observerCopy.dump(fd);
6365 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6366 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006367#endif
6368
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006369#ifdef AUDIO_WATCHDOG
6370 if (mAudioWatchdog != 0) {
6371 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6372 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6373 wdCopy.dump(fd);
6374 }
6375#endif
6376
6377 } else {
6378 dprintf(fd, " No FastMixer\n");
6379 }
Eric Laurent90cea102023-05-15 15:08:27 +02006380
6381 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6382 mBluetoothLatencyModesEnabled ? "" : "not ");
6383 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6384 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6385 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006386}
6387
Andy Hung71742ab2023-07-07 13:47:37 -07006388uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006389{
6390 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6391}
6392
Andy Hung71742ab2023-07-07 13:47:37 -07006393uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006394{
6395 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6396}
6397
Andy Hung71742ab2023-07-07 13:47:37 -07006398void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006399{
6400 PlaybackThread::cacheParameters_l();
6401
6402 // FIXME: Relaxed timing because of a certain device that can't meet latency
6403 // Should be reduced to 2x after the vendor fixes the driver issue
6404 // increase threshold again due to low power audio mode. The way this warning
6405 // threshold is calculated and its usefulness should be reconsidered anyway.
6406 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6407}
6408
Andy Hung71742ab2023-07-07 13:47:37 -07006409void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung2cbc2722023-07-17 17:05:00 -07006410 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006411}
6412
Andy Hung71742ab2023-07-07 13:47:37 -07006413void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006414 // Only handle latency mode if:
6415 // - mBluetoothLatencyModesEnabled is true
6416 // - the HAL supports latency modes
6417 // - the selected device is Bluetooth LE or A2DP
6418 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6419 return;
6420 }
6421 if (mOutDeviceTypeAddrs.size() != 1
6422 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6423 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6424 return;
6425 }
6426
6427 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6428 if (mSupportedLatencyModes.size() == 1) {
6429 // If the HAL only support one latency mode currently, confirm the choice
6430 latencyMode = mSupportedLatencyModes[0];
6431 } else if (mSupportedLatencyModes.size() > 1) {
6432 // Request low latency if:
6433 // - At least one active track is either:
6434 // - a fast track with gaming usage or
6435 // - a track with acessibility usage
6436 for (const auto& track : mActiveTracks) {
6437 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6438 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6439 latencyMode = AUDIO_LATENCY_MODE_LOW;
6440 break;
6441 }
6442 }
6443 }
6444
6445 if (latencyMode != mSetLatencyMode) {
6446 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6447 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6448 __func__, mId, toString(latencyMode).c_str(), status);
6449 if (status == NO_ERROR) {
6450 mSetLatencyMode = latencyMode;
6451 }
6452 }
6453}
6454
Andy Hung71742ab2023-07-07 13:47:37 -07006455void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006456
6457 if (mOutput == nullptr || mOutput->stream == nullptr) {
6458 return;
6459 }
6460 std::vector<audio_latency_mode_t> latencyModes;
6461 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6462 if (status != NO_ERROR) {
6463 latencyModes.clear();
6464 }
6465 if (latencyModes != mSupportedLatencyModes) {
6466 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6467 __func__, mId, status, toString(latencyModes).c_str());
6468 mSupportedLatencyModes.swap(latencyModes);
6469 sendHalLatencyModesChangedEvent_l();
6470 }
6471}
6472
Andy Hung71742ab2023-07-07 13:47:37 -07006473status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006474 std::vector<audio_latency_mode_t>* modes) {
6475 if (modes == nullptr) {
6476 return BAD_VALUE;
6477 }
6478 Mutex::Autolock _l(mLock);
6479 *modes = mSupportedLatencyModes;
6480 return NO_ERROR;
6481}
6482
Andy Hung71742ab2023-07-07 13:47:37 -07006483void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006484 std::vector<audio_latency_mode_t> modes) {
6485 Mutex::Autolock _l(mLock);
6486 if (modes != mSupportedLatencyModes) {
6487 ALOGD("%s: thread(%d) supported latency modes: %s",
6488 __func__, mId, toString(modes).c_str());
6489 mSupportedLatencyModes.swap(modes);
6490 sendHalLatencyModesChangedEvent_l();
6491 }
6492}
6493
Andy Hung71742ab2023-07-07 13:47:37 -07006494status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006495 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6496 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6497 return INVALID_OPERATION;
6498 }
6499 mBluetoothLatencyModesEnabled.store(enabled);
6500 return NO_ERROR;
6501}
6502
Eric Laurent81784c32012-11-19 14:55:58 -08006503// ----------------------------------------------------------------------------
6504
Andy Hung71742ab2023-07-07 13:47:37 -07006505/* static */
6506sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07006507 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07006508 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6509 const audio_offload_info_t& offloadInfo) {
6510 return sp<DirectOutputThread>::make(
Andy Hung2cbc2722023-07-17 17:05:00 -07006511 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung71742ab2023-07-07 13:47:37 -07006512}
6513
Andy Hung2cbc2722023-07-17 17:05:00 -07006514DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fenn56576722022-10-05 13:42:36 -07006515 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6516 const audio_offload_info_t& offloadInfo)
Andy Hung2cbc2722023-07-17 17:05:00 -07006517 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fenn56576722022-10-05 13:42:36 -07006518 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006519{
Andy Hung2cbc2722023-07-17 17:05:00 -07006520 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006521}
6522
Andy Hung71742ab2023-07-07 13:47:37 -07006523DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006524{
6525}
6526
Andy Hung71742ab2023-07-07 13:47:37 -07006527void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006528{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006529 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006530 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6531 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6532}
6533
Andy Hung71742ab2023-07-07 13:47:37 -07006534void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006535{
6536 Mutex::Autolock _l(mLock);
6537 if (mMasterBalance != balance) {
6538 mMasterBalance.store(balance);
6539 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6540 broadcast_l();
6541 }
6542}
6543
Andy Hung71742ab2023-07-07 13:47:37 -07006544void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006545{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006546 float left, right;
6547
Andy Hung333ab962019-05-28 20:23:35 -07006548 // Ensure volumeshaper state always advances even when muted.
Andy Hung3ff4b552023-06-26 19:20:57 -07006549 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hungee86cee2022-12-13 19:19:53 -08006550
Andy Hungee86cee2022-12-13 19:19:53 -08006551 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6552 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6553
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006554 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6555 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hungee86cee2022-12-13 19:19:53 -08006556
6557 const int64_t volumeShaperFrames =
6558 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6559 const auto [shaperVolume, shaperActive] =
6560 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006561 mVolumeShaperActive = shaperActive;
6562
Vlad Popae2f5aef2022-07-25 16:00:20 +02006563 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6564 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6565 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6566
6567 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6568
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006569 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006570 left = right = 0;
6571 } else {
6572 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006573 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006574
Glenn Kastenc56f3422014-03-21 17:53:17 -07006575 if (left > GAIN_FLOAT_UNITY) {
6576 left = GAIN_FLOAT_UNITY;
6577 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006578 if (right > GAIN_FLOAT_UNITY) {
6579 right = GAIN_FLOAT_UNITY;
6580 }
zhangjincheng73e73872023-01-16 17:17:38 +08006581 left *= v;
6582 right *= v;
Andy Hung2cbc2722023-07-17 17:05:00 -07006583 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng73e73872023-01-16 17:17:38 +08006584 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6585 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6586 right *= mMasterBalanceRight;
6587 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006588 }
6589
Andy Hung2cbc2722023-07-17 17:05:00 -07006590 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006591 /*muteState=*/{mMasterMute,
6592 mStreamTypes[track->streamType()].volume == 0.f,
6593 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006594 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006595 clientVolumeMute,
6596 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006597
Eric Laurentbfb1b832013-01-07 09:53:42 -08006598 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006599 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006600 if (left != mLeftVolFloat || right != mRightVolFloat) {
6601 mLeftVolFloat = left;
6602 mRightVolFloat = right;
6603
Eric Laurentbfb1b832013-01-07 09:53:42 -08006604 // Delegate volume control to effect in track effect chain if needed
6605 // only one effect chain can be present on DirectOutputThread, so if
6606 // there is one, the track is connected to it
6607 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006608 // if effect chain exists, volume is handled by it.
6609 // Convert volumes from float to 8.24
6610 uint32_t vl = (uint32_t)(left * (1 << 24));
6611 uint32_t vr = (uint32_t)(right * (1 << 24));
6612 // Direct/Offload effect chains set output volume in setVolume_l().
6613 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6614 } else {
6615 // otherwise we directly set the volume.
6616 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006617 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006618 }
6619 }
6620}
6621
Andy Hung71742ab2023-07-07 13:47:37 -07006622void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006623{
Andy Hung3ff4b552023-06-26 19:20:57 -07006624 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6625 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006626
Eric Laurent0f0631e2015-07-06 18:01:25 -07006627 if (previousTrack != 0 && latestTrack != 0) {
6628 if (mType == DIRECT) {
6629 if (previousTrack.get() != latestTrack.get()) {
6630 mFlushPending = true;
6631 }
6632 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006633 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6634 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006635 mFlushPending = true;
6636 }
6637 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006638 } else if (previousTrack == 0) {
6639 // there could be an old track added back during track transition for direct
6640 // output, so always issues flush to flush data of the previous track if it
6641 // was already destroyed with HAL paused, then flush can resume the playback
6642 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006643 }
6644 PlaybackThread::onAddNewTrack_l();
6645}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006646
Andy Hung71742ab2023-07-07 13:47:37 -07006647PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07006648 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006649)
6650{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006651 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006652 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006653 bool doHwPause = false;
6654 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006655
6656 // find out which tracks need to be processed
Andy Hung3ff4b552023-06-26 19:20:57 -07006657 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006658 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006659 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006660 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006661 continue;
6662 }
6663
Andy Hung3ff4b552023-06-26 19:20:57 -07006664 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006665#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006666 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006667#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006668 // Only consider last track started for volume and mixer state control.
6669 // In theory an older track could underrun and restart after the new one starts
6670 // but as we only care about the transition phase between two tracks on a
6671 // direct output, it is not a problem to ignore the underrun case.
Andy Hung3ff4b552023-06-26 19:20:57 -07006672 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006673 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006674
Kuowei Li23666472021-01-20 10:23:25 +08006675 if (track->isPausePending()) {
6676 track->pauseAck();
6677 // It is possible a track might have been flushed or stopped.
6678 // Other operations such as flush pending might occur on the next prepare.
6679 if (track->isPausing()) {
6680 track->setPaused();
6681 }
6682 // Always perform pause, as an immediate flush will change
6683 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006684 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006685 doHwPause = true;
6686 mHwPaused = true;
6687 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006688 } else if (track->isFlushPending()) {
6689 track->flushAck();
6690 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006691 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006692 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006693 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006694 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006695 if (last) {
6696 mLeftVolFloat = mRightVolFloat = -1.0;
6697 if (mHwPaused) {
6698 doHwResume = true;
6699 mHwPaused = false;
6700 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006701 }
6702 }
6703
Eric Laurent81784c32012-11-19 14:55:58 -08006704 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006705 // for all its buffers to be filled before processing it.
6706 // Allow draining the buffer in case the client
6707 // app does not call stop() and relies on underrun to stop:
Andy Hung3ff4b552023-06-26 19:20:57 -07006708 // hence the test on (track->retryCount() > 1).
6709 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006710 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6711 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006712 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006713
6714 // target retry count that we will use is based on the time we wait for retries.
6715 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6716 // the retry threshold is when we accept any size for PCM data. This is slightly
6717 // smaller than the retry count so we can push small bits of data without a glitch.
6718 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006719 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006720 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung3ff4b552023-06-26 19:20:57 -07006721 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006722 minFrames = mNormalFrameCount;
6723 } else {
6724 minFrames = 1;
6725 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006726
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006727 const size_t framesReady = track->framesReady();
6728 const int trackId = track->id();
6729 if (ATRACE_ENABLED()) {
6730 std::string traceName("nRdy");
6731 traceName += std::to_string(trackId);
6732 ATRACE_INT(traceName.c_str(), framesReady);
6733 }
6734 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006735 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006736 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006737 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006738
Andy Hung3ff4b552023-06-26 19:20:57 -07006739 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6740 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006741 if (last) {
6742 // make sure processVolume_l() will apply new volume even if 0
6743 mLeftVolFloat = mRightVolFloat = -1.0;
6744 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006745 if (!mHwSupportsPause) {
6746 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006747 }
6748 }
6749
6750 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006751 processVolume_l(track, last);
6752 if (last) {
Andy Hung3ff4b552023-06-26 19:20:57 -07006753 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006754 if (previousTrack != 0) {
6755 if (track != previousTrack.get()) {
6756 // Flush any data still being written from last track
6757 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006758 // Invalidate previous track to force a seek when resuming.
6759 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006760 }
6761 }
6762 mPreviousTrack = track;
6763
Eric Laurentd595b7c2013-04-03 17:27:56 -07006764 // reset retry count
Andy Hung3ff4b552023-06-26 19:20:57 -07006765 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006766 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006767 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006768 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006769 doHwResume = true;
6770 mHwPaused = false;
6771 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006772 }
Eric Laurent81784c32012-11-19 14:55:58 -08006773 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006774 // clear effect chain input buffer if the last active track started underruns
6775 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006776 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006777 mEffectChains[0]->clearInputBuffer();
6778 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006779 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07006780 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006781 if (last && mHwPaused) {
6782 doHwResume = true;
6783 mHwPaused = false;
6784 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006785 }
6786 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6787 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006788 // We have consumed all the buffers of this track.
6789 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006790 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006791 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006792 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006793 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006794 if (presComplete) {
6795 mOutput->presentationComplete();
6796 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006797 if (track->isStopping_2()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07006798 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006799 }
Eric Laurent81784c32012-11-19 14:55:58 -08006800 if (track->isStopped()) {
6801 track->reset();
6802 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006803 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006804 }
6805 } else {
6806 // No buffers for this track. Give it a few chances to
6807 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006808 // Only consider last track started for mixer state control
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006809 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07006810 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung3ff4b552023-06-26 19:20:57 -07006811 && --(track->retryCount()) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006812 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung3ff4b552023-06-26 19:20:57 -07006813 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006814 } else {
6815 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6816 tracksToRemove->add(track);
6817 // indicate to client process that the track was disabled because of
6818 // underrun; it will then automatically call start() when data is available
6819 track->disable();
6820 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6821 // unlike mixerthread, HAL can be paused for direct output
6822 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6823 "minFrames = %u, mFormat = %#x",
6824 framesReady, minFrames, mFormat);
6825 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6826 doHwPause = true;
6827 mHwPaused = true;
6828 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006829 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006830 } else if (last) {
6831 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006832 }
6833 }
6834 }
6835 }
6836
Eric Laurentd1f69b02014-12-15 14:33:13 -08006837 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006838 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006839 for (size_t i = 0; i < mTracks.size(); i++) {
6840 if (mTracks[i]->isFlushPending()) {
6841 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006842 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006843 }
6844 }
6845 }
6846
6847 // make sure the pause/flush/resume sequence is executed in the right order.
6848 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6849 // before flush and then resume HW. This can happen in case of pause/flush/resume
6850 // if resume is received before pause is executed.
6851 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006852 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006853 status_t result = mOutput->stream->pause();
6854 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006855 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006856 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006857 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006858 flushHw_l();
6859 }
6860 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006861 status_t result = mOutput->stream->resume();
6862 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006863 }
Eric Laurent81784c32012-11-19 14:55:58 -08006864 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006865 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006866
6867 return mixerStatus;
6868}
6869
Andy Hung71742ab2023-07-07 13:47:37 -07006870void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006871{
Eric Laurent81784c32012-11-19 14:55:58 -08006872 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006873 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006874 // output audio to hardware
6875 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006876 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006877 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006878 status_t status = mActiveTrack->getNextBuffer(&buffer);
6879 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006880 // no need to pad with 0 for compressed audio
6881 if (audio_has_proportional_frames(mFormat)) {
6882 memset(curBuf, 0, frameCount * mFrameSize);
6883 }
Eric Laurent81784c32012-11-19 14:55:58 -08006884 break;
6885 }
6886 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6887 frameCount -= buffer.frameCount;
6888 curBuf += buffer.frameCount * mFrameSize;
6889 mActiveTrack->releaseBuffer(&buffer);
6890 }
Andy Hung2098f272014-02-27 14:00:06 -08006891 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006892 mSleepTimeUs = 0;
6893 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006894 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006895}
6896
Andy Hung71742ab2023-07-07 13:47:37 -07006897void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006898{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006899 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006900 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006901 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006902 return;
6903 }
Andy Hung85ba3332021-04-27 17:40:26 -07006904 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6905 mSleepTimeUs = mActiveSleepTimeUs;
6906 } else {
6907 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006908 }
Andy Hung85ba3332021-04-27 17:40:26 -07006909 // Note: In S or later, we do not write zeroes for
6910 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006911}
6912
Andy Hung71742ab2023-07-07 13:47:37 -07006913void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006914{
6915 {
6916 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006917 for (size_t i = 0; i < mTracks.size(); i++) {
6918 if (mTracks[i]->isFlushPending()) {
6919 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006920 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006921 }
6922 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006923 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006924 flushHw_l();
6925 }
6926 }
6927 PlaybackThread::threadLoop_exit();
6928}
6929
6930// must be called with thread mutex locked
Andy Hung71742ab2023-07-07 13:47:37 -07006931bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006932{
6933 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006934 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006935
6936 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6937 // after a timeout and we will enter standby then.
6938 if (mTracks.size() > 0) {
6939 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006940 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung3ff4b552023-06-26 19:20:57 -07006941 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006942 }
6943
Eric Laurent5cff4032015-05-26 13:49:58 -07006944 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006945}
6946
Eric Laurent10351942014-05-08 18:49:52 -07006947// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07006948bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006949 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006950{
6951 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006952 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006953
Eric Laurent10351942014-05-08 18:49:52 -07006954 AudioParameter param = AudioParameter(keyValuePair);
6955 int value;
6956 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006957 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006958 }
Eric Laurent10351942014-05-08 18:49:52 -07006959 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6960 // do not accept frame count changes if tracks are open as the track buffer
6961 // size depends on frame count and correct behavior would not be garantied
6962 // if frame count is changed after track creation
6963 if (!mTracks.isEmpty()) {
6964 status = INVALID_OPERATION;
6965 } else {
6966 reconfig = true;
6967 }
6968 }
6969 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006970 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006971 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006972 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006973 if (!mStandby) {
6974 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006975 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02006976 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07006977 }
Eric Laurent10351942014-05-08 18:49:52 -07006978 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006979 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006980 }
6981 if (status == NO_ERROR && reconfig) {
6982 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006983 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006984 }
6985 }
6986
Dean Wheatley68918102021-03-19 22:09:19 +11006987 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006988}
6989
Andy Hung71742ab2023-07-07 13:47:37 -07006990uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006991{
6992 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006993 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006994 time = PlaybackThread::activeSleepTimeUs();
6995 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006996 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006997 }
6998 return time;
6999}
7000
Andy Hung71742ab2023-07-07 13:47:37 -07007001uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007002{
7003 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007004 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007005 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7006 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007007 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007008 }
7009 return time;
7010}
7011
Andy Hung71742ab2023-07-07 13:47:37 -07007012uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007013{
7014 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007015 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007016 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7017 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007018 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007019 }
7020 return time;
7021}
7022
Andy Hung71742ab2023-07-07 13:47:37 -07007023void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007024{
7025 PlaybackThread::cacheParameters_l();
7026
7027 // use shorter standby delay as on normal output to release
7028 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007029 // no delay on outputs with HW A/V sync
7030 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007031 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007032 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007033 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007034 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007035 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007036 }
Eric Laurent81784c32012-11-19 14:55:58 -08007037}
7038
Andy Hung71742ab2023-07-07 13:47:37 -07007039void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007040{
ziyangch8f194f12021-12-01 13:48:04 -08007041 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007042 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007043 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007044 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007045 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007046 mTimestamp.clear();
Andy Hungee86cee2022-12-13 19:19:53 -08007047 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007048}
7049
Andy Hung71742ab2023-07-07 13:47:37 -07007050int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007051 // If a VolumeShaper is active, we must wake up periodically to update volume.
7052 const int64_t NS_PER_MS = 1000000;
7053 return mVolumeShaperActive ?
7054 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7055}
7056
Eric Laurent81784c32012-11-19 14:55:58 -08007057// ----------------------------------------------------------------------------
7058
Andy Hung71742ab2023-07-07 13:47:37 -07007059AsyncCallbackThread::AsyncCallbackThread(
7060 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007061 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007062 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007063 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007064 mDrainSequence(0),
7065 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007066{
7067}
7068
Andy Hung71742ab2023-07-07 13:47:37 -07007069void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007070{
7071 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7072}
7073
Andy Hung71742ab2023-07-07 13:47:37 -07007074bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007075{
7076 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007077 uint32_t writeAckSequence;
7078 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007079 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007080
7081 {
7082 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007083 while (!((mWriteAckSequence & 1) ||
7084 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007085 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007086 exitPending())) {
7087 mWaitWorkCV.wait(mLock);
7088 }
7089
Eric Laurentbfb1b832013-01-07 09:53:42 -08007090 if (exitPending()) {
7091 break;
7092 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007093 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7094 mWriteAckSequence, mDrainSequence);
7095 writeAckSequence = mWriteAckSequence;
7096 mWriteAckSequence &= ~1;
7097 drainSequence = mDrainSequence;
7098 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007099 asyncError = mAsyncError;
7100 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007101 }
7102 {
Andy Hung71742ab2023-07-07 13:47:37 -07007103 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007104 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007105 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007106 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007107 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007108 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007109 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007110 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007111 if (asyncError) {
7112 playbackThread->onAsyncError();
7113 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007114 }
7115 }
7116 }
7117 return false;
7118}
7119
Andy Hung71742ab2023-07-07 13:47:37 -07007120void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007121{
7122 ALOGV("AsyncCallbackThread::exit");
7123 Mutex::Autolock _l(mLock);
7124 requestExit();
7125 mWaitWorkCV.broadcast();
7126}
7127
Andy Hung71742ab2023-07-07 13:47:37 -07007128void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007129{
7130 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007131 // bit 0 is cleared
7132 mWriteAckSequence = sequence << 1;
7133}
7134
Andy Hung71742ab2023-07-07 13:47:37 -07007135void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007136{
7137 Mutex::Autolock _l(mLock);
7138 // ignore unexpected callbacks
7139 if (mWriteAckSequence & 2) {
7140 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007141 mWaitWorkCV.signal();
7142 }
7143}
7144
Andy Hung71742ab2023-07-07 13:47:37 -07007145void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007146{
7147 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007148 // bit 0 is cleared
7149 mDrainSequence = sequence << 1;
7150}
7151
Andy Hung71742ab2023-07-07 13:47:37 -07007152void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007153{
7154 Mutex::Autolock _l(mLock);
7155 // ignore unexpected callbacks
7156 if (mDrainSequence & 2) {
7157 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007158 mWaitWorkCV.signal();
7159 }
7160}
7161
Andy Hung71742ab2023-07-07 13:47:37 -07007162void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007163{
7164 Mutex::Autolock _l(mLock);
7165 mAsyncError = true;
7166 mWaitWorkCV.signal();
7167}
7168
Eric Laurentbfb1b832013-01-07 09:53:42 -08007169
7170// ----------------------------------------------------------------------------
Andy Hung71742ab2023-07-07 13:47:37 -07007171
7172/* static */
7173sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07007174 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07007175 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7176 const audio_offload_info_t& offloadInfo) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007177 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung71742ab2023-07-07 13:47:37 -07007178}
7179
Andy Hung2cbc2722023-07-17 17:05:00 -07007180OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fenn56576722022-10-05 13:42:36 -07007181 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7182 const audio_offload_info_t& offloadInfo)
Andy Hung2cbc2722023-07-17 17:05:00 -07007183 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007184 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007185{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007186 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007187 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007188 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007189}
7190
Andy Hung71742ab2023-07-07 13:47:37 -07007191void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007192{
7193 if (mFlushPending || mHwPaused) {
7194 // If a flush is pending or track was paused, just discard buffered data
7195 flushHw_l();
7196 } else {
7197 mMixerStatus = MIXER_DRAIN_ALL;
7198 threadLoop_drain();
7199 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007200 if (mUseAsyncWrite) {
7201 ALOG_ASSERT(mCallbackThread != 0);
7202 mCallbackThread->exit();
7203 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007204 PlaybackThread::threadLoop_exit();
7205}
7206
Andy Hung71742ab2023-07-07 13:47:37 -07007207PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07007208 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007209)
7210{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007211 size_t count = mActiveTracks.size();
7212
7213 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007214 bool doHwPause = false;
7215 bool doHwResume = false;
7216
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007217 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007218
Eric Laurentbfb1b832013-01-07 09:53:42 -08007219 // find out which tracks need to be processed
Andy Hung3ff4b552023-06-26 19:20:57 -07007220 for (const sp<IAfTrack>& t : mActiveTracks) {
7221 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007222#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007223 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007224#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007225 // Only consider last track started for volume and mixer state control.
7226 // In theory an older track could underrun and restart after the new one starts
7227 // but as we only care about the transition phase between two tracks on a
7228 // direct output, it is not a problem to ignore the underrun case.
Andy Hung3ff4b552023-06-26 19:20:57 -07007229 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007230 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007231
Haynes Mathew George7844f672014-01-15 12:32:55 -08007232 if (track->isInvalid()) {
7233 ALOGW("An invalidated track shouldn't be in active list");
7234 tracksToRemove->add(track);
7235 continue;
7236 }
7237
Andy Hung3ff4b552023-06-26 19:20:57 -07007238 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007239 ALOGW("An idle track shouldn't be in active list");
7240 continue;
7241 }
7242
Kuowei Li23666472021-01-20 10:23:25 +08007243 if (track->isPausePending()) {
7244 track->pauseAck();
7245 // It is possible a track might have been flushed or stopped.
7246 // Other operations such as flush pending might occur on the next prepare.
7247 if (track->isPausing()) {
7248 track->setPaused();
7249 }
7250 // Always perform pause if last, as an immediate flush will change
7251 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007252 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007253 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007254 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007255 mHwPaused = true;
7256 }
7257 // If we were part way through writing the mixbuffer to
7258 // the HAL we must save this until we resume
7259 // BUG - this will be wrong if a different track is made active,
7260 // in that case we want to discard the pending data in the
7261 // mixbuffer and tell the client to present it again when the
7262 // track is resumed
7263 mPausedWriteLength = mCurrentWriteLength;
7264 mPausedBytesRemaining = mBytesRemaining;
7265 mBytesRemaining = 0; // stop writing
7266 }
7267 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007268 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007269 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007270 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007271 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07007272 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007273 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007274 track->flushAck();
7275 if (last) {
7276 mFlushPending = true;
7277 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007278 } else if (track->isResumePending()){
7279 track->resumeAck();
7280 if (last) {
7281 if (mPausedBytesRemaining) {
7282 // Need to continue write that was interrupted
7283 mCurrentWriteLength = mPausedWriteLength;
7284 mBytesRemaining = mPausedBytesRemaining;
7285 mPausedBytesRemaining = 0;
7286 }
7287 if (mHwPaused) {
7288 doHwResume = true;
7289 mHwPaused = false;
7290 // threadLoop_mix() will handle the case that we need to
7291 // resume an interrupted write
7292 }
7293 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007294 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007295
Eric Laurent3df841a2016-07-15 15:15:40 -07007296 mLeftVolFloat = mRightVolFloat = -1.0;
7297
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007298 // Do not handle new data in this iteration even if track->framesReady()
7299 mixerStatus = MIXER_TRACKS_ENABLED;
7300 }
7301 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007302 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007303 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung3ff4b552023-06-26 19:20:57 -07007304 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7305 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007306 if (last) {
7307 // make sure processVolume_l() will apply new volume even if 0
7308 mLeftVolFloat = mRightVolFloat = -1.0;
7309 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007310 }
7311
7312 if (last) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007313 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007314 if (previousTrack != 0) {
7315 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007316 // Flush any data still being written from last track
7317 mBytesRemaining = 0;
7318 if (mPausedBytesRemaining) {
7319 // Last track was paused so we also need to flush saved
7320 // mixbuffer state and invalidate track so that it will
7321 // re-submit that unwritten data when it is next resumed
7322 mPausedBytesRemaining = 0;
7323 // Invalidate is a bit drastic - would be more efficient
7324 // to have a flag to tell client that some of the
7325 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007326 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007327 }
7328 // flush data already sent to the DSP if changing audio session as audio
7329 // comes from a different source. Also invalidate previous track to force a
7330 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007331 if (previousTrack->sessionId() != track->sessionId()) {
7332 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007333 }
7334 }
7335 }
7336 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007337 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007338 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007339 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007340 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07007341 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007342 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007343 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007344 mixerStatus = MIXER_TRACKS_READY;
7345 }
7346 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007347 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007348 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007349 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007350 // Hardware buffer can hold a large amount of audio so we must
7351 // wait for all current track's data to drain before we say
7352 // that the track is stopped.
7353 if (mBytesRemaining == 0) {
7354 // Only start draining when all data in mixbuffer
7355 // has been written
7356 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung3ff4b552023-06-26 19:20:57 -07007357 track->setState(IAfTrackBase::STOPPING_2);
7358 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007359 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7360 if (last && !mStandby) {
7361 // do not modify drain sequence if we are already draining. This happens
7362 // when resuming from pause after drain.
7363 if ((mDrainSequence & 1) == 0) {
7364 mSleepTimeUs = 0;
7365 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7366 mixerStatus = MIXER_DRAIN_TRACK;
7367 mDrainSequence += 2;
7368 }
7369 if (mHwPaused) {
7370 // It is possible to move from PAUSED to STOPPING_1 without
7371 // a resume so we must ensure hardware is running
7372 doHwResume = true;
7373 mHwPaused = false;
7374 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007375 }
7376 }
Eric Laurente93cc032016-05-05 10:15:10 -07007377 } else if (last) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007378 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007379 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007380 }
7381 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007382 // Drain has completed or we are in standby, signal presentation complete
7383 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007384 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007385 mOutput->presentationComplete();
7386 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007387 track->reset();
7388 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007389 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007390 if (!mUseAsyncWrite) {
7391 // If we don't get explicit drain notification we must
7392 // register discontinuity regardless of whether this is
7393 // the previous (!last) or the upcoming (last) track
7394 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007395 mTimestampVerifier.discontinuity(
7396 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007397 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007398 }
7399 } else {
7400 // No buffers for this track. Give it a few chances to
7401 // fill a buffer, then remove it from active list.
Brian Lindahl9e661ad2022-07-27 18:01:07 +02007402 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07007403 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung3ff4b552023-06-26 19:20:57 -07007404 && --(track->retryCount()) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02007405 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung3ff4b552023-06-26 19:20:57 -07007406 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007407 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007408 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7409 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007410 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007411 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007412 // it will then automatically call start() when data is available
7413 track->disable();
7414 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007415 } else if (last){
7416 mixerStatus = MIXER_TRACKS_ENABLED;
7417 }
7418 }
7419 }
7420 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007421 if (track->isReady()) { // check ready to prevent premature start.
7422 processVolume_l(track, last);
7423 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007424 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007425
Eric Laurentea0fade2013-10-04 16:23:48 -07007426 // make sure the pause/flush/resume sequence is executed in the right order.
7427 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7428 // before flush and then resume HW. This can happen in case of pause/flush/resume
7429 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007430 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007431 status_t result = mOutput->stream->pause();
7432 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007433 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007434 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007435 if (mFlushPending) {
7436 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007437 }
Eric Laurentfd477972013-10-25 18:10:40 -07007438 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007439 status_t result = mOutput->stream->resume();
7440 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007441 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007442
Eric Laurentbfb1b832013-01-07 09:53:42 -08007443 // remove all the tracks that need to be...
7444 removeTracks_l(*tracksToRemove);
7445
7446 return mixerStatus;
7447}
7448
Eric Laurentbfb1b832013-01-07 09:53:42 -08007449// must be called with thread mutex locked
Andy Hung71742ab2023-07-07 13:47:37 -07007450bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007451{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007452 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7453 mWriteAckSequence, mDrainSequence);
7454 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007455 return true;
7456 }
7457 return false;
7458}
7459
Andy Hung71742ab2023-07-07 13:47:37 -07007460bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007461{
7462 Mutex::Autolock _l(mLock);
7463 return waitingAsyncCallback_l();
7464}
7465
Andy Hung71742ab2023-07-07 13:47:37 -07007466void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007467{
Eric Laurente659ef42014-09-29 13:06:46 -07007468 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007469 // Flush anything still waiting in the mixbuffer
7470 mCurrentWriteLength = 0;
7471 mBytesRemaining = 0;
7472 mPausedWriteLength = 0;
7473 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007474 // reset bytes written count to reflect that DSP buffers are empty after flush.
7475 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007476
Eric Laurentbfb1b832013-01-07 09:53:42 -08007477 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007478 // discard any pending drain or write ack by incrementing sequence
7479 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7480 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007481 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007482 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7483 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007484 }
7485}
7486
Andy Hung71742ab2023-07-07 13:47:37 -07007487void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007488{
7489 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007490 if (PlaybackThread::invalidateTracks_l(streamType)) {
7491 mFlushPending = true;
7492 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007493}
7494
Andy Hung71742ab2023-07-07 13:47:37 -07007495void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08007496 Mutex::Autolock _l(mLock);
7497 if (PlaybackThread::invalidateTracks_l(portIds)) {
7498 mFlushPending = true;
7499 }
7500}
7501
Eric Laurentbfb1b832013-01-07 09:53:42 -08007502// ----------------------------------------------------------------------------
7503
Andy Hung71742ab2023-07-07 13:47:37 -07007504/* static */
7505sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung2cbc2722023-07-17 17:05:00 -07007506 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07007507 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007508 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -07007509}
7510
Andy Hung2cbc2722023-07-17 17:05:00 -07007511DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung44f27182023-07-06 20:56:16 -07007512 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -07007513 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007514 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007515 mWaitTimeMs(UINT_MAX)
7516{
7517 addOutputTrack(mainThread);
7518}
7519
Andy Hung71742ab2023-07-07 13:47:37 -07007520DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007521{
7522 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7523 mOutputTracks[i]->destroy();
7524 }
7525}
7526
Andy Hung71742ab2023-07-07 13:47:37 -07007527void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007528{
7529 // mix buffers...
Andy Hung71ba4b32022-10-06 12:09:49 -07007530 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007531 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007532 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007533 if (mMixerBufferValid) {
7534 memset(mMixerBuffer, 0, mMixerBufferSize);
7535 } else {
7536 memset(mSinkBuffer, 0, mSinkBufferSize);
7537 }
Eric Laurent81784c32012-11-19 14:55:58 -08007538 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007539 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007540 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007541 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007542 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007543}
7544
Andy Hung71742ab2023-07-07 13:47:37 -07007545void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007546{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007547 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007548 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007549 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007550 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007551 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007552 }
7553 } else if (mBytesWritten != 0) {
7554 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7555 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007556 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007557 } else {
7558 // flush remaining overflow buffers in output tracks
7559 writeFrames = 0;
7560 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007561 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007562 }
7563}
7564
Andy Hung71742ab2023-07-07 13:47:37 -07007565ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007566{
7567 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007568 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7569
7570 // Consider the first OutputTrack for timestamp and frame counting.
7571
7572 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7573 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7574 // we always claim success.
7575 if (i == 0) {
7576 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7577 ALOGD_IF(correction != 0 && writeFrames != 0,
7578 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7579 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7580 mFramesWritten -= correction;
7581 }
7582
7583 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007584 }
Andy Hungcf10d742020-04-28 15:38:24 -07007585 if (mStandby) {
7586 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007587 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007588 mStandby = false;
7589 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007590 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007591}
7592
Andy Hung71742ab2023-07-07 13:47:37 -07007593void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007594{
7595 // DuplicatingThread implements standby by stopping all tracks
7596 for (size_t i = 0; i < outputTracks.size(); i++) {
7597 outputTracks[i]->stop();
7598 }
7599}
7600
Andy Hung71742ab2023-07-07 13:47:37 -07007601void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007602{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007603 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007604
7605 std::stringstream ss;
7606 const size_t numTracks = mOutputTracks.size();
7607 ss << " " << numTracks << " OutputTracks";
7608 if (numTracks > 0) {
7609 ss << ":";
7610 for (const auto &track : mOutputTracks) {
Andy Hung44f27182023-07-06 20:56:16 -07007611 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007612 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007613 if (thread.get() != nullptr) {
7614 ss << thread.get() << ", " << thread->id();
7615 } else {
7616 ss << "null";
7617 }
7618 ss << ")";
7619 }
7620 }
7621 ss << "\n";
7622 std::string result = ss.str();
7623 write(fd, result.c_str(), result.size());
7624}
7625
Andy Hung71742ab2023-07-07 13:47:37 -07007626void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007627{
7628 outputTracks = mOutputTracks;
7629}
7630
Andy Hung71742ab2023-07-07 13:47:37 -07007631void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007632{
7633 outputTracks.clear();
7634}
7635
Andy Hung71742ab2023-07-07 13:47:37 -07007636void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007637{
7638 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007639 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7640 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7641 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7642 const size_t frameCount =
7643 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7644 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7645 // from different OutputTracks and their associated MixerThreads (e.g. one may
7646 // nearly empty and the other may be dropping data).
7647
Svet Ganov33761132021-05-13 22:51:08 +00007648 // TODO b/182392769: use attribution source util, move to server edge
7649 AttributionSourceState attributionSource = AttributionSourceState();
7650 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007651 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007652 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007653 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007654 attributionSource.token = sp<BBinder>::make();
Andy Hung3ff4b552023-06-26 19:20:57 -07007655 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007656 this,
7657 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007658 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007659 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007660 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007661 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007662 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7663 if (status != NO_ERROR) {
7664 ALOGE("addOutputTrack() initCheck failed %d", status);
7665 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007666 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007667 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7668 mOutputTracks.add(outputTrack);
7669 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7670 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007671}
7672
Andy Hung71742ab2023-07-07 13:47:37 -07007673void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007674{
7675 Mutex::Autolock _l(mLock);
7676 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7677 if (mOutputTracks[i]->thread() == thread) {
7678 mOutputTracks[i]->destroy();
7679 mOutputTracks.removeAt(i);
7680 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007681 if (thread->getOutput() == mOutput) {
7682 mOutput = NULL;
7683 }
Eric Laurent81784c32012-11-19 14:55:58 -08007684 return;
7685 }
7686 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007687 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007688}
7689
7690// caller must hold mLock
Andy Hung71742ab2023-07-07 13:47:37 -07007691void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007692{
7693 mWaitTimeMs = UINT_MAX;
7694 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung44f27182023-07-06 20:56:16 -07007695 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007696 if (strong != 0) {
7697 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7698 if (waitTimeMs < mWaitTimeMs) {
7699 mWaitTimeMs = waitTimeMs;
7700 }
7701 }
7702 }
7703}
7704
Andy Hung71742ab2023-07-07 13:47:37 -07007705bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007706{
7707 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung44f27182023-07-06 20:56:16 -07007708 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007709 if (thread == 0) {
7710 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7711 outputTracks[i].get());
7712 return false;
7713 }
Andy Hung44f27182023-07-06 20:56:16 -07007714 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007715 // see note at standby() declaration
Andy Hung4989d312023-06-29 21:19:25 -07007716 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007717 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7718 thread.get());
7719 return false;
7720 }
7721 }
7722 return true;
7723}
7724
Andy Hung71742ab2023-07-07 13:47:37 -07007725void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007726 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007727{
Kevin Rocard12381092018-04-11 09:19:59 -07007728 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7729 outputTrack->setMetadatas(metadata.tracks);
7730 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007731}
7732
Andy Hung71742ab2023-07-07 13:47:37 -07007733uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007734{
7735 return (mWaitTimeMs * 1000) / 2;
7736}
7737
Andy Hung71742ab2023-07-07 13:47:37 -07007738void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007739{
7740 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7741 updateWaitTime_l();
7742
7743 MixerThread::cacheParameters_l();
7744}
7745
Eric Laurentb3f315a2021-07-13 15:09:05 +02007746// ----------------------------------------------------------------------------
7747
Andy Hung71742ab2023-07-07 13:47:37 -07007748/* static */
7749sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07007750 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07007751 AudioStreamOut* output,
7752 audio_io_handle_t id,
7753 bool systemReady,
7754 audio_config_base_t* mixerConfig) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007755 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hung71742ab2023-07-07 13:47:37 -07007756}
7757
Andy Hung2cbc2722023-07-17 17:05:00 -07007758SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007759 AudioStreamOut* output,
7760 audio_io_handle_t id,
7761 bool systemReady,
7762 audio_config_base_t *mixerConfig)
Andy Hung2cbc2722023-07-17 17:05:00 -07007763 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007764{
7765}
7766
Andy Hung71742ab2023-07-07 13:47:37 -07007767void SpatializerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01007768 MixerThread::onFirstRef();
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007769
Andy Hung41ccf7f2022-12-14 14:25:49 -08007770 const pid_t tid = getTid();
7771 if (tid == -1) {
7772 // Unusual: PlaybackThread::onFirstRef() should set the threadLoop running.
7773 ALOGW("%s: Cannot update Spatializer mixer thread priority, not running", __func__);
7774 } else {
7775 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
7776 if (priorityBoost > 0) {
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007777 stream()->setHalThreadPriority(priorityBoost);
7778 }
7779 }
Eric Laurent6f9534f2022-05-03 18:15:04 +02007780}
7781
Andy Hung71742ab2023-07-07 13:47:37 -07007782void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent6f9534f2022-05-03 18:15:04 +02007783 // if mSupportedLatencyModes is empty, the HAL stream does not support
7784 // latency mode control and we can exit.
7785 if (mSupportedLatencyModes.empty()) {
7786 return;
7787 }
7788 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7789 if (mSupportedLatencyModes.size() == 1) {
7790 // If the HAL only support one latency mode currently, confirm the choice
7791 latencyMode = mSupportedLatencyModes[0];
7792 } else if (mSupportedLatencyModes.size() > 1) {
7793 // Request low latency if:
7794 // - The low latency mode is requested by the spatializer controller
7795 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7796 // AND
7797 // - At least one active track is spatialized
7798 bool hasSpatializedActiveTrack = false;
7799 for (const auto& track : mActiveTracks) {
7800 if (track->isSpatialized()) {
7801 hasSpatializedActiveTrack = true;
7802 break;
7803 }
7804 }
7805 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7806 latencyMode = AUDIO_LATENCY_MODE_LOW;
7807 }
7808 }
7809
7810 if (latencyMode != mSetLatencyMode) {
7811 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007812 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7813 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent6f9534f2022-05-03 18:15:04 +02007814 if (status == NO_ERROR) {
7815 mSetLatencyMode = latencyMode;
7816 }
7817 }
7818}
7819
Andy Hung71742ab2023-07-07 13:47:37 -07007820status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent6f9534f2022-05-03 18:15:04 +02007821 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7822 return BAD_VALUE;
7823 }
7824 Mutex::Autolock _l(mLock);
7825 mRequestedLatencyMode = mode;
7826 return NO_ERROR;
7827}
7828
Andy Hung71742ab2023-07-07 13:47:37 -07007829void SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007830{
7831 bool hasVirtualizer = false;
7832 bool hasDownMixer = false;
Andy Hungbd72c542023-06-20 18:56:17 -07007833 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007834 {
7835 Mutex::Autolock _l(mLock);
Andy Hungbd72c542023-06-20 18:56:17 -07007836 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007837 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007838 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007839 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7840 }
7841
7842 finalDownMixer = mFinalDownMixer;
7843 mFinalDownMixer.clear();
7844 }
7845
7846 if (hasVirtualizer) {
7847 if (finalDownMixer != nullptr) {
7848 int32_t ret;
Andy Hungbd72c542023-06-20 18:56:17 -07007849 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007850 }
7851 finalDownMixer.clear();
7852 } else if (!hasDownMixer) {
7853 std::vector<effect_descriptor_t> descriptors;
Andy Hung2cbc2722023-07-17 17:05:00 -07007854 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007855 EFFECT_UIID_DOWNMIX, &descriptors);
7856 if (status != NO_ERROR) {
7857 return;
7858 }
7859 ALOG_ASSERT(!descriptors.empty(),
7860 "%s getDescriptors() returned no error but empty list", __func__);
7861
7862 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7863 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007864 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007865
7866 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7867 ALOGW("%s error creating downmixer %d", __func__, status);
7868 finalDownMixer.clear();
7869 } else {
7870 int32_t ret;
Andy Hungbd72c542023-06-20 18:56:17 -07007871 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007872 }
7873 }
7874
7875 {
7876 Mutex::Autolock _l(mLock);
7877 mFinalDownMixer = finalDownMixer;
7878 }
7879}
7880
Eric Laurent81784c32012-11-19 14:55:58 -08007881// ----------------------------------------------------------------------------
7882// Record
7883// ----------------------------------------------------------------------------
7884
Andy Hung2cbc2722023-07-17 17:05:00 -07007885sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung44f27182023-07-06 20:56:16 -07007886 AudioStreamIn* input,
7887 audio_io_handle_t id,
7888 bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007889 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung44f27182023-07-06 20:56:16 -07007890}
7891
Andy Hung2cbc2722023-07-17 17:05:00 -07007892RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007893 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007894 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007895 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007896 ) :
Andy Hung2cbc2722023-07-17 17:05:00 -07007897 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007898 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007899 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007900 mActiveTracks(&this->mLocalLog),
7901 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007902 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007903 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007904 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7905 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007906 // mFastCapture below
7907 , mFastCaptureFutex(0)
7908 // mInputSource
7909 // mPipeSink
7910 // mPipeSource
7911 , mPipeFramesP2(0)
7912 // mPipeMemory
7913 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007914 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007915 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007916{
Glenn Kastend7dca052015-03-05 16:05:54 -08007917 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung2cbc2722023-07-17 17:05:00 -07007918 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007919
George Burgess IVa8f90c12020-05-14 11:27:19 -07007920 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007921 mIsMsdDevice = strcmp(
7922 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7923 }
7924
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007925 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007926
Andy Hungc8fddf32018-08-08 18:32:37 -07007927 // TODO: We may also match on address as well as device type for
7928 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007929 // TODO: This property should be ensure that only contains one single device type.
7930 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7931 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007932 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7933 : AUDIO_DEVICE_NONE));
7934
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007935 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007936 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007937 size_t numCounterOffers = 0;
7938 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007939#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007940 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007941#else
7942 (void)
7943#endif
7944 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007945 ALOG_ASSERT(index == 0);
7946
7947 // initialize fast capture depending on configuration
7948 bool initFastCapture;
7949 switch (kUseFastCapture) {
7950 case FastCapture_Never:
7951 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007952 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007953 break;
7954 case FastCapture_Always:
7955 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007956 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007957 break;
7958 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007959 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
7960 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7961 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d "
7962 "mIsMsdDevice = %d", this, (long long)mFrameCount, mSampleRate,
7963 kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007964 break;
7965 // case FastCapture_Dynamic:
7966 }
7967
7968 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007969 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007970 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007971 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7972 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007973 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007974 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007975 const sp<MemoryDealer> roHeap(readOnlyHeap());
7976 sp<IMemory> pipeMemory;
7977 if ((roHeap == 0) ||
7978 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007979 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007980 ALOGE("not enough memory for pipe buffer size=%zu; "
7981 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7982 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7983 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007984 goto failed;
7985 }
7986 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7987 memset(pipeBuffer, 0, pipeSize);
7988 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07007989 const NBAIO_Format offersFast[1] = {format};
7990 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007991 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung71ba4b32022-10-06 12:09:49 -07007992 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007993 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007994 mPipeSink = pipe;
7995 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung71ba4b32022-10-06 12:09:49 -07007996 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007997 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung71ba4b32022-10-06 12:09:49 -07007998 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007999 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008000 mPipeSource = pipeReader;
8001 mPipeFramesP2 = pipeFramesP2;
8002 mPipeMemory = pipeMemory;
8003
8004 // create fast capture
8005 mFastCapture = new FastCapture();
8006 FastCaptureStateQueue *sq = mFastCapture->sq();
8007#ifdef STATE_QUEUE_DUMP
8008 // FIXME
8009#endif
8010 FastCaptureState *state = sq->begin();
8011 state->mCblk = NULL;
8012 state->mInputSource = mInputSource.get();
8013 state->mInputSourceGen++;
8014 state->mPipeSink = pipe;
8015 state->mPipeSinkGen++;
8016 state->mFrameCount = mFrameCount;
8017 state->mCommand = FastCaptureState::COLD_IDLE;
8018 // already done in constructor initialization list
8019 //mFastCaptureFutex = 0;
8020 state->mColdFutexAddr = &mFastCaptureFutex;
8021 state->mColdGen++;
8022 state->mDumpState = &mFastCaptureDumpState;
8023#ifdef TEE_SINK
8024 // FIXME
8025#endif
Andy Hung2cbc2722023-07-17 17:05:00 -07008026 mFastCaptureNBLogWriter =
8027 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008028 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8029 sq->end();
8030 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8031
8032 // start the fast capture
8033 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8034 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008035 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008036 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008037#ifdef AUDIO_WATCHDOG
8038 // FIXME
8039#endif
8040
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008041 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008042 }
Andy Hung8946a282018-04-19 20:04:56 -07008043#ifdef TEE_SINK
8044 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8045 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8046#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008047failed: ;
8048
8049 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008050}
8051
Andy Hung71742ab2023-07-07 13:47:37 -07008052RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008053{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008054 if (mFastCapture != 0) {
8055 FastCaptureStateQueue *sq = mFastCapture->sq();
8056 FastCaptureState *state = sq->begin();
8057 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8058 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8059 if (old == -1) {
8060 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8061 }
8062 }
8063 state->mCommand = FastCaptureState::EXIT;
8064 sq->end();
8065 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8066 mFastCapture->join();
8067 mFastCapture.clear();
8068 }
Andy Hung2cbc2722023-07-17 17:05:00 -07008069 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8070 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008071 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008072}
8073
Andy Hung71742ab2023-07-07 13:47:37 -07008074void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008075{
Glenn Kastend7dca052015-03-05 16:05:54 -08008076 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008077}
8078
Andy Hung71742ab2023-07-07 13:47:37 -07008079void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008080{
8081 ALOGV(" preExit()");
8082 Mutex::Autolock _l(mLock);
8083 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008084 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008085 track->invalidate();
8086 }
8087 mActiveTracks.clear();
8088 mStartStopCond.broadcast();
8089}
8090
Andy Hung71742ab2023-07-07 13:47:37 -07008091bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008092{
Eric Laurent81784c32012-11-19 14:55:58 -08008093 nsecs_t lastWarning = 0;
8094
8095 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008096
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008097reacquire_wakelock:
Andy Hung3ff4b552023-06-26 19:20:57 -07008098 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008099 {
8100 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07008101 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008102 }
8103
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008104 // used to request a deferred sleep, to be executed later while mutex is unlocked
8105 uint32_t sleepUs = 0;
8106
Andy Hung446f4df2019-02-21 12:26:41 -08008107 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8108
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008109 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008110 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hungbd72c542023-06-20 18:56:17 -07008111 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008112
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008113 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung3ff4b552023-06-26 19:20:57 -07008114 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008115
Glenn Kasten735f45f2014-08-18 15:51:59 -07008116 // reference to the (first and only) active fast track
Andy Hung3ff4b552023-06-26 19:20:57 -07008117 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008118
Glenn Kasten735f45f2014-08-18 15:51:59 -07008119 // reference to a fast track which is about to be removed
Andy Hung3ff4b552023-06-26 19:20:57 -07008120 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008121
Eric Laurent33403f02020-05-29 18:35:06 -07008122 bool silenceFastCapture = false;
8123
Eric Laurent81784c32012-11-19 14:55:58 -08008124 { // scope for mLock
8125 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08008126
Eric Laurent021cf962014-05-13 10:18:14 -07008127 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008128
Eric Laurent000a4192014-01-29 15:17:32 -08008129 // check exitPending here because checkForNewParameters_l() and
8130 // checkForNewParameters_l() can temporarily release mLock
8131 if (exitPending()) {
8132 break;
8133 }
8134
Eric Laurent5c25d562016-07-13 17:17:45 -07008135 // sleep with mutex unlocked
8136 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008137 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07008138 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
8139 ATRACE_END();
8140 sleepUs = 0;
8141 continue;
8142 }
8143
Glenn Kasten2b806402013-11-20 16:37:38 -08008144 // if no active track(s), then standby and release wakelock
8145 size_t size = mActiveTracks.size();
8146 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008147 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008148 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008149 releaseWakeLock_l();
8150 ALOGV("RecordThread: loop stopping");
8151 // go to sleep
8152 mWaitWorkCV.wait(mLock);
8153 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008154 goto reacquire_wakelock;
8155 }
8156
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008157 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008158 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008159 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008160
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008161 activeTrack = mActiveTracks[i];
8162 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008163 if (activeTrack->isFastTrack()) {
8164 ALOG_ASSERT(fastTrackToRemove == 0);
8165 fastTrackToRemove = activeTrack;
8166 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008167 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008168 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008169 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008170 continue;
8171 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008172
Andy Hung3ff4b552023-06-26 19:20:57 -07008173 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008174 switch (activeTrackState) {
8175
Andy Hung3ff4b552023-06-26 19:20:57 -07008176 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008177 mActiveTracks.remove(activeTrack);
Andy Hung3ff4b552023-06-26 19:20:57 -07008178 activeTrack->setState(IAfTrackBase::PAUSED);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008179 doBroadcast = true;
8180 size--;
8181 continue;
8182
Andy Hung3ff4b552023-06-26 19:20:57 -07008183 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008184 sleepUs = 10000;
8185 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008186 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008187 continue;
8188
Andy Hung3ff4b552023-06-26 19:20:57 -07008189 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008190 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008191 if (mStandby) {
8192 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008193 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008194 mStandby = false;
8195 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008196 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008197 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008198 break;
8199
Andy Hung3ff4b552023-06-26 19:20:57 -07008200 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008201 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008202 break;
8203
Andy Hung3ff4b552023-06-26 19:20:57 -07008204 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8205 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8206 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008207 default:
Andy Hungce685402018-10-05 17:23:27 -07008208 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8209 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008210 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008211
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008212 if (activeTrack->isFastTrack()) {
8213 ALOG_ASSERT(!mFastTrackAvail);
8214 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008215 // if the active fast track is silenced either:
8216 // 1) silence the whole capture from fast capture buffer if this is
8217 // the only active track
8218 // 2) invalidate this track: this will cause the client to reconnect and possibly
8219 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008220 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008221 if (activeTrack->isSilenced()) {
8222 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008223 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008224 } else {
8225 silenceFastCapture = true;
8226 }
8227 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008228 // Invalidate fast tracks if access to audio history is required as this is not
8229 // possible with fast tracks. Once the fast track has been invalidated, no new
8230 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8231 if (mMaxSharedAudioHistoryMs != 0) {
8232 invalidate = true;
8233 }
8234 if (invalidate) {
8235 activeTrack->invalidate();
8236 ALOG_ASSERT(fastTrackToRemove == 0);
8237 fastTrackToRemove = activeTrack;
8238 removeTrack_l(activeTrack);
8239 mActiveTracks.remove(activeTrack);
8240 size--;
8241 continue;
8242 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008243 fastTrack = activeTrack;
8244 }
Eric Laurent33403f02020-05-29 18:35:06 -07008245
8246 activeTracks.add(activeTrack);
8247 i++;
8248
Glenn Kasten9e982352013-08-14 14:39:50 -07008249 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008250
Andy Hungdae27702016-10-31 14:01:16 -07008251 mActiveTracks.updatePowerState(this);
8252
Kevin Rocard069c2712018-03-29 19:09:14 -07008253 updateMetadata_l();
8254
Eric Laurent5c25d562016-07-13 17:17:45 -07008255 if (allStopped) {
8256 standbyIfNotAlreadyInStandby();
8257 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008258 if (doBroadcast) {
8259 mStartStopCond.broadcast();
8260 }
8261
8262 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008263 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008264 if (sleepUs == 0) {
8265 sleepUs = kRecordThreadSleepUs;
8266 }
8267 continue;
8268 }
8269 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008270
Eric Laurent81784c32012-11-19 14:55:58 -08008271 lockEffectChains_l(effectChains);
8272 }
8273
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008274 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008275
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008276 size_t size = effectChains.size();
8277 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008278 // thread mutex is not locked, but effect chain is locked
8279 effectChains[i]->process_l();
8280 }
8281
Glenn Kasten735f45f2014-08-18 15:51:59 -07008282 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008283 if (mFastCapture != 0) {
8284 FastCaptureStateQueue *sq = mFastCapture->sq();
8285 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008286 bool didModify = false;
8287 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008288 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8289 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8290 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8291 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8292 if (old == -1) {
8293 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8294 }
8295 }
8296 state->mCommand = FastCaptureState::READ_WRITE;
8297#if 0 // FIXME
Andy Hung2cbc2722023-07-17 17:05:00 -07008298 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008299 FastThreadDumpState::kSamplingNforLowRamDevice :
8300 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008301#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008302 didModify = true;
8303 }
8304 audio_track_cblk_t *cblkOld = state->mCblk;
8305 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8306 if (cblkNew != cblkOld) {
8307 state->mCblk = cblkNew;
8308 // block until acked if removing a fast track
8309 if (cblkOld != NULL) {
8310 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8311 }
8312 didModify = true;
8313 }
jiabin01c8f562018-07-19 17:47:28 -07008314 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8315 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8316 if (state->mFastPatchRecordBufferProvider != abp) {
8317 state->mFastPatchRecordBufferProvider = abp;
8318 state->mFastPatchRecordFormat = fastTrack == 0 ?
8319 AUDIO_FORMAT_INVALID : fastTrack->format();
8320 didModify = true;
8321 }
Eric Laurent33403f02020-05-29 18:35:06 -07008322 if (state->mSilenceCapture != silenceFastCapture) {
8323 state->mSilenceCapture = silenceFastCapture;
8324 didModify = true;
8325 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008326 sq->end(didModify);
8327 if (didModify) {
8328 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008329#if 0
8330 if (kUseFastCapture == FastCapture_Dynamic) {
8331 mNormalSource = mPipeSource;
8332 }
8333#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008334 }
8335 }
8336
Glenn Kasten735f45f2014-08-18 15:51:59 -07008337 // now run the fast track destructor with thread mutex unlocked
8338 fastTrackToRemove.clear();
8339
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008340 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8341 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8342 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8343 // If destination is non-contiguous, first read past the nominal end of buffer, then
8344 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008345
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008346 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung71ba4b32022-10-06 12:09:49 -07008347 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008348 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008349
8350 // If an NBAIO source is present, use it to read the normal capture's data
8351 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008352 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008353
8354 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8355 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8356 // we immediately retry the read() to get data and prevent another overflow.
8357 for (int retries = 0; retries <= 2; ++retries) {
8358 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8359 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8360 framesToRead);
8361 if (framesRead != OVERRUN) break;
8362 }
8363
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008364 const ssize_t availableToRead = mPipeSource->availableToRead();
8365 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008366 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008367 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008368 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8369 "more frames to read than fifo size, %zd > %zu",
8370 availableToRead, mPipeFramesP2);
8371 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8372 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8373 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8374 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008375 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8376 }
8377 if (framesRead < 0) {
8378 status_t status = (status_t) framesRead;
8379 switch (status) {
8380 case OVERRUN:
8381 ALOGW("overrun on read from pipe");
8382 framesRead = 0;
8383 break;
8384 case NEGOTIATE:
8385 ALOGE("re-negotiation is needed");
8386 framesRead = -1; // Will cause an attempt to recover.
8387 break;
8388 default:
8389 ALOGE("unknown error %d on read from pipe", status);
8390 break;
8391 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008392 }
8393 // otherwise use the HAL / AudioStreamIn directly
8394 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008395 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008396 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008397 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008398 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008399 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008400 if (result < 0) {
8401 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008402 } else {
8403 framesRead = bytesRead / mFrameSize;
8404 }
8405 }
8406
Andy Hung446f4df2019-02-21 12:26:41 -08008407 const int64_t lastIoEndNs = systemTime(); // end IO timing
8408
Andy Hung3f0c9022016-01-15 17:49:46 -08008409 // Update server timestamp with server stats
8410 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008411 if (framesRead >= 0) {
8412 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8413 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8414 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008415
8416 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008417 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008418 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008419 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008420 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8421 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8422 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008423 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008424 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8425
8426 mTimestampVerifier.add(position, time, mSampleRate);
8427
8428 // Correct timestamps
8429 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008430 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008431 id(), (long long)time, (long long)position);
8432 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8433 position = correctedTimestamp.mFrames;
8434 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008435 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008436 id(), (long long)time, (long long)position);
8437 }
8438
Andy Hung3f0c9022016-01-15 17:49:46 -08008439 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8440 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8441 // Note: In general record buffers should tend to be empty in
8442 // a properly running pipeline.
8443 //
8444 // Also, it is not advantageous to call get_presentation_position during the read
8445 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008446 } else {
8447 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008448 }
8449 }
Andy Hunge6c37112019-02-26 17:38:10 -08008450
8451 // From the timestamp, input read latency is negative output write latency.
8452 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung3ff4b552023-06-26 19:20:57 -07008453 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008454 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8455 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8456 mLatencyMs.add(latencyMs);
8457 }
8458
Andy Hung3f0c9022016-01-15 17:49:46 -08008459 // Use this to track timestamp information
8460 // ALOGD("%s", mTimestamp.toString().c_str());
8461
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008462 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008463 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008464 // Force input into standby so that it tries to recover at next read attempt
8465 inputStandBy();
8466 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008467 }
8468 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008469 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008470 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008471 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008472 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008473
Andy Hung8946a282018-04-19 20:04:56 -07008474#ifdef TEE_SINK
8475 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8476#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008477 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008478 {
8479 size_t part1 = mRsmpInFramesP2 - rear;
8480 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008481 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008482 (framesRead - part1) * mFrameSize);
8483 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008484 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008485 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008486
8487 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008488
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008489 // loop over each active track
8490 for (size_t i = 0; i < size; i++) {
8491 activeTrack = activeTracks[i];
8492
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008493 // skip fast tracks, as those are handled directly by FastCapture
8494 if (activeTrack->isFastTrack()) {
8495 continue;
8496 }
8497
Andy Hung73c02e42015-03-29 01:13:58 -07008498 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008499 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8500
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008501 enum {
8502 OVERRUN_UNKNOWN,
8503 OVERRUN_TRUE,
8504 OVERRUN_FALSE
8505 } overrun = OVERRUN_UNKNOWN;
8506
8507 // loop over getNextBuffer to handle circular sink
8508 for (;;) {
8509
Andy Hung3ff4b552023-06-26 19:20:57 -07008510 activeTrack->sinkBuffer().frameCount = ~0;
8511 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8512 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008513 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8514
Andy Hung73c02e42015-03-29 01:13:58 -07008515 // check available frames and handle overrun conditions
8516 // if the record track isn't draining fast enough.
8517 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008518 size_t framesIn;
Andy Hung3ff4b552023-06-26 19:20:57 -07008519 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008520 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008521 overrun = OVERRUN_TRUE;
8522 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008523 if (framesOut == 0 || framesIn == 0) {
8524 break;
8525 }
8526
Andy Hung6770c6f2015-04-07 13:43:36 -07008527 // Don't allow framesOut to be larger than what is possible with resampling
8528 // from framesIn.
8529 // This isn't strictly necessary but helps limit buffer resizing in
8530 // RecordBufferConverter. TODO: remove when no longer needed.
8531 framesOut = min(framesOut,
8532 destinationFramesPossible(
Andy Hung3ff4b552023-06-26 19:20:57 -07008533 framesIn, mSampleRate, activeTrack->sampleRate()));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008534
8535 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008536 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008537 // straight from RecordThread buffer to RecordTrack buffer.
8538 AudioBufferProvider::Buffer buffer;
8539 buffer.frameCount = framesOut;
Andy Hung71ba4b32022-10-06 12:09:49 -07008540 const status_t getNextBufferStatus =
Andy Hung3ff4b552023-06-26 19:20:57 -07008541 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07008542 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008543 ALOGV_IF(buffer.frameCount != framesOut,
8544 "%s() read less than expected (%zu vs %zu)",
8545 __func__, buffer.frameCount, framesOut);
8546 framesOut = buffer.frameCount;
Andy Hung3ff4b552023-06-26 19:20:57 -07008547 memcpy(activeTrack->sinkBuffer().raw,
8548 buffer.raw, buffer.frameCount * mFrameSize);
8549 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008550 } else {
8551 framesOut = 0;
8552 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung71ba4b32022-10-06 12:09:49 -07008553 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008554 }
8555 } else {
8556 // process frames from the RecordThread buffer provider to the RecordTrack
8557 // buffer
Andy Hung3ff4b552023-06-26 19:20:57 -07008558 framesOut = activeTrack->recordBufferConverter()->convert(
8559 activeTrack->sinkBuffer().raw,
8560 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008561 framesOut);
8562 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008563
8564 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8565 overrun = OVERRUN_FALSE;
8566 }
8567
Andy Hung93bb5732023-05-04 21:16:34 -07008568 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8569 const ssize_t framesToDrop =
Andy Hung3ff4b552023-06-26 19:20:57 -07008570 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008571 if (framesToDrop == 0) {
8572 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008573 if (framesOut > 0) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008574 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008575 // Sanitize before releasing if the track has no access to the source data
8576 // An idle UID receives silence from non virtual devices until active
8577 if (activeTrack->isSilenced()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008578 memset(activeTrack->sinkBuffer().raw,
8579 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008580 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008581 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008582 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008583 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008584 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008585 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008586 }
8587 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008588
8589 switch (overrun) {
8590 case OVERRUN_TRUE:
8591 // client isn't retrieving buffers fast enough
8592 if (!activeTrack->setOverflow()) {
8593 nsecs_t now = systemTime();
8594 // FIXME should lastWarning per track?
8595 if ((now - lastWarning) > kWarningThrottleNs) {
8596 ALOGW("RecordThread: buffer overflow");
8597 lastWarning = now;
8598 }
8599 }
8600 break;
8601 case OVERRUN_FALSE:
8602 activeTrack->clearOverflow();
8603 break;
8604 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008605 break;
8606 }
8607
Andy Hung3f0c9022016-01-15 17:49:46 -08008608 // update frame information and push timestamp out
8609 activeTrack->updateTrackFrameInfo(
Andy Hung3ff4b552023-06-26 19:20:57 -07008610 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008611 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8612 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008613 }
8614
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008615unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008616 // enable changes in effect chain
8617 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008618 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008619 if (audio_has_proportional_frames(mFormat)
8620 && loopCount == lastLoopCountRead + 1) {
8621 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8622 const double jitterMs =
8623 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8624 {framesRead, readPeriodNs},
8625 {0, 0} /* lastTimestamp */, mSampleRate);
8626 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8627
8628 Mutex::Autolock _l(mLock);
8629 mIoJitterMs.add(jitterMs);
8630 mProcessTimeMs.add(processMs);
8631 }
8632 // update timing info.
8633 mLastIoBeginNs = lastIoBeginNs;
8634 mLastIoEndNs = lastIoEndNs;
8635 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008636 }
8637
Glenn Kasten93e471f2013-08-19 08:40:07 -07008638 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008639
8640 {
8641 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008642 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008643 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008644 track->invalidate();
8645 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008646 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008647 mStartStopCond.broadcast();
8648 }
8649
8650 releaseWakeLock();
8651
8652 ALOGV("RecordThread %p exiting", this);
8653 return false;
8654}
8655
Andy Hung71742ab2023-07-07 13:47:37 -07008656void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008657{
8658 if (!mStandby) {
8659 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008660 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008661 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008662 mStandby = true;
8663 }
8664}
8665
Andy Hung71742ab2023-07-07 13:47:37 -07008666void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008667{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008668 // Idle the fast capture if it's currently running
8669 if (mFastCapture != 0) {
8670 FastCaptureStateQueue *sq = mFastCapture->sq();
8671 FastCaptureState *state = sq->begin();
8672 if (!(state->mCommand & FastCaptureState::IDLE)) {
8673 state->mCommand = FastCaptureState::COLD_IDLE;
8674 state->mColdFutexAddr = &mFastCaptureFutex;
8675 state->mColdGen++;
8676 mFastCaptureFutex = 0;
8677 sq->end();
8678 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8679 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8680#if 0
8681 if (kUseFastCapture == FastCapture_Dynamic) {
8682 // FIXME
8683 }
8684#endif
8685#ifdef AUDIO_WATCHDOG
8686 // FIXME
8687#endif
8688 } else {
8689 sq->end(false /*didModify*/);
8690 }
8691 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008692 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008693 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008694
8695 // If going into standby, flush the pipe source.
8696 if (mPipeSource.get() != nullptr) {
8697 const ssize_t flushed = mPipeSource->flush();
8698 if (flushed > 0) {
8699 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8700 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8701 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8702 }
8703 }
Eric Laurent81784c32012-11-19 14:55:58 -08008704}
8705
Glenn Kasten05997e22014-03-13 15:08:33 -07008706// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07008707sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hungd65869f2023-06-27 17:05:02 -07008708 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008709 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008710 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008711 audio_format_t format,
8712 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008713 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008714 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008715 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008716 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008717 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008718 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008719 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008720 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008721 audio_port_handle_t portId,
8722 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008723{
Glenn Kasten74935e42013-12-19 08:56:45 -08008724 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008725 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung3ff4b552023-06-26 19:20:57 -07008726 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008727 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008728 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008729 audio_input_flags_t requestedFlags = *flags;
8730 uint32_t sampleRate;
8731
8732 lStatus = initCheck();
8733 if (lStatus != NO_ERROR) {
8734 ALOGE("createRecordTrack_l() audio driver not initialized");
8735 goto Exit;
8736 }
8737
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008738 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8739 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8740 lStatus = BAD_VALUE;
8741 goto Exit;
8742 }
8743
Eric Laurentec376dc2021-04-08 20:41:22 +02008744 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008745 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008746 lStatus = PERMISSION_DENIED;
8747 goto Exit;
8748 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008749 if (maxSharedAudioHistoryMs < 0
8750 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8751 lStatus = BAD_VALUE;
8752 goto Exit;
8753 }
8754 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008755 if (*pSampleRate == 0) {
8756 *pSampleRate = mSampleRate;
8757 }
8758 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008759
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008760 // special case for FAST flag considered OK if fast capture is present and access to
8761 // audio history is not required
8762 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008763 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8764 }
8765
Eric Laurentf14db3c2017-12-08 14:20:36 -08008766 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008767 if ((*flags & inputFlags) != *flags) {
8768 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8769 " input flags (%08x)",
8770 *flags, inputFlags);
8771 *flags = (audio_input_flags_t)(*flags & inputFlags);
8772 }
Eric Laurent81784c32012-11-19 14:55:58 -08008773
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008774 // client expresses a preference for FAST and no access to audio history,
8775 // but we get the final say
8776 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008777 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008778 // we formerly checked for a callback handler (non-0 tid),
8779 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008780 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008781 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008782 // Frame count is not specified (0), or is less than or equal the pipe depth.
8783 // It is OK to provide a higher capacity than requested.
8784 // We will force it to mPipeFramesP2 below.
8785 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008786 // PCM data
8787 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008788 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008789 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008790 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008791 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008792 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008793 hasFastCapture() &&
8794 // there are sufficient fast track slots available
8795 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008796 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008797 // check compatibility with audio effects.
8798 Mutex::Autolock _l(mLock);
8799 // Do not accept FAST flag if the session has software effects
Andy Hungbd72c542023-06-20 18:56:17 -07008800 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008801 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008802 audio_input_flags_t old = *flags;
8803 chain->checkInputFlagCompatibility(flags);
8804 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008805 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8806 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008807 }
8808 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008809 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008810 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8811 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008812 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008813 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8814 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008815 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008816 this, frameCount, mFrameCount, mPipeFramesP2,
8817 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008818 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008819 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008820 }
8821 }
8822
Eric Laurentf14db3c2017-12-08 14:20:36 -08008823 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8824 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8825 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8826 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8827 lStatus = BAD_TYPE;
8828 goto Exit;
8829 }
8830
Glenn Kasten74105912014-07-03 12:28:53 -07008831 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008832 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008833 // fast track: frame count is exactly the pipe depth
8834 frameCount = mPipeFramesP2;
8835 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008836 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008837 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008838 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8839 // or 20 ms if there is a fast capture
8840 // TODO This could be a roundupRatio inline, and const
8841 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8842 * sampleRate + mSampleRate - 1) / mSampleRate;
8843 // minimum number of notification periods is at least kMinNotifications,
8844 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8845 static const size_t kMinNotifications = 3;
8846 static const uint32_t kMinMs = 30;
8847 // TODO This could be a roundupRatio inline
8848 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8849 // TODO This could be a roundupRatio inline
8850 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8851 maxNotificationFrames;
8852 const size_t minFrameCount = maxNotificationFrames *
8853 max(kMinNotifications, minNotificationsByMs);
8854 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008855 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8856 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008857 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008858 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008859 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008860 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008861
8862 { // scope for mLock
8863 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008864 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008865 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008866 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008867 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008868 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008869 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008870 }
Eric Laurent81784c32012-11-19 14:55:58 -08008871
Andy Hung3ff4b552023-06-26 19:20:57 -07008872 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008873 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008874 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung3ff4b552023-06-26 19:20:57 -07008875 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008876 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008877
Glenn Kasten03003332013-08-06 15:40:54 -07008878 lStatus = track->initCheck();
8879 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008880 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008881 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008882 goto Exit;
8883 }
8884 mTracks.add(track);
8885
Eric Laurent05067782016-06-01 18:27:28 -07008886 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008887 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8888 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8889 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008890 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008891 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008892
8893 if (maxSharedAudioHistoryMs != 0) {
8894 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8895 }
Eric Laurent81784c32012-11-19 14:55:58 -08008896 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008897
Eric Laurent81784c32012-11-19 14:55:58 -08008898 lStatus = NO_ERROR;
8899
8900Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008901 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008902 return track;
8903}
8904
Andy Hung71742ab2023-07-07 13:47:37 -07008905status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08008906 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008907 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008908{
8909 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8910 sp<ThreadBase> strongMe = this;
8911 status_t status = NO_ERROR;
8912
8913 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008914 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008915 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008916 recordTrack->synchronizedRecordState().startRecording(
Andy Hung2cbc2722023-07-17 17:05:00 -07008917 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07008918 event, triggerSession,
8919 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08008920 }
8921
8922 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008923 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008924 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008925 if (recordTrack->isInvalid()) {
8926 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008927 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8928 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008929 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008930 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008931 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008932 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8933 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008934 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung3ff4b552023-06-26 19:20:57 -07008935 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008936 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07008937 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008938 }
8939 return status;
8940 }
8941
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008942 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8943 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8944 // or using a separate command thread
Andy Hung3ff4b552023-06-26 19:20:57 -07008945 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08008946 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008947 if (recordTrack->isExternalTrack()) {
8948 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008949 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008950 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008951 if (recordTrack->isInvalid()) {
8952 recordTrack->clearSyncStartEvent();
Andy Hung3ff4b552023-06-26 19:20:57 -07008953 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
8954 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07008955 // STARTING_2 forces destroy to call stopInput.
8956 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008957 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8958 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008959 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008960 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07008961 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung3ff4b552023-06-26 19:20:57 -07008962 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07008963 // Someone else has changed state, let them take over,
8964 // leave mState in the new state.
8965 recordTrack->clearSyncStartEvent();
8966 return INVALID_OPERATION;
8967 }
8968 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008969 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008970 ALOGW("%s(%d): startInput failed, status %d",
8971 __func__, recordTrack->id(), status);
8972 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8973 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008974 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008975 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008976 return status;
8977 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008978 sendIoConfigEvent_l(
8979 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008980 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008981
8982 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8983
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008984 // Catch up with current buffer indices if thread is already running.
8985 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8986 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8987 // see previously buffered data before it called start(), but with greater risk of overrun.
8988
Andy Hung3ff4b552023-06-26 19:20:57 -07008989 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008990 if (!recordTrack->isDirect()) {
8991 // clear any converter state as new data will be discontinuous
Andy Hung3ff4b552023-06-26 19:20:57 -07008992 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008993 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008994 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08008995 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008996 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008997 return status;
8998 }
Eric Laurent81784c32012-11-19 14:55:58 -08008999}
9000
Andy Hung71742ab2023-07-07 13:47:37 -07009001void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009002{
Andy Hung71742ab2023-07-07 13:47:37 -07009003 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009004
9005 if (strongEvent != 0) {
Andy Hung02a6c4e2023-06-23 19:27:19 -07009006 sp<IAfTrackBase> ptr =
9007 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9008 if (ptr != nullptr) {
Andy Hung56126702023-07-14 11:00:08 -07009009 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hung02a6c4e2023-06-23 19:27:19 -07009010 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009011 }
Eric Laurent81784c32012-11-19 14:55:58 -08009012 }
9013}
9014
Andy Hung71742ab2023-07-07 13:47:37 -07009015bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009016 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07009017 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07009018 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung3ff4b552023-06-26 19:20:57 -07009019 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009020 return false;
9021 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009022 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung3ff4b552023-06-26 19:20:57 -07009023 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009024
Andy Hungabfab202019-03-07 19:45:54 -08009025 // NOTE: Waiting here is important to keep stop synchronous.
9026 // This is needed for proper patchRecord peer release.
Andy Hung3ff4b552023-06-26 19:20:57 -07009027 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungce685402018-10-05 17:23:27 -07009028 mWaitWorkCV.broadcast(); // signal thread to stop
9029 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08009030 }
Andy Hungce685402018-10-05 17:23:27 -07009031
Andy Hung3ff4b552023-06-26 19:20:57 -07009032 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009033 ALOGV("Record stopped OK");
9034 return true;
9035 }
Andy Hungce685402018-10-05 17:23:27 -07009036
9037 // don't handle anything - we've been invalidated or restarted and in a different state
9038 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung3ff4b552023-06-26 19:20:57 -07009039 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009040 return false;
9041}
9042
Andy Hung71742ab2023-07-07 13:47:37 -07009043bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009044{
9045 return false;
9046}
9047
Andy Hung71742ab2023-07-07 13:47:37 -07009048status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009049{
9050#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9051 if (!isValidSyncEvent(event)) {
9052 return BAD_VALUE;
9053 }
9054
Glenn Kastend848eb42016-03-08 13:42:11 -08009055 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009056 status_t ret = NAME_NOT_FOUND;
9057
9058 Mutex::Autolock _l(mLock);
9059
9060 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009061 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009062 if (eventSession == track->sessionId()) {
9063 (void) track->setSyncEvent(event);
9064 ret = NO_ERROR;
9065 }
9066 }
9067 return ret;
9068#else
9069 return BAD_VALUE;
9070#endif
9071}
9072
Andy Hung71742ab2023-07-07 13:47:37 -07009073status_t RecordThread::getActiveMicrophones(
Andy Hung44f27182023-07-06 20:56:16 -07009074 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009075{
9076 ALOGV("RecordThread::getActiveMicrophones");
9077 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009078 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009079 return NO_INIT;
9080 }
jiabin9ff780e2018-03-19 18:19:52 -07009081 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9082 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009083}
9084
Andy Hung71742ab2023-07-07 13:47:37 -07009085status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009086 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009087{
Paul McLean12340082019-03-19 09:35:05 -06009088 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009089 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009090 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009091 return NO_INIT;
9092 }
Paul McLean12340082019-03-19 09:35:05 -06009093 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009094}
9095
Andy Hung71742ab2023-07-07 13:47:37 -07009096status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009097{
Paul McLean12340082019-03-19 09:35:05 -06009098 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009099 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009100 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009101 return NO_INIT;
9102 }
Paul McLean12340082019-03-19 09:35:05 -06009103 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009104}
9105
Andy Hung71742ab2023-07-07 13:47:37 -07009106status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009107 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9108 int64_t sharedAudioStartMs) {
9109 AutoMutex _l(mLock);
9110 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9111}
9112
Andy Hung71742ab2023-07-07 13:47:37 -07009113status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009114 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9115 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009116
Eric Laurentec376dc2021-04-08 20:41:22 +02009117 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9118 return BAD_VALUE;
9119 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009120
9121 if (sharedAudioStartMs < 0
9122 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009123 return BAD_VALUE;
9124 }
9125
Eric Laurent2407ce32021-04-26 14:56:03 +02009126 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9127 // As we cannot detect more than one wraparound, only accept values up current write position
9128 // after one wraparound
9129 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9130 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009131 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009132 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9133 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009134 // Bring the start frame position within the input buffer to match the documented
9135 // "best effort" behavior of the API.
9136 if (sharedOffset < 0) {
9137 sharedAudioStartFrames = mRsmpInRear;
Andy Hung71ba4b32022-10-06 12:09:49 -07009138 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009139 sharedAudioStartFrames =
9140 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009141 }
9142
Eric Laurentec376dc2021-04-08 20:41:22 +02009143 mSharedAudioPackageName = sharedAudioPackageName;
9144 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009145 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009146 } else {
9147 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009148 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009149 }
9150 return NO_ERROR;
9151}
9152
Andy Hung71742ab2023-07-07 13:47:37 -07009153void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009154 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9155 mSharedAudioStartFrames = -1;
9156 mSharedAudioPackageName = "";
9157}
9158
Andy Hung71742ab2023-07-07 13:47:37 -07009159ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009160{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009161 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009162 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009163 }
9164 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009165 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung3ff4b552023-06-26 19:20:57 -07009166 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009167 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009168 }
9169 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009170 MetadataUpdate change;
9171 change.recordMetadataUpdate = metadata.tracks;
9172 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009173}
9174
Eric Laurent81784c32012-11-19 14:55:58 -08009175// destroyTrack_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -07009176void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009177{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009178 track->terminate();
Andy Hung3ff4b552023-06-26 19:20:57 -07009179 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009180
Eric Laurent81784c32012-11-19 14:55:58 -08009181 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009182 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009183 removeTrack_l(track);
9184 }
9185}
9186
Andy Hung71742ab2023-07-07 13:47:37 -07009187void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009188{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009189 String8 result;
9190 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00009191 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009192
Eric Laurent81784c32012-11-19 14:55:58 -08009193 mTracks.remove(track);
9194 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009195 if (track->isFastTrack()) {
9196 ALOG_ASSERT(!mFastTrackAvail);
9197 mFastTrackAvail = true;
9198 }
Eric Laurent81784c32012-11-19 14:55:58 -08009199}
9200
Andy Hung71742ab2023-07-07 13:47:37 -07009201void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009202{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009203 AudioStreamIn *input = mInput;
9204 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9205 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009206 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009207 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009208 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009209 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009210 }
Andy Hungbfa64962017-06-12 14:43:19 -07009211
9212 if (input != nullptr) {
9213 dprintf(fd, " Hal stream dump:\n");
9214 (void)input->stream->dump(fd);
9215 }
9216
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009217 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009218 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009219
Glenn Kasten2f90c512015-12-02 11:40:09 -08009220 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9221 // while we are dumping it. It may be inconsistent, but it won't mutate!
9222 // This is a large object so we place it on the heap.
9223 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009224 const std::unique_ptr<FastCaptureDumpState> copy =
9225 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009226 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009227}
9228
Andy Hung71742ab2023-07-07 13:47:37 -07009229void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009230{
Eric Laurent81784c32012-11-19 14:55:58 -08009231 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009232 size_t numtracks = mTracks.size();
9233 size_t numactive = mActiveTracks.size();
9234 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009235 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009236 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009237 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009238 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009239 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009240 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009241 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009242 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009243 if (track != 0) {
9244 bool active = mActiveTracks.indexOf(track) >= 0;
9245 if (active) {
9246 numactiveseen++;
9247 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009248 result.append(prefix);
9249 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009250 }
Eric Laurent81784c32012-11-19 14:55:58 -08009251 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009252 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009253 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009254 }
9255
Marco Nelissenb2208842014-02-07 14:00:50 -08009256 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009257 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009258 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009259 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009260 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009261 for (size_t i = 0; i < numactive; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009262 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009263 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009264 result.append(prefix);
9265 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009266 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009267 }
Eric Laurent81784c32012-11-19 14:55:58 -08009268
9269 }
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00009270 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009271}
9272
Andy Hung71742ab2023-07-07 13:47:37 -07009273void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009274{
9275 Mutex::Autolock _l(mLock);
9276 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009277 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009278 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009279 track->setSilenced(silenced);
9280 }
9281 }
9282}
Andy Hung73c02e42015-03-29 01:13:58 -07009283
Andy Hung3ff4b552023-06-26 19:20:57 -07009284void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009285{
Andy Hung44f27182023-07-06 20:56:16 -07009286 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung71742ab2023-07-07 13:47:37 -07009287 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009288 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009289 const int32_t rear = recordThread->mRsmpInRear;
9290 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009291 if (mRecordTrack->startFrames() >= 0) {
9292 int32_t startFrames = mRecordTrack->startFrames();
9293 // Accept a recent wraparound of mRsmpInRear
9294 if (startFrames <= rear) {
9295 deltaFrames = rear - startFrames;
9296 } else {
9297 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009298 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009299 // start frame cannot be further in the past than start of resampling buffer
9300 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9301 deltaFrames = recordThread->mRsmpInFrames;
9302 }
9303 }
9304 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009305}
9306
Andy Hung3ff4b552023-06-26 19:20:57 -07009307void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009308 size_t *framesAvailable, bool *hasOverrun)
9309{
Andy Hung44f27182023-07-06 20:56:16 -07009310 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung71742ab2023-07-07 13:47:37 -07009311 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009312 const int32_t rear = recordThread->mRsmpInRear;
9313 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009314 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009315
9316 size_t framesIn;
9317 bool overrun = false;
9318 if (filled < 0) {
9319 // should not happen, but treat like a massive overrun and re-sync
9320 framesIn = 0;
9321 mRsmpInFront = rear;
9322 overrun = true;
9323 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9324 framesIn = (size_t) filled;
9325 } else {
9326 // client is not keeping up with server, but give it latest data
9327 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009328 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9329 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009330 overrun = true;
9331 }
9332 if (framesAvailable != NULL) {
9333 *framesAvailable = framesIn;
9334 }
9335 if (hasOverrun != NULL) {
9336 *hasOverrun = overrun;
9337 }
9338}
9339
Eric Laurent81784c32012-11-19 14:55:58 -08009340// AudioBufferProvider interface
Andy Hung3ff4b552023-06-26 19:20:57 -07009341status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009342 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009343{
Andy Hung44f27182023-07-06 20:56:16 -07009344 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009345 if (threadBase == 0) {
9346 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009347 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009348 return NOT_ENOUGH_DATA;
9349 }
Andy Hung71742ab2023-07-07 13:47:37 -07009350 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009351 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009352 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009353 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009354 // FIXME should not be P2 (don't want to increase latency)
9355 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009356 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009357 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009358
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009359 front &= recordThread->mRsmpInFramesP2 - 1;
9360 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009361 if (part1 > (size_t) filled) {
9362 part1 = filled;
9363 }
9364 size_t ask = buffer->frameCount;
9365 ALOG_ASSERT(ask > 0);
9366 if (part1 > ask) {
9367 part1 = ask;
9368 }
9369 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009370 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009371 buffer->raw = NULL;
9372 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009373 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009374 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009375 }
9376
Andy Hung57446612015-04-19 23:56:46 -07009377 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009378 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009379 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009380 return NO_ERROR;
9381}
9382
9383// AudioBufferProvider interface
Andy Hung3ff4b552023-06-26 19:20:57 -07009384void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009385 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009386{
Hongwei Wang95e37682019-04-12 11:13:36 -07009387 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009388 if (stepCount == 0) {
9389 return;
9390 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009391 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009392 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009393 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009394 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009395 buffer->frameCount = 0;
9396}
9397
Andy Hung71742ab2023-07-07 13:47:37 -07009398void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009399{
9400 Mutex::Autolock _l(mLock);
9401 checkBtNrec_l();
9402}
9403
Andy Hung71742ab2023-07-07 13:47:37 -07009404void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009405{
9406 // disable AEC and NS if the device is a BT SCO headset supporting those
9407 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009408 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Andy Hung2cbc2722023-07-17 17:05:00 -07009409 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009410 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9411 for (size_t i = 0; i < mEffectChains.size(); i++) {
9412 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9413 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9414 }
9415 }
9416}
9417
Andy Hung97a893e2015-03-29 01:03:07 -07009418
Andy Hung71742ab2023-07-07 13:47:37 -07009419bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009420 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009421{
9422 bool reconfig = false;
9423
Eric Laurent10351942014-05-08 18:49:52 -07009424 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009425
Eric Laurent10351942014-05-08 18:49:52 -07009426 audio_format_t reqFormat = mFormat;
9427 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009428 // 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 +08009429 [[maybe_unused]] audio_channel_mask_t channelMask =
9430 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009431
9432 AudioParameter param = AudioParameter(keyValuePair);
9433 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009434
9435 // scope for AutoPark extends to end of method
9436 AutoPark<FastCapture> park(mFastCapture);
9437
Eric Laurent10351942014-05-08 18:49:52 -07009438 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9439 // channel count change can be requested. Do we mandate the first client defines the
9440 // HAL sampling rate and channel count or do we allow changes on the fly?
9441 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9442 samplingRate = value;
9443 reconfig = true;
9444 }
9445 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009446 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009447 status = BAD_VALUE;
9448 } else {
9449 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009450 reconfig = true;
9451 }
Eric Laurent10351942014-05-08 18:49:52 -07009452 }
9453 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9454 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009455 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009456 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009457 status = BAD_VALUE;
9458 } else {
9459 channelMask = mask;
9460 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009461 }
Eric Laurent10351942014-05-08 18:49:52 -07009462 }
9463 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9464 // do not accept frame count changes if tracks are open as the track buffer
9465 // size depends on frame count and correct behavior would not be guaranteed
9466 // if frame count is changed after track creation
9467 if (mActiveTracks.size() > 0) {
9468 status = INVALID_OPERATION;
9469 } else {
9470 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009471 }
Eric Laurent10351942014-05-08 18:49:52 -07009472 }
9473 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009474 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009475 }
9476 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9477 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009478 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009479 }
Glenn Kastene198c362013-08-13 09:13:36 -07009480
Eric Laurent10351942014-05-08 18:49:52 -07009481 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009482 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009483 if (status == INVALID_OPERATION) {
9484 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009485 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009486 }
9487 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009488 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009489 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9490 if (mInput->stream->getAudioProperties(&config) == OK &&
9491 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9492 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009493 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009494 status = NO_ERROR;
9495 }
Eric Laurent81784c32012-11-19 14:55:58 -08009496 }
Eric Laurent10351942014-05-08 18:49:52 -07009497 if (status == NO_ERROR) {
9498 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009499 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009500 }
9501 }
Eric Laurent81784c32012-11-19 14:55:58 -08009502 }
Eric Laurent10351942014-05-08 18:49:52 -07009503
Eric Laurent81784c32012-11-19 14:55:58 -08009504 return reconfig;
9505}
9506
Andy Hung71742ab2023-07-07 13:47:37 -07009507String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009508{
Eric Laurent81784c32012-11-19 14:55:58 -08009509 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009510 if (initCheck() == NO_ERROR) {
9511 String8 out_s8;
9512 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9513 return out_s8;
9514 }
Eric Laurent81784c32012-11-19 14:55:58 -08009515 }
Andy Hung71ba4b32022-10-06 12:09:49 -07009516 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009517}
9518
Andy Hung71742ab2023-07-07 13:47:37 -07009519void RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009520 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009521 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009522 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009523 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009524 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009525 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009526 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9527 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009528 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009529 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009530 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009531 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009532 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009533 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009534 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009535 break;
9536 }
Andy Hung2cbc2722023-07-17 17:05:00 -07009537 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009538}
9539
Andy Hung71742ab2023-07-07 13:47:37 -07009540void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009541{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009542 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9543 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009544 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009545 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9546 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009547 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9548 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009549 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009550 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009551 ALOGI("HAL format %#x is not linear pcm", mFormat);
9552 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009553 result = mInput->stream->getFrameSize(&mFrameSize);
9554 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009555 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9556 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009557 result = mInput->stream->getBufferSize(&mBufferSize);
9558 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009559 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009560 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9561 "mBufferSize=%zu, mFrameCount=%zu",
9562 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009563
Eric Laurentec376dc2021-04-08 20:41:22 +02009564 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9565 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009566 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009567
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009568 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9569 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009570
9571 audio_input_flags_t flags = mInput->flags;
9572 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9573 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9574 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9575 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9576 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9577 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9578 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9579 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9580 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009581}
9582
Andy Hung71742ab2023-07-07 13:47:37 -07009583uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009584{
9585 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009586 uint32_t result;
9587 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9588 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009589 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009590 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009591}
9592
Andy Hung71742ab2023-07-07 13:47:37 -07009593KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009594{
Glenn Kastend848eb42016-03-08 13:42:11 -08009595 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009596 Mutex::Autolock _l(mLock);
9597 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009598 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009599 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009600 if (ids.indexOfKey(sessionId) < 0) {
9601 ids.add(sessionId, true);
9602 }
9603 }
9604 return ids;
9605}
9606
Andy Hung71742ab2023-07-07 13:47:37 -07009607AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009608{
9609 Mutex::Autolock _l(mLock);
9610 AudioStreamIn *input = mInput;
9611 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009612 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009613 return input;
9614}
9615
9616// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hung71742ab2023-07-07 13:47:37 -07009617sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009618{
9619 if (mInput == NULL) {
9620 return NULL;
9621 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009622 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009623}
9624
Andy Hung71742ab2023-07-07 13:47:37 -07009625status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009626{
Eric Laurent81784c32012-11-19 14:55:58 -08009627 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009628 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009629 chain->setInBuffer(NULL);
9630 chain->setOutBuffer(NULL);
9631
9632 checkSuspendOnAddEffectChain_l(chain);
9633
Eric Laurent1b928682014-10-02 19:41:47 -07009634 // make sure enabled pre processing effects state is communicated to the HAL as we
9635 // just moved them to a new input stream.
9636 chain->syncHalEffectsState();
9637
Eric Laurent81784c32012-11-19 14:55:58 -08009638 mEffectChains.add(chain);
9639
9640 return NO_ERROR;
9641}
9642
Andy Hung71742ab2023-07-07 13:47:37 -07009643size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009644{
9645 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009646
9647 for (size_t i = 0; i < mEffectChains.size(); i++) {
9648 if (chain == mEffectChains[i]) {
9649 mEffectChains.removeAt(i);
9650 break;
9651 }
Eric Laurent81784c32012-11-19 14:55:58 -08009652 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009653 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009654}
9655
Andy Hung71742ab2023-07-07 13:47:37 -07009656status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009657 audio_patch_handle_t *handle)
9658{
9659 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009660
9661 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009662 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009663 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009664 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009665 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009666 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009667 }
9668
Eric Laurentd8365c52017-07-16 15:27:05 -07009669 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009670
9671 // store new source and send to effects
9672 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9673 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009674 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009675 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009676 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009677 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009678
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009679 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009680 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9681 status = hwDevice->createAudioPatch(patch->num_sources,
9682 patch->sources,
9683 patch->num_sinks,
9684 patch->sinks,
9685 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009686 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009687 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9688 patch->sinks[0].ext.mix.usecase.source,
9689 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009690 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009691 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009692
jiabinc52b1ff2019-10-31 17:20:42 -07009693 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009694 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009695 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009696 }
Eric Laurent296fb132015-05-01 11:38:42 -07009697
Andy Hungc2b11cb2020-04-22 09:04:01 -07009698 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009699 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009700 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009701 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009702 // also dispatch to active AudioRecords
9703 for (const auto &track : mActiveTracks) {
9704 track->logEndInterval();
9705 track->logBeginInterval(pathSourcesAsString);
9706 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009707 // Force meteadata update after a route change
9708 mActiveTracks.setHasChanged();
9709
Eric Laurent1c333e22014-05-20 10:48:17 -07009710 return status;
9711}
9712
Andy Hung71742ab2023-07-07 13:47:37 -07009713status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009714{
9715 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009716
jiabinc52b1ff2019-10-31 17:20:42 -07009717 mPatch = audio_patch{};
9718 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009719
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009720 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009721 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9722 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009723 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009724 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009725 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009726 // Force meteadata update after a route change
9727 mActiveTracks.setHasChanged();
9728
Eric Laurent1c333e22014-05-20 10:48:17 -07009729 return status;
9730}
9731
Andy Hung71742ab2023-07-07 13:47:37 -07009732void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009733{
wendy lin56aa82b2020-12-02 15:19:55 +08009734 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009735 mOutDevices = outDevices;
9736 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9737 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009738 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009739 }
9740}
9741
Andy Hung71742ab2023-07-07 13:47:37 -07009742int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009743{
9744 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009745 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009746 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009747 int32_t oldestFront = mRsmpInRear;
9748 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009749 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009750 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009751 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009752 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009753 if (filled > maxFilled) {
9754 oldestFront = front;
9755 maxFilled = filled;
9756 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009757 }
Andy Hung71ba4b32022-10-06 12:09:49 -07009758 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009759 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9760 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009761 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009762}
9763
Andy Hung71742ab2023-07-07 13:47:37 -07009764void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009765{
9766 if (offset == 0) {
9767 return;
9768 }
9769 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009770 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009771 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung3ff4b552023-06-26 19:20:57 -07009772 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009773 }
9774}
9775
Andy Hung71742ab2023-07-07 13:47:37 -07009776void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009777{
9778 // This is the formula for calculating the temporary buffer size.
9779 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9780 // 1 full output buffer, regardless of the alignment of the available input.
9781 // The value is somewhat arbitrary, and could probably be even larger.
9782 // A larger value should allow more old data to be read after a track calls start(),
9783 // without increasing latency.
9784 //
9785 // Note this is independent of the maximum downsampling ratio permitted for capture.
9786 size_t minRsmpInFrames = mFrameCount * 7;
9787
9788 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9789 // capture history available to another client using the same session ID:
9790 // dimension the resampler input buffer accordingly.
9791
9792 // Get oldest client read position: getOldestFront_l() must be called before altering
9793 // mRsmpInRear, or mRsmpInFrames
9794 int32_t previousFront = getOldestFront_l();
9795 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9796 int32_t previousRear = mRsmpInRear;
9797 mRsmpInRear = 0;
9798
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009799 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hung71742ab2023-07-07 13:47:37 -07009800 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009801 "resizeInputBuffer_l() called with invalid max shared history %d",
9802 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009803 if (maxSharedAudioHistoryMs != 0) {
9804 // resizeInputBuffer_l should never be called with a non zero shared history if the
9805 // buffer was not already allocated
9806 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9807 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9808 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9809 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009810 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009811 return;
9812 }
9813 mRsmpInFrames = rsmpInFrames;
9814 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009815 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009816 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9817 // initialized
9818 if (mRsmpInFrames < minRsmpInFrames) {
9819 mRsmpInFrames = minRsmpInFrames;
9820 }
9821 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9822
9823 // TODO optimize audio capture buffer sizes ...
9824 // Here we calculate the size of the sliding buffer used as a source
9825 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9826 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9827 // be better to have it derived from the pipe depth in the long term.
9828 // The current value is higher than necessary. However it should not add to latency.
9829
9830 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9831 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9832
9833 void *rsmpInBuffer;
9834 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9835 // if posix_memalign fails, will segv here.
9836 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9837
9838 // Copy audio history if any from old buffer before freeing it
9839 if (previousRear != 0) {
9840 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9841 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9842
9843 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9844 previousFront &= previousRsmpInFramesP2 - 1;
9845 size_t part1 = previousRsmpInFramesP2 - previousFront;
9846 if (part1 > (size_t) unread) {
9847 part1 = unread;
9848 }
9849 if (part1 != 0) {
9850 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9851 part1 * mFrameSize);
9852 mRsmpInRear = part1;
9853 part1 = unread - part1;
9854 if (part1 != 0) {
9855 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9856 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9857 mRsmpInRear += part1;
9858 }
9859 }
9860 // Update front for all clients according to new rear
9861 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9862 } else {
9863 mRsmpInRear = 0;
9864 }
9865 free(mRsmpInBuffer);
9866 mRsmpInBuffer = rsmpInBuffer;
9867}
9868
Andy Hung71742ab2023-07-07 13:47:37 -07009869void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009870{
9871 Mutex::Autolock _l(mLock);
9872 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009873 if (record->getSource()) {
9874 mSource = record->getSource();
9875 }
Eric Laurent83b88082014-06-20 18:31:16 -07009876}
9877
Andy Hung71742ab2023-07-07 13:47:37 -07009878void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009879{
9880 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009881 if (mSource == record->getSource()) {
9882 mSource = mInput;
9883 }
Eric Laurent83b88082014-06-20 18:31:16 -07009884 destroyTrack_l(record);
9885}
9886
Andy Hung71742ab2023-07-07 13:47:37 -07009887void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07009888{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009889 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009890 config->role = AUDIO_PORT_ROLE_SINK;
9891 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9892 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009893 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9894 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9895 config->flags.input = mInput->flags;
9896 }
Eric Laurent83b88082014-06-20 18:31:16 -07009897}
Eric Laurent1c333e22014-05-20 10:48:17 -07009898
Eric Laurent6acd1d42017-01-04 14:23:29 -08009899// ----------------------------------------------------------------------------
9900// Mmap
9901// ----------------------------------------------------------------------------
9902
Andy Hung667dec42023-07-07 15:58:48 -07009903// Mmap stream control interface implementation. Each MmapThreadHandle controls one
9904// MmapPlaybackThread or MmapCaptureThread instance.
9905class MmapThreadHandle : public MmapStreamInterface {
9906public:
9907 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
9908 ~MmapThreadHandle() override;
9909
9910 // MmapStreamInterface virtuals
9911 status_t createMmapBuffer(int32_t minSizeFrames,
9912 struct audio_mmap_buffer_info* info) final;
9913 status_t getMmapPosition(struct audio_mmap_position* position) final;
9914 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
9915 status_t start(const AudioClient& client,
9916 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
9917 status_t stop(audio_port_handle_t handle) final;
9918 status_t standby() final;
9919 status_t reportData(const void* buffer, size_t frameCount) final;
9920private:
9921 const sp<IAfMmapThread> mThread;
9922};
9923
9924/* static */
9925sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
9926 const sp<IAfMmapThread>& mmapThread) {
9927 return sp<MmapThreadHandle>::make(mmapThread);
9928}
9929
9930MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009931 : mThread(thread)
9932{
Phil Burk9fabbf82017-08-03 12:02:00 -07009933 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009934}
9935
Andy Hung667dec42023-07-07 15:58:48 -07009936// MmapStreamInterface could be directly implemented by MmapThread excepting this
9937// special handling on adapter dtor.
9938MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009939{
Phil Burk9fabbf82017-08-03 12:02:00 -07009940 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009941}
9942
Andy Hung667dec42023-07-07 15:58:48 -07009943status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009944 struct audio_mmap_buffer_info *info)
9945{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009946 return mThread->createMmapBuffer(minSizeFrames, info);
9947}
9948
Andy Hung667dec42023-07-07 15:58:48 -07009949status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009950{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009951 return mThread->getMmapPosition(position);
9952}
9953
Andy Hung667dec42023-07-07 15:58:48 -07009954status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -07009955 int64_t *timeNanos) {
9956 return mThread->getExternalPosition(position, timeNanos);
9957}
9958
Andy Hung667dec42023-07-07 15:58:48 -07009959status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009960 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009961{
jiabind1f1cb62020-03-24 11:57:57 -07009962 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009963}
9964
Andy Hung667dec42023-07-07 15:58:48 -07009965status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009966{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009967 return mThread->stop(handle);
9968}
9969
Andy Hung667dec42023-07-07 15:58:48 -07009970status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -08009971{
Eric Laurent18b57012017-02-13 16:23:52 -08009972 return mThread->standby();
9973}
9974
Andy Hung667dec42023-07-07 15:58:48 -07009975status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
9976{
jiabinfc791ee2023-02-15 19:43:40 +00009977 return mThread->reportData(buffer, frameCount);
9978}
9979
Eric Laurent6acd1d42017-01-04 14:23:29 -08009980
Andy Hung71742ab2023-07-07 13:47:37 -07009981MmapThread::MmapThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07009982 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung71ba4b32022-10-06 12:09:49 -07009983 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung2cbc2722023-07-17 17:05:00 -07009984 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009985 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009986 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009987 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009988 mActiveTracks(&this->mLocalLog),
9989 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9990 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009991{
Eric Laurent18b57012017-02-13 16:23:52 -08009992 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009993 readHalParameters_l();
9994}
9995
Andy Hung71742ab2023-07-07 13:47:37 -07009996void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009997{
9998 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9999}
10000
Andy Hung71742ab2023-07-07 13:47:37 -070010001void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010002{
Andy Hung3ff4b552023-06-26 19:20:57 -070010003 ActiveTracks<IAfMmapTrack> activeTracks;
Eric Laurent331679c2018-04-16 17:03:16 -070010004 {
10005 Mutex::Autolock _l(mLock);
Andy Hung3ff4b552023-06-26 19:20:57 -070010006 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010007 activeTracks.add(t);
10008 }
10009 }
Andy Hung3ff4b552023-06-26 19:20:57 -070010010 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010011 stop(t->portId());
10012 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010013 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010014 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010015 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010016 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010017 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010018 }
10019}
10020
10021
Andy Hung71742ab2023-07-07 13:47:37 -070010022void MmapThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010023 audio_stream_type_t streamType __unused,
10024 audio_session_t sessionId,
10025 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010026 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010027 audio_port_handle_t portId)
10028{
10029 mAttr = *attr;
10030 mSessionId = sessionId;
10031 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010032 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010033 mPortId = portId;
10034}
10035
Andy Hung71742ab2023-07-07 13:47:37 -070010036status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010037 struct audio_mmap_buffer_info *info)
10038{
10039 if (mHalStream == 0) {
10040 return NO_INIT;
10041 }
Eric Laurent18b57012017-02-13 16:23:52 -080010042 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010043 return mHalStream->createMmapBuffer(minSizeFrames, info);
10044}
10045
Andy Hung71742ab2023-07-07 13:47:37 -070010046status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010047{
10048 if (mHalStream == 0) {
10049 return NO_INIT;
10050 }
10051 return mHalStream->getMmapPosition(position);
10052}
10053
Andy Hung71742ab2023-07-07 13:47:37 -070010054status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010055{
Eric Laurentdda206a2022-07-08 17:28:35 +020010056 // The HAL must receive track metadata before starting the stream
10057 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010058 status_t ret = mHalStream->start();
10059 if (ret != NO_ERROR) {
10060 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10061 return ret;
10062 }
Andy Hungcf10d742020-04-28 15:38:24 -070010063 if (mStandby) {
10064 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010065 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010066 mStandby = false;
10067 }
Eric Laurent331679c2018-04-16 17:03:16 -070010068 return NO_ERROR;
10069}
10070
Andy Hung71742ab2023-07-07 13:47:37 -070010071status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010072 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010073 audio_port_handle_t *handle)
10074{
Eric Laurenta54f1282017-07-01 19:39:32 -070010075 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010076 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010077 if (mHalStream == 0) {
10078 return NO_INIT;
10079 }
10080
10081 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010082
Eric Laurentdda206a2022-07-08 17:28:35 +020010083 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010084 if (*handle == mPortId) {
Eric Laurentdda206a2022-07-08 17:28:35 +020010085 acquireWakeLock();
10086 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010087 }
10088
10089 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10090
10091 audio_io_handle_t io = mId;
Andy Hungc5106312023-07-19 16:56:19 -070010092 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010093 client.attributionSource);
10094
Eric Laurenta54f1282017-07-01 19:39:32 -070010095 if (isOutput()) {
10096 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10097 config.sample_rate = mSampleRate;
10098 config.channel_mask = mChannelMask;
10099 config.format = mFormat;
10100 audio_stream_type_t stream = streamType();
10101 audio_output_flags_t flags =
10102 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010103 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010104 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010105 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010106 bool isBitPerfect;
Eric Laurenta54f1282017-07-01 19:39:32 -070010107 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
10108 mSessionId,
10109 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010110 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010111 &config,
10112 flags,
10113 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010114 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010115 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010116 &isSpatialized,
10117 &isBitPerfect);
Kevin Rocard153f92d2018-12-18 18:33:28 -080010118 ALOGD_IF(!secondaryOutputs.empty(),
10119 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010120 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010121 audio_config_base_t config;
10122 config.sample_rate = mSampleRate;
10123 config.channel_mask = mChannelMask;
10124 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010125 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -070010126 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010127 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -070010128 mSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010129 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010130 &config,
10131 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10132 &deviceId,
10133 &portId);
10134 }
10135 // APM should not chose a different input or output stream for the same set of attributes
10136 // and audo configuration
10137 if (ret != NO_ERROR || io != mId) {
10138 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10139 __FUNCTION__, ret, io, mId);
10140 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010141 }
10142
10143 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010144 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010145 } else {
jiabincfc10a42022-06-15 19:26:01 +000010146 {
10147 // Add the track record before starting input so that the silent status for the
10148 // client can be cached.
10149 Mutex::Autolock _l(mLock);
10150 setClientSilencedState_l(portId, false /*silenced*/);
10151 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010152 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010153 }
10154
Eric Laurent331679c2018-04-16 17:03:16 -070010155 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010156 // abort if start is rejected by audio policy manager
10157 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010158 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010159 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -070010160 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010161 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010162 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010163 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010164 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010165 }
Eric Laurent331679c2018-04-16 17:03:16 -070010166 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010167 } else {
10168 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010169 }
jiabincfc10a42022-06-15 19:26:01 +000010170 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010171 return PERMISSION_DENIED;
10172 }
10173
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010174 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung3ff4b552023-06-26 19:20:57 -070010175 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10176 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010177 mChannelMask, mSessionId, isOutput(),
10178 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010179 IPCThreadState::self()->getCallingPid(), portId);
jiabincfc10a42022-06-15 19:26:01 +000010180 if (!isOutput()) {
10181 track->setSilenced_l(isClientSilenced_l(portId));
10182 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010183
Eric Laurent4eb58f12018-12-07 16:41:02 -080010184 if (isOutput()) {
10185 // force volume update when a new track is added
10186 mHalVolFloat = -1.0f;
10187 } else if (!track->isSilenced_l()) {
Andy Hung3ff4b552023-06-26 19:20:57 -070010188 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung71ba4b32022-10-06 12:09:49 -070010189 if (t->isSilenced_l()
10190 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010191 t->invalidate();
Andy Hung71ba4b32022-10-06 12:09:49 -070010192 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010193 }
10194 }
10195
Eric Laurent6acd1d42017-01-04 14:23:29 -080010196 mActiveTracks.add(track);
Andy Hungbd72c542023-06-20 18:56:17 -070010197 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010198 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +020010199 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010200 chain->incTrackCnt();
10201 chain->incActiveTrackCnt();
10202 }
10203
Andy Hungc2b11cb2020-04-22 09:04:01 -070010204 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010205 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010206
10207 if (mActiveTracks.size() == 1) {
10208 ret = exitStandby_l();
10209 }
10210
Eric Laurent6acd1d42017-01-04 14:23:29 -080010211 broadcast_l();
10212
Eric Laurentdda206a2022-07-08 17:28:35 +020010213 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010214
Eric Laurentdda206a2022-07-08 17:28:35 +020010215 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010216}
10217
Andy Hung71742ab2023-07-07 13:47:37 -070010218status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010219{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010220 ALOGV("%s handle %d", __FUNCTION__, handle);
10221
10222 if (mHalStream == 0) {
10223 return NO_INIT;
10224 }
10225
Eric Laurenta54f1282017-07-01 19:39:32 -070010226 if (handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +000010227 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -070010228 return NO_ERROR;
10229 }
10230
Eric Laurent331679c2018-04-16 17:03:16 -070010231 Mutex::Autolock _l(mLock);
10232
Andy Hung3ff4b552023-06-26 19:20:57 -070010233 sp<IAfMmapTrack> track;
10234 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010235 if (handle == t->portId()) {
10236 track = t;
10237 break;
10238 }
10239 }
10240 if (track == 0) {
10241 return BAD_VALUE;
10242 }
10243
10244 mActiveTracks.remove(track);
jiabincfc10a42022-06-15 19:26:01 +000010245 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010246
Eric Laurent331679c2018-04-16 17:03:16 -070010247 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010248 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010249 AudioSystem::stopOutput(track->portId());
10250 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010251 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010252 AudioSystem::stopInput(track->portId());
10253 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010254 }
Eric Laurent331679c2018-04-16 17:03:16 -070010255 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010256
Andy Hungbd72c542023-06-20 18:56:17 -070010257 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010258 if (chain != 0) {
10259 chain->decActiveTrackCnt();
10260 chain->decTrackCnt();
10261 }
10262
Eric Laurentdda206a2022-07-08 17:28:35 +020010263 if (mActiveTracks.isEmpty()) {
10264 mHalStream->stop();
10265 }
10266
Eric Laurent6acd1d42017-01-04 14:23:29 -080010267 broadcast_l();
10268
Eric Laurent6acd1d42017-01-04 14:23:29 -080010269 return NO_ERROR;
10270}
10271
Andy Hung71742ab2023-07-07 13:47:37 -070010272status_t MmapThread::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010273{
10274 ALOGV("%s", __FUNCTION__);
10275
10276 if (mHalStream == 0) {
10277 return NO_INIT;
10278 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010279 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010280 return INVALID_OPERATION;
10281 }
10282 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010283 if (!mStandby) {
10284 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010285 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010286 mStandby = true;
10287 }
Eric Laurent18b57012017-02-13 16:23:52 -080010288 releaseWakeLock();
10289 return NO_ERROR;
10290}
10291
Andy Hung71742ab2023-07-07 13:47:37 -070010292status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010293 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10294 return INVALID_OPERATION;
10295}
Eric Laurent6acd1d42017-01-04 14:23:29 -080010296
Andy Hung71742ab2023-07-07 13:47:37 -070010297void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010298{
10299 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10300 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10301 mFormat = mHALFormat;
10302 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10303 result = mHalStream->getFrameSize(&mFrameSize);
10304 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010305 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10306 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010307 result = mHalStream->getBufferSize(&mBufferSize);
10308 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10309 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010310
Andy Hungcf10d742020-04-28 15:38:24 -070010311 // TODO: make a readHalParameters call?
10312 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010313 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
10314 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
10315 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10316 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10317 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10318 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10319 /*
10320 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10321 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10322 (int32_t)mHapticChannelMask)
10323 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10324 (int32_t)mHapticChannelCount)
10325 */
10326 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
10327 formatToString(mHALFormat).c_str())
10328 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10329 (int32_t)mFrameCount) // sic - added HAL
10330 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010331}
10332
Andy Hung71742ab2023-07-07 13:47:37 -070010333bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010334{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010335 checkSilentMode_l();
10336
10337 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10338
10339 while (!exitPending())
10340 {
Andy Hungbd72c542023-06-20 18:56:17 -070010341 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010342
Andy Hung13850be2019-03-14 11:33:09 -070010343 { // under Thread lock
10344 Mutex::Autolock _l(mLock);
10345
Eric Laurent6acd1d42017-01-04 14:23:29 -080010346 if (mSignalPending) {
10347 // A signal was raised while we were unlocked
10348 mSignalPending = false;
10349 } else {
10350 if (mConfigEvents.isEmpty()) {
10351 // we're about to wait, flush the binder command buffer
10352 IPCThreadState::self()->flushCommands();
10353
10354 if (exitPending()) {
10355 break;
10356 }
10357
Eric Laurent6acd1d42017-01-04 14:23:29 -080010358 // wait until we have something to do...
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010359 ALOGV("%s going to sleep", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010360 mWaitWorkCV.wait(mLock);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010361 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010362
10363 checkSilentMode_l();
10364
10365 continue;
10366 }
10367 }
10368
10369 processConfigEvents_l();
10370
10371 processVolume_l();
10372
10373 checkInvalidTracks_l();
10374
10375 mActiveTracks.updatePowerState(this);
10376
Kevin Rocard069c2712018-03-29 19:09:14 -070010377 updateMetadata_l();
10378
Eric Laurent6acd1d42017-01-04 14:23:29 -080010379 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010380 } // release Thread lock
10381
Eric Laurent6acd1d42017-01-04 14:23:29 -080010382 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010383 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010384 }
Andy Hung13850be2019-03-14 11:33:09 -070010385
10386 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010387 unlockEffectChains(effectChains);
10388 // Effect chains will be actually deleted here if they were removed from
10389 // mEffectChains list during mixing or effects processing
10390 }
10391
10392 threadLoop_exit();
10393
10394 if (!mStandby) {
10395 threadLoop_standby();
10396 mStandby = true;
10397 }
10398
Eric Laurent6acd1d42017-01-04 14:23:29 -080010399 ALOGV("Thread %p type %d exiting", this, mType);
10400 return false;
10401}
10402
10403// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -070010404bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010405 status_t& status)
10406{
10407 AudioParameter param = AudioParameter(keyValuePair);
10408 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010409 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010410 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010411 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010412 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010413 if (sendToHal) {
10414 status = mHalStream->setParameters(keyValuePair);
10415 } else {
10416 status = NO_ERROR;
10417 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010418
10419 return false;
10420}
10421
Andy Hung71742ab2023-07-07 13:47:37 -070010422String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010423{
10424 Mutex::Autolock _l(mLock);
10425 String8 out_s8;
10426 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10427 return out_s8;
10428 }
Andy Hung71ba4b32022-10-06 12:09:49 -070010429 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010430}
10431
Andy Hung71742ab2023-07-07 13:47:37 -070010432void MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010433 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010434 sp<AudioIoDescriptor> desc;
10435 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010436 switch (event) {
10437 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010438 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010439 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010440 isInput = true;
10441 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010442 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010443 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010444 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010445 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10446 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010447 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010448 case AUDIO_INPUT_CLOSED:
10449 case AUDIO_OUTPUT_CLOSED:
10450 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010451 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010452 break;
10453 }
Andy Hung2cbc2722023-07-17 17:05:00 -070010454 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010455}
10456
Andy Hung71742ab2023-07-07 13:47:37 -070010457status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010458 audio_patch_handle_t *handle)
Andy Hung71ba4b32022-10-06 12:09:49 -070010459NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010460{
10461 status_t status = NO_ERROR;
10462
10463 // store new device and send to effects
10464 audio_devices_t type = AUDIO_DEVICE_NONE;
10465 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010466 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10467 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10468 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010469 if (isOutput()) {
10470 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010471 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10472 && !mAudioHwDev->supportsAudioPatches(),
10473 "Enumerated device type(%#x) must not be used "
10474 "as it does not support audio patches",
10475 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010476 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung71ba4b32022-10-06 12:09:49 -070010477 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10478 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010479 }
10480 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010481 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010482 } else {
10483 type = patch->sources[0].ext.device.type;
10484 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010485 numDevices = mPatch.num_sources;
10486 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010487 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010488 }
10489
10490 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010491 if (isOutput()) {
10492 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10493 } else {
10494 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10495 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010496 }
10497
jiabinc52b1ff2019-10-31 17:20:42 -070010498 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010499 // store new source and send to effects
10500 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10501 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10502 for (size_t i = 0; i < mEffectChains.size(); i++) {
10503 mEffectChains[i]->setAudioSource_l(mAudioSource);
10504 }
10505 }
10506 }
10507
10508 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010509 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10510 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010511 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010512 audio_port_config port;
10513 std::optional<audio_source_t> source;
10514 if (isOutput()) {
10515 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010516 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010517 port = patch->sources[0];
10518 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010519 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010520 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010521 *handle = AUDIO_PATCH_HANDLE_NONE;
10522 }
10523
jiabinc52b1ff2019-10-31 17:20:42 -070010524 if (numDevices == 0 || mDeviceId != deviceId) {
10525 if (isOutput()) {
10526 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10527 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010528 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010529 } else {
10530 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10531 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10532 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010533 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010534 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010535 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010536 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -070010537 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010538 }
jiabinc52b1ff2019-10-31 17:20:42 -070010539 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010540 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010541 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010542 // Force meteadata update after a route change
10543 mActiveTracks.setHasChanged();
10544
Eric Laurent6acd1d42017-01-04 14:23:29 -080010545 return status;
10546}
10547
Andy Hung71742ab2023-07-07 13:47:37 -070010548status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010549{
10550 status_t status = NO_ERROR;
10551
jiabinc52b1ff2019-10-31 17:20:42 -070010552 mPatch = audio_patch{};
10553 mOutDeviceTypeAddrs.clear();
10554 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010555
10556 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10557 supportsAudioPatches : false;
10558
10559 if (supportsAudioPatches) {
10560 status = mHalDevice->releaseAudioPatch(handle);
10561 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010562 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010563 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010564 // Force meteadata update after a route change
10565 mActiveTracks.setHasChanged();
10566
Eric Laurent6acd1d42017-01-04 14:23:29 -080010567 return status;
10568}
10569
Andy Hung71742ab2023-07-07 13:47:37 -070010570void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010571{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010572 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010573 if (isOutput()) {
10574 config->role = AUDIO_PORT_ROLE_SOURCE;
10575 config->ext.mix.hw_module = mAudioHwDev->handle();
10576 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10577 } else {
10578 config->role = AUDIO_PORT_ROLE_SINK;
10579 config->ext.mix.hw_module = mAudioHwDev->handle();
10580 config->ext.mix.usecase.source = mAudioSource;
10581 }
10582}
10583
Andy Hung71742ab2023-07-07 13:47:37 -070010584status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010585{
10586 audio_session_t session = chain->sessionId();
10587
10588 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10589 // Attach all tracks with same session ID to this chain.
10590 // indicate all active tracks in the chain
Andy Hung3ff4b552023-06-26 19:20:57 -070010591 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010592 if (session == track->sessionId()) {
10593 chain->incTrackCnt();
10594 chain->incActiveTrackCnt();
10595 }
10596 }
10597
10598 chain->setThread(this);
10599 chain->setInBuffer(nullptr);
10600 chain->setOutBuffer(nullptr);
10601 chain->syncHalEffectsState();
10602
10603 mEffectChains.add(chain);
10604 checkSuspendOnAddEffectChain_l(chain);
10605 return NO_ERROR;
10606}
10607
Andy Hung71742ab2023-07-07 13:47:37 -070010608size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010609{
10610 audio_session_t session = chain->sessionId();
10611
10612 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10613
10614 for (size_t i = 0; i < mEffectChains.size(); i++) {
10615 if (chain == mEffectChains[i]) {
10616 mEffectChains.removeAt(i);
10617 // detach all active tracks from the chain
10618 // detach all tracks with same session ID from this chain
Andy Hung3ff4b552023-06-26 19:20:57 -070010619 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010620 if (session == track->sessionId()) {
10621 chain->decActiveTrackCnt();
10622 chain->decTrackCnt();
10623 }
10624 }
10625 break;
10626 }
10627 }
10628 return mEffectChains.size();
10629}
10630
Andy Hung71742ab2023-07-07 13:47:37 -070010631void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010632{
10633 mHalStream->standby();
10634}
10635
Andy Hung71742ab2023-07-07 13:47:37 -070010636void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010637{
Phil Burk7dce7282017-09-27 13:51:41 -070010638 // Do not call callback->onTearDown() because it is redundant for thread exit
10639 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010640}
10641
Andy Hung71742ab2023-07-07 13:47:37 -070010642status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010643{
10644 return BAD_VALUE;
10645}
10646
Andy Hung71742ab2023-07-07 13:47:37 -070010647bool MmapThread::isValidSyncEvent(
10648 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010649{
10650 return false;
10651}
10652
Andy Hung71742ab2023-07-07 13:47:37 -070010653status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010654 const effect_descriptor_t *desc, audio_session_t sessionId)
10655{
10656 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010657 if (audio_is_global_session(sessionId)) {
10658 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010659 desc->name, mThreadName);
10660 return BAD_VALUE;
10661 }
10662
10663 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10664 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10665 desc->name);
10666 return BAD_VALUE;
10667 }
10668 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010669 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10670 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010671 return BAD_VALUE;
10672 }
10673
10674 // Only allow effects without processing load or latency
10675 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10676 return BAD_VALUE;
10677 }
10678
Andy Hungbd72c542023-06-20 18:56:17 -070010679 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010680 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10681 return BAD_VALUE;
10682 }
10683
Eric Laurent6acd1d42017-01-04 14:23:29 -080010684 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010685}
10686
Andy Hung71742ab2023-07-07 13:47:37 -070010687void MmapThread::checkInvalidTracks_l()
Andy Hung71ba4b32022-10-06 12:09:49 -070010688NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010689{
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010690 sp<MmapStreamCallback> callback;
Andy Hung3ff4b552023-06-26 19:20:57 -070010691 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010692 if (track->isInvalid()) {
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010693 callback = mCallback.promote();
10694 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10695 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
Eric Laurent331679c2018-04-16 17:03:16 -070010696 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010697 }
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010698 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010699 }
10700 }
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010701 if (callback != 0) {
10702 mLock.unlock();
10703 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10704 mLock.lock();
10705 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010706}
10707
Andy Hung71742ab2023-07-07 13:47:37 -070010708void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010709{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010710 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10711 mAttr.content_type, mAttr.usage, mAttr.source);
10712 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010713 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010714 dprintf(fd, " No active clients\n");
10715 }
10716}
10717
Andy Hung71742ab2023-07-07 13:47:37 -070010718void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010719{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010720 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010721 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010722 dprintf(fd, " %zu Tracks\n", numtracks);
10723 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010724 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010725 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010726 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010727 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -070010728 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010729 result.append(prefix);
10730 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010731 }
10732 } else {
10733 dprintf(fd, "\n");
10734 }
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010735 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010736}
10737
Andy Hung71742ab2023-07-07 13:47:37 -070010738/* static */
10739sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung2cbc2722023-07-17 17:05:00 -070010740 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung71742ab2023-07-07 13:47:37 -070010741 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -070010742 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -070010743}
10744
10745MmapPlaybackThread::MmapPlaybackThread(
Andy Hung2cbc2722023-07-17 17:05:00 -070010746 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010747 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -070010748 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010749 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010750 mStreamVolume(1.0),
10751 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010752 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010753{
10754 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10755 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung2cbc2722023-07-17 17:05:00 -070010756 mMasterVolume = afThreadCallback->masterVolume_l();
10757 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010758 if (mAudioHwDev) {
10759 if (mAudioHwDev->canSetMasterVolume()) {
10760 mMasterVolume = 1.0;
10761 }
10762
10763 if (mAudioHwDev->canSetMasterMute()) {
10764 mMasterMute = false;
10765 }
10766 }
10767}
10768
Andy Hung71742ab2023-07-07 13:47:37 -070010769void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010770 audio_stream_type_t streamType,
10771 audio_session_t sessionId,
10772 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010773 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010774 audio_port_handle_t portId)
10775{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010776 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010777 mStreamType = streamType;
10778}
10779
Andy Hung71742ab2023-07-07 13:47:37 -070010780AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010781{
10782 Mutex::Autolock _l(mLock);
10783 AudioStreamOut *output = mOutput;
10784 mOutput = NULL;
10785 return output;
10786}
10787
Andy Hung71742ab2023-07-07 13:47:37 -070010788void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010789{
10790 Mutex::Autolock _l(mLock);
10791 // Don't apply master volume in SW if our HAL can do it for us.
10792 if (mAudioHwDev &&
10793 mAudioHwDev->canSetMasterVolume()) {
10794 mMasterVolume = 1.0;
10795 } else {
10796 mMasterVolume = value;
10797 }
10798}
10799
Andy Hung71742ab2023-07-07 13:47:37 -070010800void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010801{
10802 Mutex::Autolock _l(mLock);
10803 // Don't apply master mute in SW if our HAL can do it for us.
10804 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10805 mMasterMute = false;
10806 } else {
10807 mMasterMute = muted;
10808 }
10809}
10810
Andy Hung71742ab2023-07-07 13:47:37 -070010811void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010812{
10813 Mutex::Autolock _l(mLock);
10814 if (stream == mStreamType) {
10815 mStreamVolume = value;
10816 broadcast_l();
10817 }
10818}
10819
Andy Hung71742ab2023-07-07 13:47:37 -070010820float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010821{
10822 Mutex::Autolock _l(mLock);
10823 if (stream == mStreamType) {
10824 return mStreamVolume;
10825 }
10826 return 0.0f;
10827}
10828
Andy Hung71742ab2023-07-07 13:47:37 -070010829void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010830{
10831 Mutex::Autolock _l(mLock);
10832 if (stream == mStreamType) {
10833 mStreamMute= muted;
10834 broadcast_l();
10835 }
10836}
10837
Andy Hung71742ab2023-07-07 13:47:37 -070010838void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010839{
10840 Mutex::Autolock _l(mLock);
10841 if (streamType == mStreamType) {
Andy Hung3ff4b552023-06-26 19:20:57 -070010842 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010843 track->invalidate();
10844 }
10845 broadcast_l();
10846 }
10847}
10848
Andy Hung71742ab2023-07-07 13:47:37 -070010849void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010850{
10851 Mutex::Autolock _l(mLock);
10852 bool trackMatch = false;
Andy Hung3ff4b552023-06-26 19:20:57 -070010853 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010854 if (portIds.find(track->portId()) != portIds.end()) {
10855 track->invalidate();
10856 trackMatch = true;
10857 portIds.erase(track->portId());
10858 }
10859 if (portIds.empty()) {
10860 break;
10861 }
10862 }
10863 if (trackMatch) {
10864 broadcast_l();
10865 }
10866}
10867
Andy Hung71742ab2023-07-07 13:47:37 -070010868void MmapPlaybackThread::processVolume_l()
Andy Hung71ba4b32022-10-06 12:09:49 -070010869NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080010870{
10871 float volume;
10872
10873 if (mMasterMute || mStreamMute) {
10874 volume = 0;
10875 } else {
10876 volume = mMasterVolume * mStreamVolume;
10877 }
10878
10879 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010880
10881 // Convert volumes from float to 8.24
10882 uint32_t vol = (uint32_t)(volume * (1 << 24));
10883
10884 // Delegate volume control to effect in track effect chain if needed
10885 // only one effect chain can be present on DirectOutputThread, so if
10886 // there is one, the track is connected to it
10887 if (!mEffectChains.isEmpty()) {
10888 mEffectChains[0]->setVolume_l(&vol, &vol);
10889 volume = (float)vol / (1 << 24);
10890 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010891 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010892 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10893 mHalVolFloat = volume; // HW volume control worked, so update value.
10894 mNoCallbackWarningCount = 0;
10895 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010896 sp<MmapStreamCallback> callback = mCallback.promote();
10897 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010898 mHalVolFloat = volume; // SW volume control worked, so update value.
10899 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010900 mLock.unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010901 callback->onVolumeChanged(volume);
Eric Laurent734046e2018-04-16 14:50:52 -070010902 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010903 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010904 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10905 ALOGW("Could not set MMAP stream volume: no volume callback!");
10906 mNoCallbackWarningCount++;
10907 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010908 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010909 }
Andy Hung3ff4b552023-06-26 19:20:57 -070010910 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010911 track->setMetadataHasChanged();
Andy Hung2cbc2722023-07-17 17:05:00 -070010912 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010913 /*muteState=*/{mMasterMute,
10914 mStreamVolume == 0.f,
10915 mStreamMute,
10916 // TODO(b/241533526): adjust logic to include mute from AppOps
10917 false /*muteFromPlaybackRestricted*/,
10918 false /*muteFromClientVolume*/,
10919 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010920 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010921 }
10922}
10923
Andy Hung71742ab2023-07-07 13:47:37 -070010924ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070010925{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010926 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010010927 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010928 }
10929 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung3ff4b552023-06-26 19:20:57 -070010930 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070010931 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010932 playback_track_metadata_v7_t trackMetadata;
10933 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010934 .usage = track->attributes().usage,
10935 .content_type = track->attributes().content_type,
10936 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010937 };
10938 trackMetadata.channel_mask = track->channelMask(),
10939 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10940 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010941 }
10942 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010010943
10944 MetadataUpdate change;
10945 change.playbackMetadataUpdate = metadata.tracks;
10946 return change;
10947};
Kevin Rocard069c2712018-03-29 19:09:14 -070010948
Andy Hung71742ab2023-07-07 13:47:37 -070010949void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010950{
10951 if (!mMasterMute) {
10952 char value[PROPERTY_VALUE_MAX];
10953 if (property_get("ro.audio.silent", value, "0") > 0) {
10954 char *endptr;
10955 unsigned long ul = strtoul(value, &endptr, 0);
10956 if (*endptr == '\0' && ul != 0) {
10957 ALOGD("Silence is golden");
10958 // The setprop command will not allow a property to be changed after
10959 // the first time it is set, so we don't have to worry about un-muting.
10960 setMasterMute_l(true);
10961 }
10962 }
10963 }
10964}
10965
Andy Hung71742ab2023-07-07 13:47:37 -070010966void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010967{
10968 MmapThread::toAudioPortConfig(config);
10969 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10970 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10971 config->flags.output = mOutput->flags;
10972 }
10973}
10974
Andy Hung71742ab2023-07-07 13:47:37 -070010975status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung4989d312023-06-29 21:19:25 -070010976 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070010977{
10978 if (mOutput == nullptr) {
10979 return NO_INIT;
10980 }
10981 struct timespec timestamp;
10982 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10983 if (status == NO_ERROR) {
10984 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10985 }
10986 return status;
10987}
10988
Andy Hung71742ab2023-07-07 13:47:37 -070010989status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010990 // Send to MelProcessor for sound dose measurement.
10991 auto processor = mMelProcessor.load();
10992 if (processor) {
10993 processor->process(buffer, frameCount * mFrameSize);
10994 }
10995
jiabinfc791ee2023-02-15 19:43:40 +000010996 return NO_ERROR;
10997}
10998
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010999// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -070011000void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011001 const sp<audio_utils::MelProcessor>& processor)
11002{
11003 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011004 mMelProcessor.store(processor);
11005 if (processor) {
11006 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011007 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011008
11009 // no need to update output format for MMapPlaybackThread since it is
11010 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011011}
11012
11013// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung71742ab2023-07-07 13:47:37 -070011014void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011015{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011016 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11017 auto melProcessor = mMelProcessor.load();
11018 if (melProcessor != nullptr) {
11019 melProcessor->pause();
11020 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011021}
11022
Andy Hung71742ab2023-07-07 13:47:37 -070011023void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011024{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011025 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011026
Glenn Kastend3bb6452016-12-05 18:14:37 -080011027 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
11028 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011029 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11030}
11031
Andy Hung71742ab2023-07-07 13:47:37 -070011032/* static */
11033sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung2cbc2722023-07-17 17:05:00 -070011034 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung71742ab2023-07-07 13:47:37 -070011035 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -070011036 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -070011037}
11038
11039MmapCaptureThread::MmapCaptureThread(
Andy Hung2cbc2722023-07-17 17:05:00 -070011040 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011041 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -070011042 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011043 mInput(input)
11044{
11045 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11046 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11047}
11048
Andy Hung71742ab2023-07-07 13:47:37 -070011049status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011050{
Phil Burkf054fc32018-12-06 09:45:59 -080011051 {
11052 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011053 if (mInput != nullptr && mInput->stream != nullptr) {
11054 mInput->stream->setGain(1.0f);
11055 }
11056 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011057 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011058}
11059
Andy Hung71742ab2023-07-07 13:47:37 -070011060AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011061{
11062 Mutex::Autolock _l(mLock);
11063 AudioStreamIn *input = mInput;
11064 mInput = NULL;
11065 return input;
11066}
Kevin Rocard069c2712018-03-29 19:09:14 -070011067
Andy Hung71742ab2023-07-07 13:47:37 -070011068void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011069{
11070 bool changed = false;
11071 bool silenced = false;
11072
11073 sp<MmapStreamCallback> callback = mCallback.promote();
11074 if (callback == 0) {
11075 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11076 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11077 mNoCallbackWarningCount++;
11078 }
11079 }
11080
11081 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11082 // track is silenced and unmute otherwise
11083 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11084 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11085 changed = true;
11086 silenced = mActiveTracks[i]->isSilenced_l();
11087 }
11088 }
11089
11090 if (changed) {
11091 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11092 }
11093}
11094
Andy Hung71742ab2023-07-07 13:47:37 -070011095ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011096{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011097 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011098 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011099 }
11100 StreamInHalInterface::SinkMetadata metadata;
Andy Hung3ff4b552023-06-26 19:20:57 -070011101 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011102 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011103 record_track_metadata_v7_t trackMetadata;
11104 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011105 .source = track->attributes().source,
11106 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011107 };
11108 trackMetadata.channel_mask = track->channelMask(),
11109 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11110 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011111 }
11112 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011113 MetadataUpdate change;
11114 change.recordMetadataUpdate = metadata.tracks;
11115 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011116}
11117
Andy Hung71742ab2023-07-07 13:47:37 -070011118void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011119{
11120 Mutex::Autolock _l(mLock);
11121 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011122 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011123 mActiveTracks[i]->setSilenced_l(silenced);
11124 broadcast_l();
11125 }
11126 }
jiabincfc10a42022-06-15 19:26:01 +000011127 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011128}
11129
Andy Hung71742ab2023-07-07 13:47:37 -070011130void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011131{
11132 MmapThread::toAudioPortConfig(config);
11133 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11134 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11135 config->flags.input = mInput->flags;
11136 }
11137}
11138
Andy Hung71742ab2023-07-07 13:47:37 -070011139status_t MmapCaptureThread::getExternalPosition(
Andy Hung4989d312023-06-29 21:19:25 -070011140 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011141{
11142 if (mInput == nullptr) {
11143 return NO_INIT;
11144 }
11145 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11146}
11147
jiabinc658e452022-10-21 20:52:21 +000011148// ----------------------------------------------------------------------------
11149
Andy Hung71742ab2023-07-07 13:47:37 -070011150/* static */
11151sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung2cbc2722023-07-17 17:05:00 -070011152 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -070011153 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -070011154 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -070011155}
11156
Andy Hung2cbc2722023-07-17 17:05:00 -070011157BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011158 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -070011159 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011160
Andy Hung71742ab2023-07-07 13:47:37 -070011161PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -070011162 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011163 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11164 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011165 float volumeLeft = 1.0f;
11166 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011167 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11168 const int trackId = mActiveTracks[0]->id();
11169 mAudioMixer->setParameter(
11170 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11171 mAudioMixer->setParameter(
11172 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11173 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011174 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011175 mIsBitPerfect = true;
11176 } else {
11177 mIsBitPerfect = false;
11178 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11179 // active.
11180 for (const auto& track : mActiveTracks) {
11181 const int trackId = track->id();
11182 mAudioMixer->setParameter(
11183 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11184 }
11185 }
jiabin76d94692022-12-15 21:51:21 +000011186 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11187 mVolumeLeft = volumeLeft;
11188 mVolumeRight = volumeRight;
11189 setVolumeForOutput_l(volumeLeft, volumeRight);
11190 }
jiabinc658e452022-10-21 20:52:21 +000011191 return result;
11192}
11193
Andy Hung71742ab2023-07-07 13:47:37 -070011194void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011195 MixerThread::threadLoop_mix();
11196 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11197}
11198
Glenn Kasten63238ef2015-03-02 15:50:29 -080011199} // namespace android