blob: d07e107287ab9a9b789a4b6e6761c4880dc84f82 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
Vlad Popab042ee62022-10-20 18:05:00 +020020// #define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <memory>
Andy Hungb68f5eb2019-12-03 16:49:17 -080027#include <sstream>
Eric Tan7b651152018-07-13 10:17:19 -070028#include <string>
Glenn Kastenad8510a2015-02-17 16:24:07 -080029#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080030#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080031#include <sys/syscall.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070032#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080033#include <cutils/properties.h>
Vlad Popae8d99472022-06-30 16:02:48 +020034#include <binder/PersistableBundle.h>
jiabinc52b1ff2019-10-31 17:20:42 -070035#include <media/AudioContainers.h>
36#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070037#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070038#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080039#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070040#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080041#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080042#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043
44#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070045#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010046#include <audio_utils/Balance.h>
Vlad Popab042ee62022-10-20 18:05:00 +020047#include <audio_utils/MelProcessor.h>
jiabinf6eb4c32020-02-25 14:06:25 -080048#include <audio_utils/Metadata.h>
jiabin245cdd92018-12-07 17:55:15 -080049#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080050#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080051#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080052#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070053#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070054#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070055#include <system/audio_effects/effect_aec.h>
Eric Laurentb3f315a2021-07-13 15:09:05 +020056#include <system/audio_effects/effect_downmix.h>
57#include <system/audio_effects/effect_ns.h>
Eric Laurent1c5e2e32021-08-18 18:50:28 +020058#include <system/audio_effects/effect_spatializer.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070059#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080060
61// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070062#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080063#include <media/nbaio/AudioStreamOutSink.h>
64#include <media/nbaio/MonoPipe.h>
65#include <media/nbaio/MonoPipeReader.h>
66#include <media/nbaio/Pipe.h>
67#include <media/nbaio/PipeReader.h>
68#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080069#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070070#include <mediautils/Process.h>
Eric Laurent81784c32012-11-19 14:55:58 -080071
Mikhail Naganov2996f672019-04-18 12:29:59 -070072#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080073#include <powermanager/PowerManager.h>
74
Kevin Rocard7588ff42018-01-08 11:11:30 -080075#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070076#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080077
Eric Laurent81784c32012-11-19 14:55:58 -080078#include "AudioFlinger.h"
Andy Hung4b17e882023-07-07 13:47:37 -070079#include "Threads.h"
80
Andy Hungab7ef302018-05-15 19:35:29 -070081#include <mediautils/SchedulingPolicyService.h>
82#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080083
Eric Laurent81784c32012-11-19 14:55:58 -080084#ifdef ADD_BATTERY_DATA
85#include <media/IMediaPlayerService.h>
86#include <media/IMediaDeathNotifier.h>
87#endif
88
Eric Laurent81784c32012-11-19 14:55:58 -080089#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070090#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080091#include <cpustats/ThreadCpuUsage.h>
92#endif
93
Andy Hungd69d9f12023-05-23 17:36:46 -070094#include <fastpath/AutoPark.h>
Glenn Kastenc05b8d72016-03-24 09:48:17 -070095
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080096#include <pthread.h>
Andy Hungf2f5d642023-07-18 20:54:44 -070097#include <afutils/DumpTryLock.h>
Andy Hungc3af0112023-07-19 16:56:19 -070098#include <afutils/Permission.h>
Andy Hung0077d8c2023-05-24 11:53:47 -070099#include <afutils/TypedLogger.h>
Andy Hung76cb9152023-07-20 21:23:42 -0700100#include <afutils/Vibrator.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800101
Eric Laurent81784c32012-11-19 14:55:58 -0800102// ----------------------------------------------------------------------------
103
104// Note: the following macro is used for extremely verbose logging message. In
105// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
106// 0; but one side effect of this is to turn all LOGV's as well. Some messages
107// are so verbose that we want to suppress them even when we have ALOG_ASSERT
108// turned on. Do not uncomment the #def below unless you really know what you
109// are doing and want to see all of the extremely verbose messages.
110//#define VERY_VERY_VERBOSE_LOGGING
111#ifdef VERY_VERY_VERBOSE_LOGGING
112#define ALOGVV ALOGV
113#else
114#define ALOGVV(a...) do { } while(0)
115#endif
116
Andy Hung6770c6f2015-04-07 13:43:36 -0700117// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700118#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700119
Andy Hung6770c6f2015-04-07 13:43:36 -0700120template <typename T>
121static inline T min(const T& a, const T& b)
122{
123 return a < b ? a : b;
124}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700125
Eric Laurent81784c32012-11-19 14:55:58 -0800126namespace android {
127
Andy Hung4b17e882023-07-07 13:47:37 -0700128using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700129using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000130using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700131
Eric Laurent81784c32012-11-19 14:55:58 -0800132// retry counts for buffer fill timeout
133// 50 * ~20msecs = 1 second
134static const int8_t kMaxTrackRetries = 50;
135static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700136
Eric Laurent81784c32012-11-19 14:55:58 -0800137// allow less retry attempts on direct output thread.
138// direct outputs can be a scarce resource in audio hardware and should
139// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700140// Notes:
141// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
142// in case the data write is bursty for the AudioTrack. The application
143// should endeavor to write at least once every kMaxTrackRetriesDirectMs
144// to prevent an underrun situation. If the data is bursty, then
145// the application can also throttle the data sent to be even.
146// 2) For compressed audio data, any data present in the AudioTrack buffer
147// will be sent and reset the retry count. This delivers data as
148// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
149// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
150// of data to be available, then any remaining data is delivered.
151// This is required to ensure the last bit of data is delivered before underrun.
152//
153// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
154// or the size of the HAL period for proportional / linear PCM tracks.
155static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800156
157// don't warn about blocked writes or record buffer overflows more often than this
158static const nsecs_t kWarningThrottleNs = seconds(5);
159
160// RecordThread loop sleep time upon application overrun or audio HAL read error
161static const int kRecordThreadSleepUs = 5000;
162
Eric Laurent10351942014-05-08 18:49:52 -0700163// maximum time to wait in sendConfigEvent_l() for a status to be received
164static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800165
166// minimum sleep time for the mixer thread loop when tracks are active but in underrun
167static const uint32_t kMinThreadSleepTimeUs = 5000;
168// maximum divider applied to the active sleep time in the mixer thread loop
169static const uint32_t kMaxThreadSleepTimeShift = 2;
170
Andy Hung09a50072014-02-27 14:30:47 -0800171// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700172// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800173static const uint32_t kMinNormalSinkBufferSizeMs = 20;
174// maximum normal sink buffer size
175static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800176
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700177// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
178// FIXME This should be based on experimentally observed scheduling jitter
179static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
180
Eric Laurent972a1732013-09-04 09:42:59 -0700181// Offloaded output thread standby delay: allows track transition without going to standby
182static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
183
Eric Laurent51716182016-02-29 18:00:56 -0800184// Direct output thread minimum sleep time in idle or active(underrun) state
185static const nsecs_t kDirectMinSleepTimeUs = 10000;
186
Brian Lindahl65e90012022-07-27 18:01:07 +0200187// Minimum amount of time between checking to see if the timestamp is advancing
188// for underrun detection. If we check too frequently, we may not detect a
189// timestamp update and will falsely detect underrun.
190static const nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1000;
191
Glenn Kasten1b291842016-07-18 14:55:21 -0700192// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
193// balance between power consumption and latency, and allows threads to be scheduled reliably
194// by the CFS scheduler.
195// FIXME Express other hardcoded references to 20ms with references to this constant and move
196// it appropriately.
197#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800198
Eric Laurent81784c32012-11-19 14:55:58 -0800199// Whether to use fast mixer
200static const enum {
201 FastMixer_Never, // never initialize or use: for debugging only
202 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
203 // normal mixer multiplier is 1
204 FastMixer_Static, // initialize if needed, then use all the time if initialized,
205 // multiplier is calculated based on min & max normal mixer buffer size
206 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
207 // multiplier is calculated based on min & max normal mixer buffer size
208 // FIXME for FastMixer_Dynamic:
209 // Supporting this option will require fixing HALs that can't handle large writes.
210 // For example, one HAL implementation returns an error from a large write,
211 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
212 // We could either fix the HAL implementations, or provide a wrapper that breaks
213 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
214} kUseFastMixer = FastMixer_Static;
215
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700216// Whether to use fast capture
217static const enum {
218 FastCapture_Never, // never initialize or use: for debugging only
219 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
220 FastCapture_Static, // initialize if needed, then use all the time if initialized
221} kUseFastCapture = FastCapture_Static;
222
Eric Laurent81784c32012-11-19 14:55:58 -0800223// Priorities for requestPriority
224static const int kPriorityAudioApp = 2;
225static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700226static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800227
Glenn Kastenea38ee72016-04-18 11:08:01 -0700228// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
229// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
230// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700231
232// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800233static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800234
Glenn Kasten03490092014-05-27 12:30:54 -0700235// The minimum and maximum allowed values
236static const int kFastTrackMultiplierMin = 1;
237static const int kFastTrackMultiplierMax = 2;
238
239// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
240static int sFastTrackMultiplier = kFastTrackMultiplier;
241
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700242// See Thread::readOnlyHeap().
243// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
244// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
245// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700246static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700247
Andy Hungd58c4732023-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 Hungd21a2ab2023-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 Naganovf53e1822022-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 Hung920f6572022-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",
566 title.string(),
567 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 Hung4b17e882023-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 Hung7535ed92023-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 Hung7535ed92023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-07-07 13:47:37 -0700690status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800691{
Eric Laurent81784c32012-11-19 14:55:58 -0800692 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
693 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 Hung4b17e882023-07-07 13:47:37 -0700700status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-07-07 13:47:37 -0700842void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-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 Hung4b17e882023-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",
877 data->mKeyValuePairs.string());
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 Laurent68a40a82022-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 Hung4b17e882023-07-07 13:47:37 -07001016void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-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 Hungf2f5d642023-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 Hung4b17e882023-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,
Marco Nelissenb2208842014-02-07 14:00:50 -08001064 channelMaskToString(mChannelMask, mType != RECORD).string());
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 Hung4b17e882023-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 Hung116bc262023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung116bc262023-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 Hung4b17e882023-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 Hung116bc262023-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 Hung4b17e882023-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 Hung116bc262023-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 Hung4b17e882023-07-07 13:47:37 -07001384void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001385 audio_session_t sessionId,
Andy Hung920f6572022-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 Hung4b17e882023-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 Hung116bc262023-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 Hung4b17e882023-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 Hung116bc262023-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 Hung4b17e882023-07-07 13:47:37 -07001609sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-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 Hung116bc262023-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 Hung116bc262023-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 Hung116bc262023-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 Hung7535ed92023-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 Hung7535ed92023-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 Hung7535ed92023-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 Hung116bc262023-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 Hung4b17e882023-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 Hung116bc262023-06-20 18:56:17 -07001718 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001719 {
1720 Mutex::Autolock _l(mLock);
Andy Hung116bc262023-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 Hung7535ed92023-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 Hung4b17e882023-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 Hung7535ed92023-07-17 17:05:00 -07001755 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001756 }
1757 }
1758}
1759
Andy Hung4b17e882023-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 Hung4b17e882023-07-07 13:47:37 -07001767sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung3e4c8742023-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 Hung4b17e882023-07-07 13:47:37 -07001774sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung3e4c8742023-06-29 21:19:25 -07001775 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001776{
Andy Hung116bc262023-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 Hung4b17e882023-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 Hung116bc262023-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 Hung4b17e882023-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 Hung116bc262023-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 Hung116bc262023-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 Hung7535ed92023-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 Hung4b17e882023-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 Hung116bc262023-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 Hung4b17e882023-07-07 13:47:37 -07001853void ThreadBase::lockEffectChains_l(
Andy Hung116bc262023-06-20 18:56:17 -07001854 Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-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 Hung4b17e882023-07-07 13:47:37 -07001863void ThreadBase::unlockEffectChains(
Andy Hung116bc262023-06-20 18:56:17 -07001864 const Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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 Hung4b17e882023-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;
1904 config->format = mFormat;
1905 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 Hung4b17e882023-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 Hung4b17e882023-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;
Atneya Nair166663a2023-06-27 19:16:24 -07001934 track->beginBatteryAttribution();
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 Hung4b17e882023-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++;
Atneya Nair166663a2023-06-27 19:16:24 -07001948 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001949 // 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 Hung4b17e882023-07-07 13:47:37 -07001959void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001960 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001961 track->endBatteryAttribution();
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();
Andy Hungdae27702016-10-31 14:01:16 -07001968}
1969
1970template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001971void ThreadBase::ActiveTracks<T>::updatePowerState(
Andy Hung920f6572022-10-06 12:09:49 -07001972 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001973 // Updates ActiveTracks client uids to the thread wakelock.
1974 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1975 thread->updateWakeLockUids_l(getWakeLockUids());
1976 mLastActiveTracksGeneration = mActiveTracksGeneration;
1977 }
Andy Hungdae27702016-10-31 14:01:16 -07001978}
Eric Laurent83b88082014-06-20 18:31:16 -07001979
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001980template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001981bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001982 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001983 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001984
1985 for (const sp<T> &track : mActiveTracks) {
1986 // Do not short-circuit as all hasChanged states must be reset
1987 // as all the metadata are going to be sent
1988 hasChanged |= track->readAndClearHasChanged();
1989 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001990 return hasChanged;
1991}
1992
1993template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001994void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001995 const char *funcName, const sp<T> &track) const {
1996 if (mLocalLog != nullptr) {
1997 String8 result;
1998 track->appendDump(result, false /* active */);
1999 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
2000 }
2001}
2002
Andy Hung4b17e882023-07-07 13:47:37 -07002003void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002004{
2005 // Thread could be blocked waiting for async
2006 // so signal it to handle state changes immediately
2007 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2008 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2009 mSignalPending = true;
2010 mWaitWorkCV.broadcast();
2011}
2012
Andy Hungd0979812019-02-21 15:51:44 -08002013// Call only from threadLoop() or when it is idle.
2014// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hung4b17e882023-07-07 13:47:37 -07002015void ThreadBase::sendStatistics(bool force)
Andy Hungd0979812019-02-21 15:51:44 -08002016{
2017 // Do not log if we have no stats.
2018 // We choose the timestamp verifier because it is the most likely item to be present.
2019 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2020 if (nstats == 0) {
2021 return;
2022 }
2023
2024 // Don't log more frequently than once per 12 hours.
2025 // We use BOOTTIME to include suspend time.
2026 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2027 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2028 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2029 return;
2030 }
2031
2032 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2033 mLastRecordedTimeNs = timeNs;
2034
Ray Essickf27e9872019-12-07 06:28:46 -08002035 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002036
2037#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2038
2039 // thread configuration
2040 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2041 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2042 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2043 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2044 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2045 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2046 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07002047 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
2048 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002049
2050 // thread statistics
2051 if (mIoJitterMs.getN() > 0) {
2052 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2053 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2054 }
2055 if (mProcessTimeMs.getN() > 0) {
2056 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2057 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2058 }
2059 const auto tsjitter = mTimestampVerifier.getJitterMs();
2060 if (tsjitter.getN() > 0) {
2061 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2062 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2063 }
2064 if (mLatencyMs.getN() > 0) {
2065 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2066 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2067 }
Robert Wu06db0a32021-08-10 19:05:34 +00002068 if (mMonopipePipeDepthStats.getN() > 0) {
2069 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2070 mMonopipePipeDepthStats.getMean());
2071 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2072 mMonopipePipeDepthStats.getStdDev());
2073 }
Andy Hungd0979812019-02-21 15:51:44 -08002074
2075 item->selfrecord();
2076}
2077
Andy Hung4b17e882023-07-07 13:47:37 -07002078product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002079{
Andy Hung7535ed92023-07-17 17:05:00 -07002080 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002081 return PRODUCT_STRATEGY_NONE;
2082 }
2083 return AudioSystem::getStrategyForStream(stream);
2084}
2085
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002086// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07002087void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002088 const sp<audio_utils::MelProcessor>& /*processor*/)
2089{
2090 // Do nothing
2091 ALOGW("%s: ThreadBase does not support CSD", __func__);
2092}
2093
2094// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07002095void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002096{
2097 // Do nothing
2098 ALOGW("%s: ThreadBase does not support CSD", __func__);
2099}
2100
Eric Laurent81784c32012-11-19 14:55:58 -08002101// ----------------------------------------------------------------------------
2102// Playback
2103// ----------------------------------------------------------------------------
2104
Andy Hung7535ed92023-07-17 17:05:00 -07002105PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002106 AudioStreamOut* output,
2107 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002108 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002109 bool systemReady,
2110 audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07002111 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002112 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hungd21a2ab2023-07-20 21:44:14 -07002113 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002114 mMixerBuffer(NULL),
2115 mMixerBufferSize(0),
2116 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2117 mMixerBufferValid(false),
Andy Hungd21a2ab2023-07-20 21:44:14 -07002118 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002119 mEffectBuffer(NULL),
2120 mEffectBufferSize(0),
2121 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2122 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002123 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002124 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002125 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002126 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002127 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002128 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002129 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002130 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002131 mMixerStatus(MIXER_IDLE),
2132 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hungd58c4732023-07-20 21:31:38 -07002133 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002134 mBytesRemaining(0),
2135 mCurrentWriteLength(0),
2136 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002137 mWriteAckSequence(0),
2138 mDrainSequence(0),
Andy Hung1b6d46a2023-07-19 16:22:58 -07002139 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002140 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002141 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002142 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002143 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002144 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002145 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002146{
Glenn Kastend7dca052015-03-05 16:05:54 -08002147 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung7535ed92023-07-17 17:05:00 -07002148 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002149
2150 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2151 // it would be safer to explicitly pass initial masterVolume/masterMute as
2152 // parameter.
2153 //
2154 // If the HAL we are using has support for master volume or master mute,
2155 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2156 // and the mute set to false).
Andy Hung7535ed92023-07-17 17:05:00 -07002157 mMasterVolume = afThreadCallback->masterVolume_l();
2158 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002159 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002160 if (mOutput->audioHwDev->canSetMasterVolume()) {
2161 mMasterVolume = 1.0;
2162 }
2163
2164 if (mOutput->audioHwDev->canSetMasterMute()) {
2165 mMasterMute = false;
2166 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002167 mIsMsdDevice = strcmp(
2168 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002169 }
2170
Eric Laurentf1f22e72021-07-13 14:04:14 +02002171 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2172 mMixerChannelMask = mixerConfig->channel_mask;
2173 }
2174
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002175 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002176
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002177 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002178 && mMixerChannelMask != mChannelMask) {
2179 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2180 mChannelMask, mMixerChannelMask);
2181 }
2182
Andy Hungc8fddf32018-08-08 18:32:37 -07002183 // TODO: We may also match on address as well as device type for
2184 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002185 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002186 // TODO: This property should be ensure that only contains one single device type.
2187 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2188 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002189 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2190 : AUDIO_DEVICE_NONE));
2191 }
2192
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002193 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2194 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002195 mStreamTypes[stream].volume = 0.0f;
Andy Hung7535ed92023-07-17 17:05:00 -07002196 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002197 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002198 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002199 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2200 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002201 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2202 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002203}
2204
Andy Hung4b17e882023-07-07 13:47:37 -07002205PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002206{
Andy Hung7535ed92023-07-17 17:05:00 -07002207 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002208 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002209 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002210 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002211 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002212}
2213
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002214// Thread virtuals
2215
Andy Hung4b17e882023-07-07 13:47:37 -07002216void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002217{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002218 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002219 ALOGE("The stream is not open yet"); // This should not happen.
2220 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002221 // Callbacks take strong or weak pointers as a parameter.
2222 // Since PlaybackThread passes itself as a callback handler, it can only
2223 // be done outside of the constructor. Creating weak and especially strong
2224 // pointers to a refcounted object in its own constructor is strongly
2225 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2226 // Even if a function takes a weak pointer, it is possible that it will
2227 // need to convert it to a strong pointer down the line.
2228 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2229 mOutput->stream->setCallback(this) == OK) {
2230 mUseAsyncWrite = true;
Andy Hung4b17e882023-07-07 13:47:37 -07002231 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002232 }
2233
jiabinf6eb4c32020-02-25 14:06:25 -08002234 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002235 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002236 }
2237 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002238 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002239 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002240}
2241
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002242// ThreadBase virtuals
Andy Hung4b17e882023-07-07 13:47:37 -07002243void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002244{
2245 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002246 status_t result = mOutput->stream->exit();
2247 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002248}
2249
Andy Hung4b17e882023-07-07 13:47:37 -07002250void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002251{
Eric Laurent81784c32012-11-19 14:55:58 -08002252 String8 result;
2253
Marco Nelissenb2208842014-02-07 14:00:50 -08002254 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002255 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2256 const stream_type_t *st = &mStreamTypes[i];
2257 if (i > 0) {
2258 result.appendFormat(", ");
2259 }
2260 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2261 if (st->mute) {
2262 result.append("M");
2263 }
2264 }
2265 result.append("\n");
2266 write(fd, result.string(), result.length());
2267 result.clear();
2268
Eric Laurent81784c32012-11-19 14:55:58 -08002269 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2270 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002271 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002272 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002273
2274 size_t numtracks = mTracks.size();
2275 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002276 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002277 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002278 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002279 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002280 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002281 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002282 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002283 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002284 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002285 if (track != 0) {
2286 bool active = mActiveTracks.indexOf(track) >= 0;
2287 if (active) {
2288 numactiveseen++;
2289 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002290 result.append(prefix);
2291 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002292 }
2293 }
2294 } else {
2295 result.append("\n");
2296 }
2297 if (numactiveseen != numactive) {
2298 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002299 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002300 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002301 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002302 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002303 for (size_t i = 0; i < numactive; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002304 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002305 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002306 result.append(prefix);
2307 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002308 }
2309 }
2310 }
2311
2312 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002313}
2314
Andy Hung4b17e882023-07-07 13:47:37 -07002315void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002316{
Andy Hung04cb8f72020-03-20 13:44:33 -07002317 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002318 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002319 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2320 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002321 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2322 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2323 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2324 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002325 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002326 dprintf(fd, " Total writes: %d\n", mNumWrites);
2327 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2328 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2329 dprintf(fd, " Suspend count: %d\n", mSuspended);
2330 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2331 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2332 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2333 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002334 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002335 AudioStreamOut *output = mOutput;
2336 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002337 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002338 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002339 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2340 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2341 if (mPipeSink.get() != nullptr) {
2342 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2343 }
2344 if (output != nullptr) {
2345 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002346 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002347 }
Eric Laurent81784c32012-11-19 14:55:58 -08002348}
2349
Eric Laurent81784c32012-11-19 14:55:58 -08002350// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07002351sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002352 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002353 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002354 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002355 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002356 audio_format_t format,
2357 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002358 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002359 size_t *pNotificationFrameCount,
2360 uint32_t notificationsPerBuffer,
2361 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002362 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002363 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002364 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002365 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002366 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002367 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002368 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002369 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002370 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002371 bool isSpatialized,
2372 bool isBitPerfect)
Eric Laurent81784c32012-11-19 14:55:58 -08002373{
Glenn Kasten74935e42013-12-19 08:56:45 -08002374 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002375 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung11e74242023-06-26 19:20:57 -07002376 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002377 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002378 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002379 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002380 uint32_t sampleRate;
2381
2382 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2383 lStatus = BAD_VALUE;
2384 goto Exit;
2385 }
Eric Laurent21da6472017-11-09 16:29:26 -08002386
2387 if (*pSampleRate == 0) {
2388 *pSampleRate = mSampleRate;
2389 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002390 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002391
2392 // special case for FAST flag considered OK if fast mixer is present
2393 if (hasFastMixer()) {
2394 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2395 }
2396
2397 // Check if requested flags are compatible with output stream flags
2398 if ((*flags & outputFlags) != *flags) {
2399 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2400 *flags, outputFlags);
2401 *flags = (audio_output_flags_t)(*flags & outputFlags);
2402 }
Eric Laurent81784c32012-11-19 14:55:58 -08002403
jiabinc658e452022-10-21 20:52:21 +00002404 if (isBitPerfect) {
Andy Hung116bc262023-06-20 18:56:17 -07002405 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002406 if (chain.get() != nullptr) {
2407 // Bit-perfect is required according to the configuration and preferred mixer
2408 // attributes, but it is not in the output flag from the client's request. Explicitly
2409 // adding bit-perfect flag to check the compatibility
2410 audio_output_flags_t flagsToCheck =
2411 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2412 chain->checkOutputFlagCompatibility(&flagsToCheck);
2413 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2414 ALOGE("%s cannot create track as there is data-processing effect attached to "
2415 "given session id(%d)", __func__, sessionId);
2416 lStatus = BAD_VALUE;
2417 goto Exit;
2418 }
2419 *flags = flagsToCheck;
2420 }
2421 }
2422
Eric Laurent81784c32012-11-19 14:55:58 -08002423 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002424 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002425 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002426 // PCM data
2427 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002428 // TODO: extract as a data library function that checks that a computationally
2429 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002430 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002431 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2432 (channelMask == AUDIO_CHANNEL_OUT_MONO
2433 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002434 // hardware sample rate
2435 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002436 // normal mixer has an associated fast mixer
2437 hasFastMixer() &&
2438 // there are sufficient fast track slots available
2439 (mFastTrackAvailMask != 0)
2440 // FIXME test that MixerThread for this fast track has a capable output HAL
2441 // FIXME add a permission test also?
2442 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002443 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2444 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002445 // read the fast track multiplier property the first time it is needed
2446 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2447 if (ok != 0) {
2448 ALOGE("%s pthread_once failed: %d", __func__, ok);
2449 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002450 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002451 }
Eric Laurent4c415062016-06-17 16:14:16 -07002452
2453 // check compatibility with audio effects.
2454 { // scope for mLock
2455 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002456 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002457 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002458 AUDIO_SESSION_OUTPUT_STAGE,
2459 AUDIO_SESSION_OUTPUT_MIX,
2460 sessionId,
2461 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002462 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002463 if (chain.get() != nullptr) {
2464 audio_output_flags_t old = *flags;
2465 chain->checkOutputFlagCompatibility(flags);
2466 if (old != *flags) {
2467 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2468 (int)session, (int)old, (int)*flags);
2469 }
Eric Laurent4c415062016-06-17 16:14:16 -07002470 }
2471 }
2472 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002473 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002474 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2475 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002476 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002477 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002478 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002479 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002480 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002481 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002482 audio_is_linear_pcm(format), channelMask, sampleRate,
2483 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002484 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002485 }
2486 }
Eric Laurent21da6472017-11-09 16:29:26 -08002487
2488 if (!audio_has_proportional_frames(format)) {
2489 if (sharedBuffer != 0) {
2490 // Same comment as below about ignoring frameCount parameter for set()
2491 frameCount = sharedBuffer->size();
2492 } else if (frameCount == 0) {
2493 frameCount = mNormalFrameCount;
2494 }
2495 if (notificationFrameCount != frameCount) {
2496 notificationFrameCount = frameCount;
2497 }
2498 } else if (sharedBuffer != 0) {
2499 // FIXME: Ensure client side memory buffers need
2500 // not have additional alignment beyond sample
2501 // (e.g. 16 bit stereo accessed as 32 bit frame).
2502 size_t alignment = audio_bytes_per_sample(format);
2503 if (alignment & 1) {
2504 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2505 alignment = 1;
2506 }
2507 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2508 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2509 if (channelCount > 1) {
2510 // More than 2 channels does not require stronger alignment than stereo
2511 alignment <<= 1;
2512 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002513 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002514 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002515 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002516 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002517 goto Exit;
2518 }
Eric Laurent21da6472017-11-09 16:29:26 -08002519
2520 // When initializing a shared buffer AudioTrack via constructors,
2521 // there's no frameCount parameter.
2522 // But when initializing a shared buffer AudioTrack via set(),
2523 // there _is_ a frameCount parameter. We silently ignore it.
2524 frameCount = sharedBuffer->size() / frameSize;
2525 } else {
2526 size_t minFrameCount = 0;
2527 // For fast tracks we try to respect the application's request for notifications per buffer.
2528 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2529 if (notificationsPerBuffer > 0) {
2530 // Avoid possible arithmetic overflow during multiplication.
2531 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2532 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2533 notificationsPerBuffer, mFrameCount);
2534 } else {
2535 minFrameCount = mFrameCount * notificationsPerBuffer;
2536 }
2537 }
2538 } else {
2539 // For normal PCM streaming tracks, update minimum frame count.
2540 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2541 // cover audio hardware latency.
2542 // This is probably too conservative, but legacy application code may depend on it.
2543 // If you change this calculation, also review the start threshold which is related.
2544 uint32_t latencyMs = latency_l();
2545 if (latencyMs == 0) {
2546 ALOGE("Error when retrieving output stream latency");
2547 lStatus = UNKNOWN_ERROR;
2548 goto Exit;
2549 }
2550
2551 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2552 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2553
Eric Laurent81784c32012-11-19 14:55:58 -08002554 }
Eric Laurent21da6472017-11-09 16:29:26 -08002555 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002556 frameCount = minFrameCount;
2557 }
Eric Laurent81784c32012-11-19 14:55:58 -08002558 }
Eric Laurent21da6472017-11-09 16:29:26 -08002559
2560 // Make sure that application is notified with sufficient margin before underrun.
2561 // The client can divide the AudioTrack buffer into sub-buffers,
2562 // and expresses its desire to server as the notification frame count.
2563 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2564 size_t maxNotificationFrames;
2565 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2566 // notify every HAL buffer, regardless of the size of the track buffer
2567 maxNotificationFrames = mFrameCount;
2568 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002569 // Triple buffer the notification period for a triple buffered mixer period;
2570 // otherwise, double buffering for the notification period is fine.
2571 //
2572 // TODO: This should be moved to AudioTrack to modify the notification period
2573 // on AudioTrack::setBufferSizeInFrames() changes.
2574 const int nBuffering =
2575 (uint64_t{frameCount} * mSampleRate)
2576 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2577
Eric Laurent21da6472017-11-09 16:29:26 -08002578 maxNotificationFrames = frameCount / nBuffering;
2579 // If client requested a fast track but this was denied, then use the smaller maximum.
2580 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2581 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2582 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2583 maxNotificationFrames = maxNotificationFramesFastDenied;
2584 }
2585 }
2586 }
2587 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2588 if (notificationFrameCount == 0) {
2589 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2590 maxNotificationFrames, frameCount);
2591 } else {
2592 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2593 notificationFrameCount, maxNotificationFrames, frameCount);
2594 }
2595 notificationFrameCount = maxNotificationFrames;
2596 }
2597 }
2598
Glenn Kasten74935e42013-12-19 08:56:45 -08002599 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002600 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002601
Glenn Kastenc3df8382014-03-13 15:05:25 -07002602 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002603 case BIT_PERFECT:
2604 if (isBitPerfect) {
2605 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2606 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2607 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2608 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2609 mChannelMask);
2610 lStatus = BAD_VALUE;
2611 goto Exit;
2612 }
2613 }
2614 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002615
2616 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002617 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002618 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002619 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2620 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002621 sampleRate, format, channelMask, mOutput, mFormat);
2622 lStatus = BAD_VALUE;
2623 goto Exit;
2624 }
2625 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002626 break;
2627
2628 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002629 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002630 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2631 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002632 sampleRate, format, channelMask, mOutput, mFormat);
2633 lStatus = BAD_VALUE;
2634 goto Exit;
2635 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002636 break;
2637
2638 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002639 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002640 ALOGE("createTrack_l() Bad parameter: format %#x \""
2641 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002642 format, mOutput, mFormat);
2643 lStatus = BAD_VALUE;
2644 goto Exit;
2645 }
Andy Hungcd044842014-08-07 11:04:34 -07002646 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002647 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2648 lStatus = BAD_VALUE;
2649 goto Exit;
2650 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002651 break;
2652
Eric Laurent81784c32012-11-19 14:55:58 -08002653 }
2654
2655 lStatus = initCheck();
2656 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002657 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002658 goto Exit;
2659 }
2660
2661 { // scope for mLock
2662 Mutex::Autolock _l(mLock);
2663
2664 // all tracks in same audio session must share the same routing strategy otherwise
2665 // conflicts will happen when tracks are moved from one output to another by audio policy
2666 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002667 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002668 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002669 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002670 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002671 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002672 if (sessionId == t->sessionId() && strategy != actual) {
2673 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2674 strategy, actual);
2675 lStatus = BAD_VALUE;
2676 goto Exit;
2677 }
2678 }
2679 }
2680
yucliuc9c49cd2020-07-13 16:25:21 -07002681 // Set DIRECT flag if current thread is DirectOutputThread. This can
2682 // happen when the playback is rerouted to direct output thread by
2683 // dynamic audio policy.
2684 // Do NOT report the flag changes back to client, since the client
2685 // doesn't explicitly request a direct flag.
2686 audio_output_flags_t trackFlags = *flags;
2687 if (mType == DIRECT) {
2688 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2689 }
2690
Andy Hung11e74242023-06-26 19:20:57 -07002691 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002692 channelMask, frameCount,
2693 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002694 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung11e74242023-06-26 19:20:57 -07002695 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002696 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002697
Glenn Kasten03003332013-08-06 15:40:54 -07002698 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2699 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002700 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002701 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002702 goto Exit;
2703 }
2704 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002705 {
2706 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2707 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002708 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002709 }
2710 }
Eric Laurent81784c32012-11-19 14:55:58 -08002711
Andy Hung116bc262023-06-20 18:56:17 -07002712 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002713 if (chain != 0) {
2714 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2715 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002716 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002717 chain->incTrackCnt();
2718 }
2719
Eric Laurent05067782016-06-01 18:27:28 -07002720 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002721 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2722 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2723 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002724 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002725 }
2726 }
2727
2728 lStatus = NO_ERROR;
2729
2730Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002731 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002732 return track;
2733}
2734
Andy Hung1bc088a2018-02-09 15:57:31 -08002735template<typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07002736ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002737{
Andy Hungc0691382018-09-12 18:01:57 -07002738 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002739 const ssize_t index = mTracks.remove(track);
2740 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002741 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002742 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002743 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002744 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002745 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002746 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002747 }
2748 return index;
2749}
2750
Andy Hung4b17e882023-07-07 13:47:37 -07002751uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002752{
2753 return latency;
2754}
2755
Andy Hung4b17e882023-07-07 13:47:37 -07002756uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002757{
2758 Mutex::Autolock _l(mLock);
2759 return latency_l();
2760}
Andy Hung4b17e882023-07-07 13:47:37 -07002761uint32_t PlaybackThread::latency_l() const
Eric Laurent81784c32012-11-19 14:55:58 -08002762{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002763 uint32_t latency;
2764 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2765 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002766 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002767 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002768}
2769
Andy Hung4b17e882023-07-07 13:47:37 -07002770void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002771{
2772 Mutex::Autolock _l(mLock);
2773 // Don't apply master volume in SW if our HAL can do it for us.
2774 if (mOutput && mOutput->audioHwDev &&
2775 mOutput->audioHwDev->canSetMasterVolume()) {
2776 mMasterVolume = 1.0;
2777 } else {
2778 mMasterVolume = value;
2779 }
2780}
2781
Andy Hung4b17e882023-07-07 13:47:37 -07002782void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002783{
2784 mMasterBalance.store(balance);
2785}
2786
Andy Hung4b17e882023-07-07 13:47:37 -07002787void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002788{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002789 if (isDuplicating()) {
2790 return;
2791 }
Eric Laurent81784c32012-11-19 14:55:58 -08002792 Mutex::Autolock _l(mLock);
2793 // Don't apply master mute in SW if our HAL can do it for us.
2794 if (mOutput && mOutput->audioHwDev &&
2795 mOutput->audioHwDev->canSetMasterMute()) {
2796 mMasterMute = false;
2797 } else {
2798 mMasterMute = muted;
2799 }
2800}
2801
Andy Hung4b17e882023-07-07 13:47:37 -07002802void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002803{
2804 Mutex::Autolock _l(mLock);
2805 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002806 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002807}
2808
Andy Hung4b17e882023-07-07 13:47:37 -07002809void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002810{
2811 Mutex::Autolock _l(mLock);
2812 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002813 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002814}
2815
Andy Hung4b17e882023-07-07 13:47:37 -07002816float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002817{
2818 Mutex::Autolock _l(mLock);
2819 return mStreamTypes[stream].volume;
2820}
2821
Andy Hung4b17e882023-07-07 13:47:37 -07002822void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002823{
2824 mOutput->stream->setVolume(left, right);
2825}
2826
Eric Laurent81784c32012-11-19 14:55:58 -08002827// addTrack_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07002828status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Andy Hung920f6572022-10-06 12:09:49 -07002829NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent81784c32012-11-19 14:55:58 -08002830{
2831 status_t status = ALREADY_EXISTS;
2832
Eric Laurent81784c32012-11-19 14:55:58 -08002833 if (mActiveTracks.indexOf(track) < 0) {
2834 // the track is newly added, make sure it fills up all its
2835 // buffers before playing. This is to ensure the client will
2836 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002837 if (track->isExternalTrack()) {
Andy Hung11e74242023-06-26 19:20:57 -07002838 IAfTrackBase::track_state state = track->state();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002839 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002840 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002841 mLock.lock();
2842 // abort track was stopped/paused while we released the lock
Andy Hung11e74242023-06-26 19:20:57 -07002843 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002844 if (status == NO_ERROR) {
2845 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002846 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002847 mLock.lock();
2848 }
2849 return INVALID_OPERATION;
2850 }
2851 // abort if start is rejected by audio policy manager
2852 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002853 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2854 // current playback thread is reopened, which may happen when clients set preferred
2855 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2856 // immediately.
2857 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002858 }
2859#ifdef ADD_BATTERY_DATA
2860 // to track the speaker usage
2861 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2862#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002863 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002864 }
2865
Eric Laurent51716182016-02-29 18:00:56 -08002866 // set retry count for buffer fill
2867 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002868 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07002869 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002870 } else {
Andy Hung11e74242023-06-26 19:20:57 -07002871 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002872 }
Andy Hung11e74242023-06-26 19:20:57 -07002873 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002874 } else {
Andy Hung11e74242023-06-26 19:20:57 -07002875 track->retryCount() = kMaxTrackStartupRetries;
2876 track->fillingStatus() =
2877 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002878 }
2879
Andy Hung116bc262023-06-20 18:56:17 -07002880 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002881 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2882 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2883 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002884 // Unlock due to VibratorService will lock for this call and will
2885 // call Tracks.mute/unmute which also require thread's lock.
2886 mLock.unlock();
Andy Hung76cb9152023-07-20 21:23:42 -07002887 const os::HapticScale intensity = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002888 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002889 std::optional<media::AudioVibratorInfo> vibratorInfo;
2890 {
2891 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2892 // used to play this track.
Andy Hung7535ed92023-07-17 17:05:00 -07002893 Mutex::Autolock _l(mAfThreadCallback->mutex());
2894 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002895 }
jiabin57303cc2018-12-18 15:45:57 -08002896 mLock.lock();
Simon Bowden62823412022-10-17 14:52:26 +00002897 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002898 if (vibratorInfo) {
2899 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2900 }
2901
jiabin57303cc2018-12-18 15:45:57 -08002902 // Haptic playback should be enabled by vibrator service.
2903 if (track->getHapticPlaybackEnabled()) {
2904 // Disable haptic playback of all active track to ensure only
2905 // one track playing haptic if current track should play haptic.
2906 for (const auto &t : mActiveTracks) {
2907 t->setHapticPlaybackEnabled(false);
2908 }
jiabin245cdd92018-12-07 17:55:15 -08002909 }
jiabine70bc7f2020-06-30 22:07:55 -07002910
2911 // Set haptic intensity for effect
2912 if (chain != nullptr) {
2913 chain->setHapticIntensity_l(track->id(), intensity);
2914 }
jiabin245cdd92018-12-07 17:55:15 -08002915 }
2916
Andy Hung11e74242023-06-26 19:20:57 -07002917 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002918 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002919 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002920 if (chain != 0) {
2921 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2922 track->sessionId());
2923 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002924 }
2925
Andy Hungc2b11cb2020-04-22 09:04:01 -07002926 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002927 status = NO_ERROR;
2928 }
2929
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002930 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002931 return status;
2932}
2933
Andy Hung4b17e882023-07-07 13:47:37 -07002934bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002935{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002936 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002937 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002938 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung11e74242023-06-26 19:20:57 -07002939 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002940 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002941 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002942 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002943 if (track->isPausePending()) {
2944 track->pauseAck();
2945 }
Andy Hung11e74242023-06-26 19:20:57 -07002946 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002947 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002948
2949 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002950}
2951
Andy Hung4b17e882023-07-07 13:47:37 -07002952void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002953{
2954 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002955
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002956 String8 result;
2957 track->appendDump(result, false /* active */);
2958 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002959
Eric Laurent81784c32012-11-19 14:55:58 -08002960 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002961 {
2962 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2963 mAudioTrackCallbacks.erase(track);
2964 }
Eric Laurent81784c32012-11-19 14:55:58 -08002965 if (track->isFastTrack()) {
Andy Hung11e74242023-06-26 19:20:57 -07002966 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002967 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002968 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2969 mFastTrackAvailMask |= 1 << index;
2970 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung11e74242023-06-26 19:20:57 -07002971 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002972 }
Andy Hung116bc262023-06-20 18:56:17 -07002973 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002974 if (chain != 0) {
2975 chain->decTrackCnt();
2976 }
2977}
2978
Andy Hung4b17e882023-07-07 13:47:37 -07002979String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08002980{
Eric Laurent81784c32012-11-19 14:55:58 -08002981 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002982 String8 out_s8;
2983 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2984 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002985 }
Andy Hung920f6572022-10-06 12:09:49 -07002986 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08002987}
2988
Andy Hung4b17e882023-07-07 13:47:37 -07002989status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002990 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002991 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002992 return NO_INIT;
2993 }
2994 return mOutput->stream->selectPresentation(presentationId, programId);
2995}
2996
Andy Hung4b17e882023-07-07 13:47:37 -07002997void PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002998 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002999 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003000 sp<AudioIoDescriptor> desc;
3001 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003002 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003003 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003004 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003005 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003006 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3007 mSampleRate, mFormat, mChannelMask,
3008 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3009 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003010 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003011 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003012 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003013 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003014 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003015 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003016 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003017 break;
3018 }
Andy Hung7535ed92023-07-17 17:05:00 -07003019 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003020}
3021
Andy Hung4b17e882023-07-07 13:47:37 -07003022void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003023{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003024 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003025}
3026
Andy Hung4b17e882023-07-07 13:47:37 -07003027void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003028{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003029 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003030}
3031
Andy Hung4b17e882023-07-07 13:47:37 -07003032void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003033{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003034 mCallbackThread->setAsyncError();
3035}
3036
Andy Hung4b17e882023-07-07 13:47:37 -07003037void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08003038 const std::basic_string<uint8_t>& metadataBs)
3039{
Andy Hung4b17e882023-07-07 13:47:37 -07003040 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003041 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hung4b17e882023-07-07 13:47:37 -07003042 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003043 if (playbackThread == nullptr) {
3044 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3045 return;
3046 }
3047
jiabinf6eb4c32020-02-25 14:06:25 -08003048 audio_utils::metadata::Data metadata =
3049 audio_utils::metadata::dataFromByteString(metadataBs);
3050 if (metadata.empty()) {
3051 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3052 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3053 (int)metadataBs.size());
3054 return;
3055 }
3056
3057 audio_utils::metadata::ByteString metaDataStr =
3058 audio_utils::metadata::byteStringFromData(metadata);
3059 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
3060 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07003061 for (const auto& callbackPair : mAudioTrackCallbacks) {
3062 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003063 }
3064 }).detach();
3065}
3066
Andy Hung4b17e882023-07-07 13:47:37 -07003067void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003068{
3069 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003070 // reject out of sequence requests
3071 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3072 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003073 mWaitWorkCV.signal();
3074 }
3075}
3076
Andy Hung4b17e882023-07-07 13:47:37 -07003077void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003078{
3079 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003080 // reject out of sequence requests
3081 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003082 // Register discontinuity when HW drain is completed because that can cause
3083 // the timestamp frame position to reset to 0 for direct and offload threads.
3084 // (Out of sequence requests are ignored, since the discontinuity would be handled
3085 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003086 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003087 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003088 mWaitWorkCV.signal();
3089 }
3090}
3091
Andy Hung4b17e882023-07-07 13:47:37 -07003092void PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003093{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003094 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003095 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3096 mSampleRate = audioConfig.sample_rate;
3097 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003098 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003099 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003100 }
Andy Hungd21a2ab2023-07-20 21:44:14 -07003101 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003102 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3103 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003104 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003105
3106 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3107 mMixerChannelMask = mChannelMask;
3108 }
3109
Andy Hunge5412692014-05-16 11:25:07 -07003110 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003111 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003112
Eric Laurentf1f22e72021-07-13 14:04:14 +02003113 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3114
Phil Burkca5e6142015-07-14 09:42:29 -07003115 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003116 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003117 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003118 // Get format from the shim, which will be different than the HAL format
3119 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003120 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003121 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003122 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003123 }
Andy Hungd21a2ab2023-07-20 21:44:14 -07003124 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003125 LOG_FATAL("HAL format %#x not supported for mixed output",
3126 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003127 }
Phil Burk062e67a2015-02-11 13:40:50 -08003128 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003129 result = mOutput->stream->getBufferSize(&mBufferSize);
3130 LOG_ALWAYS_FATAL_IF(result != OK,
3131 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003132 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003133 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003134 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003135 mFrameCount);
3136 }
3137
Eric Laurentd1f69b02014-12-15 14:33:13 -08003138 mHwSupportsPause = false;
3139 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003140 bool supportsPause = false, supportsResume = false;
3141 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3142 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003143 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003144 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003145 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003146 } else if (supportsResume) {
3147 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003148 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003149 }
3150 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003151 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3152 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3153 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003154
Andy Hungfbfc3952015-01-15 13:33:51 -08003155 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3156 // For best precision, we use float instead of the associated output
3157 // device format (typically PCM 16 bit).
3158
3159 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3160 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3161 mBufferSize = mFrameSize * mFrameCount;
3162
3163 // TODO: We currently use the associated output device channel mask and sample rate.
3164 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3165 // (if a valid mask) to avoid premature downmix.
3166 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3167 // instead of the output device sample rate to avoid loss of high frequency information.
3168 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3169 }
3170
Andy Hung09a50072014-02-27 14:30:47 -08003171 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003172 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003173 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003174 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3175 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003176 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3177 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003178
Eric Laurent81784c32012-11-19 14:55:58 -08003179 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3180 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3181 maxNormalFrameCount = maxNormalFrameCount & ~15;
3182 if (maxNormalFrameCount < minNormalFrameCount) {
3183 maxNormalFrameCount = minNormalFrameCount;
3184 }
3185 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3186 if (multiplier <= 1.0) {
3187 multiplier = 1.0;
3188 } else if (multiplier <= 2.0) {
3189 if (2 * mFrameCount <= maxNormalFrameCount) {
3190 multiplier = 2.0;
3191 } else {
3192 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3193 }
3194 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003195 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003196 }
3197 }
3198 mNormalFrameCount = multiplier * mFrameCount;
3199 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003200 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003201 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3202 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003203 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003204 mNormalFrameCount);
3205
Andy Hung08fb1742015-05-31 23:22:10 -07003206 // Check if we want to throttle the processing to no more than 2x normal rate
3207 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003208 mThreadThrottleTimeMs = 0;
3209 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003210 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3211
Andy Hung010a1a12014-03-13 13:57:33 -07003212 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3213 // Originally this was int16_t[] array, need to remove legacy implications.
3214 free(mSinkBuffer);
3215 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003216
Andy Hung5b10a202014-03-13 13:59:29 -07003217 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3218 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3219 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003220 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003221
Andy Hung69aed5f2014-02-25 17:24:40 -08003222 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3223 // drives the output.
3224 free(mMixerBuffer);
3225 mMixerBuffer = NULL;
3226 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003227 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003228 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003229 * audio_bytes_per_sample(mMixerBufferFormat);
3230 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3231 }
Andy Hung98ef9782014-03-04 14:46:50 -08003232 free(mEffectBuffer);
3233 mEffectBuffer = NULL;
3234 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003235 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003236 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003237 * audio_bytes_per_sample(mEffectBufferFormat);
3238 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3239 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003240
Eric Laurentb62d0362021-10-26 17:40:18 +02003241 if (mType == SPATIALIZER) {
3242 free(mPostSpatializerBuffer);
3243 mPostSpatializerBuffer = nullptr;
3244 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3245 * audio_bytes_per_sample(mEffectBufferFormat);
3246 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3247 }
3248
Mikhail Naganov55773032020-10-01 15:08:13 -07003249 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3250 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003251 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3252 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003253 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003254
Eric Laurent81784c32012-11-19 14:55:58 -08003255 // force reconfiguration of effect chains and engines to take new buffer size and audio
3256 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003257 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003258 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3259 // matter.
3260 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003261 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003262 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung7535ed92023-07-17 17:05:00 -07003263 mAfThreadCallback->moveEffectChain_l(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003264 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003265 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003266
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003267 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003268 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003269 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3270 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3271 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3272 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3273 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3274 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3275 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3276 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3277 (int32_t)mHapticChannelMask)
3278 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3279 (int32_t)mHapticChannelCount)
3280 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3281 formatToString(mHALFormat).c_str())
3282 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3283 (int32_t)mFrameCount) // sic - added HAL
3284 ;
3285 uint32_t latencyMs;
3286 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3287 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3288 }
3289 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003290}
3291
Andy Hung4b17e882023-07-07 13:47:37 -07003292ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003293{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003294 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003295 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003296 }
3297 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003298 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung11e74242023-06-26 19:20:57 -07003299 for (const sp<IAfTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -07003300 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003301 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003302 }
Kevin Rocard12381092018-04-11 09:19:59 -07003303 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003304 MetadataUpdate change;
3305 change.playbackMetadataUpdate = metadata.tracks;
3306 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003307}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003308
Andy Hung4b17e882023-07-07 13:47:37 -07003309void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003310 const StreamOutHalInterface::SourceMetadata& metadata)
3311{
3312 mOutput->stream->updateSourceMetadata(metadata);
3313};
3314
Andy Hung4b17e882023-07-07 13:47:37 -07003315status_t PlaybackThread::getRenderPosition(
Andy Hung3e4c8742023-06-29 21:19:25 -07003316 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003317{
3318 if (halFrames == NULL || dspFrames == NULL) {
3319 return BAD_VALUE;
3320 }
3321 Mutex::Autolock _l(mLock);
3322 if (initCheck() != NO_ERROR) {
3323 return INVALID_OPERATION;
3324 }
Andy Hung818e7a32016-02-16 18:08:07 -08003325 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003326 *halFrames = framesWritten;
3327
3328 if (isSuspended()) {
3329 // return an estimation of rendered frames when the output is suspended
3330 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003331 *dspFrames = (uint32_t)
3332 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003333 return NO_ERROR;
3334 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003335 status_t status;
3336 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003337 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003338 *dspFrames = (size_t)frames;
3339 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003340 }
3341}
3342
Andy Hung4b17e882023-07-07 13:47:37 -07003343product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003344{
3345 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3346 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3347 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003348 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003349 }
3350 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003351 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003352 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003353 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003354 }
3355 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003356 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003357}
3358
3359
Andy Hung4b17e882023-07-07 13:47:37 -07003360AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003361{
3362 Mutex::Autolock _l(mLock);
3363 return mOutput;
3364}
3365
Andy Hung4b17e882023-07-07 13:47:37 -07003366AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003367{
3368 Mutex::Autolock _l(mLock);
3369 AudioStreamOut *output = mOutput;
3370 mOutput = NULL;
3371 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3372 // must push a NULL and wait for ack
3373 mOutputSink.clear();
3374 mPipeSink.clear();
3375 mNormalSink.clear();
3376 return output;
3377}
3378
3379// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hung4b17e882023-07-07 13:47:37 -07003380sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003381{
3382 if (mOutput == NULL) {
3383 return NULL;
3384 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003385 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003386}
3387
Andy Hung4b17e882023-07-07 13:47:37 -07003388uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003389{
3390 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3391}
3392
Andy Hung4b17e882023-07-07 13:47:37 -07003393status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003394{
3395 if (!isValidSyncEvent(event)) {
3396 return BAD_VALUE;
3397 }
3398
3399 Mutex::Autolock _l(mLock);
3400
3401 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003402 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003403 if (event->triggerSession() == track->sessionId()) {
3404 (void) track->setSyncEvent(event);
3405 return NO_ERROR;
3406 }
3407 }
3408
3409 return NAME_NOT_FOUND;
3410}
3411
Andy Hung4b17e882023-07-07 13:47:37 -07003412bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003413{
3414 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3415}
3416
Andy Hung4b17e882023-07-07 13:47:37 -07003417void PlaybackThread::threadLoop_removeTracks(
Andy Hung11e74242023-06-26 19:20:57 -07003418 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003419{
Andy Hungfe726a62018-09-27 15:17:25 -07003420 // Miscellaneous track cleanup when removed from the active list,
3421 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003422#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003423 for (const auto& track : tracksToRemove) {
3424 if (track->isExternalTrack()) {
3425 // to track the speaker usage
3426 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003427 }
3428 }
Andy Hungfe726a62018-09-27 15:17:25 -07003429#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003430}
3431
Andy Hung4b17e882023-07-07 13:47:37 -07003432void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003433{
3434 if (!mMasterMute) {
3435 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003436 if (mOutDeviceTypeAddrs.empty()) {
3437 ALOGD("ro.audio.silent is ignored since no output device is set");
3438 return;
3439 }
jiabinc52b1ff2019-10-31 17:20:42 -07003440 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003441 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3442 return;
3443 }
Eric Laurent81784c32012-11-19 14:55:58 -08003444 if (property_get("ro.audio.silent", value, "0") > 0) {
3445 char *endptr;
3446 unsigned long ul = strtoul(value, &endptr, 0);
3447 if (*endptr == '\0' && ul != 0) {
3448 ALOGD("Silence is golden");
3449 // The setprop command will not allow a property to be changed after
3450 // the first time it is set, so we don't have to worry about un-muting.
3451 setMasterMute_l(true);
3452 }
3453 }
3454 }
3455}
3456
3457// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung4b17e882023-07-07 13:47:37 -07003458ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003459{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003460 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003461 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003462 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003463 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003464
3465 // If an NBAIO sink is present, use it to write the normal mixer's submix
3466 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003467
Andy Hung010a1a12014-03-13 13:57:33 -07003468 const size_t count = mBytesRemaining / mFrameSize;
3469
Simon Wilson2d590962012-11-29 15:18:50 -08003470 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003471 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1b6d46a2023-07-19 16:22:58 -07003472 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003473 if (screenState != mScreenState) {
3474 mScreenState = screenState;
3475 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3476 if (pipe != NULL) {
3477 pipe->setAvgFrames((mScreenState & 1) ?
3478 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3479 }
3480 }
Andy Hung010a1a12014-03-13 13:57:33 -07003481 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003482 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003483
Eric Laurent81784c32012-11-19 14:55:58 -08003484 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003485 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003486
Andy Hung8946a282018-04-19 20:04:56 -07003487#ifdef TEE_SINK
3488 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3489#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003490 } else {
3491 bytesWritten = framesWritten;
3492 }
3493 // otherwise use the HAL / AudioStreamOut directly
3494 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003495 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003496
Eric Laurentbfb1b832013-01-07 09:53:42 -08003497 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003498 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3499 mWriteAckSequence += 2;
3500 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003501 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003502 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003503 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003504 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003505 // FIXME We should have an implementation of timestamps for direct output threads.
3506 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003507 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003508 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003509
Eric Laurentbfb1b832013-01-07 09:53:42 -08003510 if (mUseAsyncWrite &&
3511 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3512 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003513 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003514 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003515 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003516 }
Eric Laurent81784c32012-11-19 14:55:58 -08003517 }
3518
Eric Laurent81784c32012-11-19 14:55:58 -08003519 mNumWrites++;
3520 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003521 if (mStandby) {
3522 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003523 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003524 mStandby = false;
3525 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003526 return bytesWritten;
3527}
3528
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003529// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07003530void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003531 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003532{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003533 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003534 if (outputSink != nullptr) {
3535 outputSink->startMelComputation(processor);
3536 }
Vlad Popab042ee62022-10-20 18:05:00 +02003537}
3538
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003539// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07003540void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003541{
3542 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003543 if (outputSink != nullptr) {
3544 outputSink->stopMelComputation();
3545 }
Vlad Popab042ee62022-10-20 18:05:00 +02003546}
3547
Andy Hung4b17e882023-07-07 13:47:37 -07003548void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003549{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003550 bool supportsDrain = false;
3551 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003552 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3553 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003554 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3555 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003556 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003557 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003558 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003559 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003560 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003561 }
3562}
3563
Andy Hung4b17e882023-07-07 13:47:37 -07003564void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003565{
Eric Laurent275e8e92014-11-30 15:14:47 -08003566 {
3567 Mutex::Autolock _l(mLock);
3568 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003569 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003570 track->invalidate();
3571 }
Andy Hungdae27702016-10-31 14:01:16 -07003572 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3573 // After we exit there are no more track changes sent to BatteryNotifier
3574 // because that requires an active threadLoop.
3575 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3576 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003577 }
Eric Laurent81784c32012-11-19 14:55:58 -08003578}
3579
3580/*
3581The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003582 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003583 - mActiveSleepTimeUs from activeSleepTimeUs()
3584 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003585 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3586 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003587 - maxPeriod from frame count and sample rate (MIXER only)
3588
3589The parameters that affect these derived values are:
3590 - frame count
3591 - frame size
3592 - sample rate
3593 - device type: A2DP or not
3594 - device latency
3595 - format: PCM or not
3596 - active sleep time
3597 - idle sleep time
3598*/
3599
Andy Hung4b17e882023-07-07 13:47:37 -07003600void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003601{
Andy Hung25c2dac2014-02-27 14:56:00 -08003602 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003603 mActiveSleepTimeUs = activeSleepTimeUs();
3604 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003605
Andy Hungd58c4732023-07-20 21:31:38 -07003606 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003607
Eric Laurent42537be2016-01-08 17:16:42 -08003608 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3609 // truncating audio when going to standby.
jiabinc52b1ff2019-10-31 17:20:42 -07003610 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003611 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3612 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3613 }
3614 }
Eric Laurent81784c32012-11-19 14:55:58 -08003615}
3616
Andy Hung4b17e882023-07-07 13:47:37 -07003617bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003618{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003619 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003620 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003621 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003622 size_t size = mTracks.size();
3623 for (size_t i = 0; i < size; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003624 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003625 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003626 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003627 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003628 }
3629 }
Eric Laurent13084622016-05-17 10:51:49 -07003630 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003631}
3632
Andy Hung4b17e882023-07-07 13:47:37 -07003633void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003634{
3635 Mutex::Autolock _l(mLock);
3636 invalidateTracks_l(streamType);
3637}
3638
Andy Hung4b17e882023-07-07 13:47:37 -07003639void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003640 Mutex::Autolock _l(mLock);
3641 invalidateTracks_l(portIds);
3642}
3643
Andy Hung4b17e882023-07-07 13:47:37 -07003644bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003645 bool trackMatch = false;
3646 const size_t size = mTracks.size();
3647 for (size_t i = 0; i < size; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003648 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003649 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3650 t->invalidate();
3651 portIds.erase(t->portId());
3652 trackMatch = true;
3653 }
3654 if (portIds.empty()) {
3655 break;
3656 }
3657 }
3658 return trackMatch;
3659}
3660
jiabinf042b9b2021-05-07 23:46:28 +00003661// getTrackById_l must be called with holding thread lock
Andy Hung4b17e882023-07-07 13:47:37 -07003662IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003663 audio_port_handle_t trackPortId) {
3664 for (size_t i = 0; i < mTracks.size(); i++) {
3665 if (mTracks[i]->portId() == trackPortId) {
3666 return mTracks[i].get();
3667 }
3668 }
3669 return nullptr;
3670}
3671
Andy Hung4b17e882023-07-07 13:47:37 -07003672status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003673{
Glenn Kastend848eb42016-03-08 13:42:11 -08003674 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003675 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003676 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003677
Andy Hungd3639922022-04-28 18:00:49 -07003678 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003679 if (!audio_is_global_session(session)) {
3680 // player sessions on a spatializer output will use a dedicated input buffer and
3681 // will either output multi channel to mEffectBuffer if the track is spatilaized
3682 // or stereo to mPostSpatializerBuffer if not spatialized.
3683 uint32_t channelMask;
3684 bool isSessionSpatialized =
3685 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3686 if (isSessionSpatialized) {
3687 channelMask = mMixerChannelMask;
3688 } else {
3689 channelMask = mChannelMask;
3690 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003691 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003692 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung7535ed92023-07-17 17:05:00 -07003693 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003694 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003695 &halInBuffer);
3696 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003697
Andy Hung7535ed92023-07-17 17:05:00 -07003698 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003699 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3700 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3701 &halOutBuffer);
3702 if (result != OK) return result;
3703
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003704 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003705
Mikhail Naganov022b9952017-01-04 16:36:51 -08003706 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3707 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003708 } else {
3709 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3710 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3711 // mPostSpatializerBuffer as output buffer
3712 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung7535ed92023-07-17 17:05:00 -07003713 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003714 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3715 if (result != OK) return result;
Andy Hung7535ed92023-07-17 17:05:00 -07003716 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003717 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3718 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003719
Eric Laurentb62d0362021-10-26 17:40:18 +02003720 if (session == AUDIO_SESSION_DEVICE) {
3721 halInBuffer = halOutBuffer;
3722 }
3723 }
3724 } else {
Andy Hung7535ed92023-07-17 17:05:00 -07003725 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003726 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3727 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3728 &halInBuffer);
3729 if (result != OK) return result;
3730 halOutBuffer = halInBuffer;
3731 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3732 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003733 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003734 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003735 // Only one effect chain can be present in direct output thread and it uses
3736 // the sink buffer as input
3737 if (mType != DIRECT) {
3738 size_t numSamples = mNormalFrameCount
3739 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3740 + mHapticChannelCount);
Andy Hung7535ed92023-07-17 17:05:00 -07003741 const status_t allocateStatus =
3742 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003743 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003744 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003745 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003746
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003747 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003748 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3749 buffer, session);
3750 }
3751 }
3752 }
3753
3754 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003755 // Attach all tracks with same session ID to this chain.
3756 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003757 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003758 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003759 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3760 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003761 track->setMainBuffer(buffer);
3762 chain->incTrackCnt();
3763 }
3764 }
3765
3766 // indicate all active tracks in the chain
Andy Hung11e74242023-06-26 19:20:57 -07003767 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003768 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003769 ALOGV("addEffectChain_l() activating track %p on session %d",
3770 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003771 chain->incActiveTrackCnt();
3772 }
3773 }
3774 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003775
Eric Laurentaaa44472014-09-12 17:41:50 -07003776 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003777 chain->setInBuffer(halInBuffer);
3778 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003779 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3780 // chains list in order to be processed last as it contains output device effects.
3781 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3782 // processing effects specific to an output stream before effects applied to all streams
3783 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003784 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3785 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003786 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003787 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003788 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003789 // Effect chain for other sessions are inserted at beginning of effect
3790 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003791 // sessions is not important.
3792 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003793 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3794 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003795 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003796 size_t size = mEffectChains.size();
3797 size_t i = 0;
3798 for (i = 0; i < size; i++) {
3799 if (mEffectChains[i]->sessionId() < session) {
3800 break;
3801 }
3802 }
3803 mEffectChains.insertAt(chain, i);
3804 checkSuspendOnAddEffectChain_l(chain);
3805
3806 return NO_ERROR;
3807}
3808
Andy Hung4b17e882023-07-07 13:47:37 -07003809size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003810{
Glenn Kastend848eb42016-03-08 13:42:11 -08003811 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003812
3813 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3814
3815 for (size_t i = 0; i < mEffectChains.size(); i++) {
3816 if (chain == mEffectChains[i]) {
3817 mEffectChains.removeAt(i);
3818 // detach all active tracks from the chain
Andy Hung11e74242023-06-26 19:20:57 -07003819 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003820 if (session == track->sessionId()) {
3821 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3822 chain.get(), session);
3823 chain->decActiveTrackCnt();
3824 }
3825 }
3826
3827 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003828 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung11e74242023-06-26 19:20:57 -07003829 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003830 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003831 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003832 chain->decTrackCnt();
3833 }
3834 }
3835 break;
3836 }
3837 }
3838 return mEffectChains.size();
3839}
3840
Andy Hung4b17e882023-07-07 13:47:37 -07003841status_t PlaybackThread::attachAuxEffect(
Andy Hung11e74242023-06-26 19:20:57 -07003842 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003843{
3844 Mutex::Autolock _l(mLock);
3845 return attachAuxEffect_l(track, EffectId);
3846}
3847
Andy Hung4b17e882023-07-07 13:47:37 -07003848status_t PlaybackThread::attachAuxEffect_l(
Andy Hung11e74242023-06-26 19:20:57 -07003849 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003850{
3851 status_t status = NO_ERROR;
3852
3853 if (EffectId == 0) {
3854 track->setAuxBuffer(0, NULL);
3855 } else {
3856 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003857 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003858 if (effect != 0) {
3859 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3860 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3861 } else {
3862 status = INVALID_OPERATION;
3863 }
3864 } else {
3865 status = BAD_VALUE;
3866 }
3867 }
3868 return status;
3869}
3870
Andy Hung4b17e882023-07-07 13:47:37 -07003871void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003872{
3873 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003874 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003875 if (track->auxEffectId() == effectId) {
3876 attachAuxEffect_l(track, 0);
3877 }
3878 }
3879}
3880
Andy Hung4b17e882023-07-07 13:47:37 -07003881bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003882NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003883{
Andy Hung78d8d952023-05-30 18:10:23 -07003884 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003885
Andy Hung11e74242023-06-26 19:20:57 -07003886 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003887
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003888 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003889 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003890
3891 // MIXER
3892 nsecs_t lastWarning = 0;
3893
3894 // DUPLICATING
3895 // FIXME could this be made local to while loop?
3896 writeFrames = 0;
3897
3898 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003899 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003900
Andy Hungd3639922022-04-28 18:00:49 -07003901 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003902 sleepTimeShift = 0;
3903 }
3904
3905 CpuStats cpuStats;
3906 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3907
3908 acquireWakeLock();
3909
Glenn Kasteneef598c2017-04-03 14:41:13 -07003910 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3911 // thread associated with this PlaybackThread.
3912 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3913 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003914 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3915 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003916 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003917 const char *logString = NULL;
3918
rago1bb90822017-05-02 18:31:48 -07003919 // Estimated time for next buffer to be written to hal. This is used only on
3920 // suspended mode (for now) to help schedule the wait time until next iteration.
3921 nsecs_t timeLoopNextNs = 0;
3922
Eric Laurent664539d2013-09-23 18:24:31 -07003923 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003924
Andy Hung2dbffc22018-08-08 18:50:41 -07003925 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003926
Eric Laurentb3f315a2021-07-13 15:09:05 +02003927 sendCheckOutputStageEffectsEvent();
3928
Andy Hung446f4df2019-02-21 12:26:41 -08003929 // loopCount is used for statistics and diagnostics.
3930 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003931 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003932 // Log merge requests are performed during AudioFlinger binder transactions, but
3933 // that does not cover audio playback. It's requested here for that reason.
Andy Hung7535ed92023-07-17 17:05:00 -07003934 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003935
Eric Laurent81784c32012-11-19 14:55:58 -08003936 cpuStats.sample(myName);
3937
Andy Hung116bc262023-06-20 18:56:17 -07003938 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003939 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003940 bool isHapticSessionSpatialized = false;
Andy Hung11e74242023-06-26 19:20:57 -07003941 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003942
Andy Hung2dbffc22018-08-08 18:50:41 -07003943 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3944 //
jiabinc52b1ff2019-10-31 17:20:42 -07003945 // Note: we access outDeviceTypes() outside of mLock.
3946 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003947 // Here, we try for the AF lock, but do not block on it as the latency
3948 // is more informational.
Andy Hung7535ed92023-07-17 17:05:00 -07003949 if (mAfThreadCallback->mutex().tryLock() == NO_ERROR) {
Andy Hungd25fe392023-07-13 16:52:46 -07003950 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07003951 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07003952 status_t status = INVALID_OPERATION;
3953 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung7535ed92023-07-17 17:05:00 -07003954 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungd25fe392023-07-13 16:52:46 -07003955 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07003956 && swPatches.size() > 0) {
3957 status = swPatches[0].getLatencyMs_l(&latencyMs);
3958 downstreamPatchHandle = swPatches[0].getPatchHandle();
3959 }
3960 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003961 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003962 lastDownstreamPatchHandle = downstreamPatchHandle;
3963 }
3964 if (status == OK) {
3965 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003966 // latency of 5 seconds).
3967 const double minLatency = 0., maxLatency = 5000.;
3968 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003969 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003970 } else {
3971 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07003972 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07003973 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003974 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003975 }
Andy Hung7535ed92023-07-17 17:05:00 -07003976 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07003977 }
3978 } else {
3979 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3980 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003981 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003982 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3983 }
3984 }
3985
Eric Laurentb3f315a2021-07-13 15:09:05 +02003986 if (mCheckOutputStageEffects.exchange(false)) {
3987 checkOutputStageEffects();
3988 }
3989
Vlad Popa7e81cea2023-01-19 16:34:16 +01003990 MetadataUpdate metadataUpdate;
Eric Laurent81784c32012-11-19 14:55:58 -08003991 { // scope for mLock
3992
3993 Mutex::Autolock _l(mLock);
3994
Eric Laurent021cf962014-05-13 10:18:14 -07003995 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003996 if (mCheckOutputStageEffects.load()) {
3997 continue;
3998 }
Eric Laurent10351942014-05-08 18:49:52 -07003999
Glenn Kasteneef598c2017-04-03 14:41:13 -07004000 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08004001 if (logString != NULL) {
4002 mNBLogWriter->logTimestamp();
4003 mNBLogWriter->log(logString);
4004 logString = NULL;
4005 }
4006
Dean Wheatley12473e92021-03-18 23:00:55 +11004007 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004008
Eric Laurent81784c32012-11-19 14:55:58 -08004009 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004010 if (mSignalPending) {
4011 // A signal was raised while we were unlocked
4012 mSignalPending = false;
4013 } else if (waitingAsyncCallback_l()) {
4014 if (exitPending()) {
4015 break;
4016 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004017 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004018 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004019 releaseWakeLock_l();
4020 released = true;
4021 }
Andy Hung10cbff12017-02-21 17:30:14 -08004022
4023 const int64_t waitNs = computeWaitTimeNs_l();
4024 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
4025 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
4026 if (status == TIMED_OUT) {
4027 mSignalPending = true; // if timeout recheck everything
4028 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004029 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004030 if (released) {
4031 acquireWakeLock_l();
4032 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004033 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4034 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004035
4036 continue;
4037 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004038 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004039 isSuspended()) {
4040 // put audio hardware into standby after short delay
4041 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004042
4043 threadLoop_standby();
4044
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004045 // This is where we go into standby
4046 if (!mStandby) {
4047 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004048 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004049 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004050 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004051 }
Andy Hungd0979812019-02-21 15:51:44 -08004052 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004053 }
4054
Eric Tan39ec8d62018-07-24 09:49:29 -07004055 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004056 // we're about to wait, flush the binder command buffer
4057 IPCThreadState::self()->flushCommands();
4058
4059 clearOutputTracks();
4060
4061 if (exitPending()) {
4062 break;
4063 }
4064
4065 releaseWakeLock_l();
4066 // wait until we have something to do...
4067 ALOGV("%s going to sleep", myName.string());
4068 mWaitWorkCV.wait(mLock);
4069 ALOGV("%s waking up", myName.string());
4070 acquireWakeLock_l();
4071
4072 mMixerStatus = MIXER_IDLE;
4073 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4074 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004075 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004076 checkSilentMode_l();
4077
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004078 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4079 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004080 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004081 sleepTimeShift = 0;
4082 }
4083
4084 continue;
4085 }
4086 }
Eric Laurent81784c32012-11-19 14:55:58 -08004087 // mMixerStatusIgnoringFastTracks is also updated internally
4088 mMixerStatus = prepareTracks_l(&tracksToRemove);
4089
Andy Hungdae27702016-10-31 14:01:16 -07004090 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004091
Vlad Popa7e81cea2023-01-19 16:34:16 +01004092 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004093
Eric Laurent81784c32012-11-19 14:55:58 -08004094 // prevent any changes in effect chain list and in each effect chain
4095 // during mixing and effect process as the audio buffers could be deleted
4096 // or modified if an effect is created or deleted
4097 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004098
4099 // Determine which session to pick up haptic data.
4100 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004101 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004102 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004103 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004104 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004105 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004106 if (effectChain != nullptr
4107 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004108 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004109 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004110 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004111 break;
4112 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004113 if (activeHapticSessionId == AUDIO_SESSION_NONE
4114 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004115 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004116 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004117 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004118 }
4119 }
4120 }
4121
Andy Hungc1646382019-04-30 16:12:10 -07004122 // Acquire a local copy of active tracks with lock (release w/o lock).
4123 //
4124 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4125 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4126 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4127 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent68a40a82022-05-03 18:15:04 +02004128
4129 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004130
Jiabin Huangfb476842022-12-06 03:18:10 +00004131 for (const auto &track : mActiveTracks ) {
jiabin7434e812023-06-27 18:22:35 +00004132 track->updateTeePatches_l();
Jiabin Huangfb476842022-12-06 03:18:10 +00004133 }
4134
Eric Laurent19952e12023-04-20 10:08:29 +02004135 // signal actual start of output stream when the render position reported by the kernel
4136 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004137 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4138 && (mKernelPositionOnStandby
4139 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004140 mHalStarted = true;
4141 mWaitHalStartCV.broadcast();
4142 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004143 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004144
Eric Laurentbfb1b832013-01-07 09:53:42 -08004145 if (mBytesRemaining == 0) {
4146 mCurrentWriteLength = 0;
4147 if (mMixerStatus == MIXER_TRACKS_READY) {
4148 // threadLoop_mix() sets mCurrentWriteLength
4149 threadLoop_mix();
4150 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4151 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004152 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004153 // must be written to HAL
4154 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004155 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004156 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004157
4158 // Tally underrun frames as we are inserting 0s here.
4159 for (const auto& track : activeTracks) {
Andy Hung11e74242023-06-26 19:20:57 -07004160 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004161 && !track->isStopped()
4162 && !track->isPaused()
4163 && !track->isTerminated()) {
4164 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4165 __func__, track->id(), track->getTrackStateAsString(),
4166 mNormalFrameCount);
Andy Hung11e74242023-06-26 19:20:57 -07004167 track->audioTrackServerProxy()->tallyUnderrunFrames(
4168 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004169 }
4170 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004171 }
4172 }
Andy Hung98ef9782014-03-04 14:46:50 -08004173 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004174 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004175 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004176 // or mSinkBuffer (if there are no effects and there is no data already copied to
4177 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004178 //
4179 // This is done pre-effects computation; if effects change to
4180 // support higher precision, this needs to move.
4181 //
4182 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004183 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004184 uint32_t mixerChannelCount = mEffectBufferValid ?
4185 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004186 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004187 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4188 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4189
David Li88ee0902022-06-22 10:01:21 +08004190 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4191 // do these processes after effects are applied.
4192 if (!mEffectBufferValid) {
4193 // mono blend occurs for mixer threads only (not direct or offloaded)
4194 // and is handled here if we're going directly to the sink.
4195 if (requireMonoBlend()) {
4196 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4197 mNormalFrameCount, true /*limit*/);
4198 }
Andy Hung2ddee192015-12-18 17:34:44 -08004199
David Li88ee0902022-06-22 10:01:21 +08004200 if (!hasFastMixer()) {
4201 // Balance must take effect after mono conversion.
4202 // We do it here if there is no FastMixer.
4203 // mBalance detects zero balance within the class for speed
4204 // (not needed here).
4205 mBalance.setBalance(mMasterBalance.load());
4206 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4207 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004208 }
4209
Andy Hung98ef9782014-03-04 14:46:50 -08004210 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004211 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004212
4213 // If we're going directly to the sink and there are haptic channels,
4214 // we should adjust channels as the sample data is partially interleaved
4215 // in this case.
4216 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4217 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4218 mChannelCount + mHapticChannelCount,
4219 audio_bytes_per_sample(format),
4220 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4221 }
Andy Hung98ef9782014-03-04 14:46:50 -08004222 }
4223
Eric Laurentbfb1b832013-01-07 09:53:42 -08004224 mBytesRemaining = mCurrentWriteLength;
4225 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004226 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4227 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4228 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4229 mBytesWritten += mBytesRemaining;
4230 mFramesWritten += framesRemaining;
4231 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004232 mBytesRemaining = 0;
4233 }
Eric Laurent81784c32012-11-19 14:55:58 -08004234
Eric Laurentbfb1b832013-01-07 09:53:42 -08004235 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004236 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004237 for (size_t i = 0; i < effectChains.size(); i ++) {
4238 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004239 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004240 if (activeHapticSessionId != AUDIO_SESSION_NONE
4241 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004242 // Haptic data is active in this case, copy it directly from
4243 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004244 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4245 audio_channel_count_from_out_mask(mMixerChannelMask) :
4246 mChannelCount;
4247 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4248 hapticSessionChannelCount = mChannelCount;
4249 }
4250
jiabin47affe52019-04-04 18:02:07 -07004251 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004252 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004253 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004254 memcpy_by_audio_format(
4255 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004256 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004257 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004258 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004259 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004260 }
Eric Laurent81784c32012-11-19 14:55:58 -08004261 }
4262 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004263 // Process effect chains for offloaded thread even if no audio
4264 // was read from audio track: process only updates effect state
4265 // and thus does have to be synchronized with audio writes but may have
4266 // to be called while waiting for async write callback
4267 if (mType == OFFLOAD) {
4268 for (size_t i = 0; i < effectChains.size(); i ++) {
4269 effectChains[i]->process_l();
4270 }
4271 }
Eric Laurent81784c32012-11-19 14:55:58 -08004272
Andy Hung98ef9782014-03-04 14:46:50 -08004273 // Only if the Effects buffer is enabled and there is data in the
4274 // Effects buffer (buffer valid), we need to
4275 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004276 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004277 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004278 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004279 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004280 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004281 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004282 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004283 }
4284
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004285 if (!hasFastMixer()) {
4286 // Balance must take effect after mono conversion.
4287 // We do it here if there is no FastMixer.
4288 // mBalance detects zero balance within the class for speed (not needed here).
4289 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004290 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004291 }
4292
Eric Laurentb62d0362021-10-26 17:40:18 +02004293 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4294 // mPostSpatializerBuffer if the haptics track is spatialized.
4295 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4296 // For other thread types, the haptics channels are already in mEffectBuffer.
4297 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4298 const size_t srcBufferSize = mNormalFrameCount *
4299 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4300 mEffectBufferFormat);
4301 const size_t dstBufferSize = mNormalFrameCount
4302 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4303
4304 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4305 mEffectBufferFormat,
4306 (uint8_t*)mEffectBuffer + srcBufferSize,
4307 mEffectBufferFormat,
4308 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004309 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004310 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4311 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4312 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4313 // Clamp PCM float values more than this distance from 0 to insulate
4314 // a HAL which doesn't handle NaN correctly.
4315 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4316 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4317 static_cast<const float*>(effectBuffer),
4318 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4319 } else {
4320 memcpy_by_audio_format(mSinkBuffer, mFormat,
4321 effectBuffer, mEffectBufferFormat, framesToCopy);
4322 }
jiabin245cdd92018-12-07 17:55:15 -08004323 // The sample data is partially interleaved when haptic channels exist,
4324 // we need to adjust channels here.
4325 if (mHapticChannelCount > 0) {
4326 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4327 mChannelCount + mHapticChannelCount,
4328 audio_bytes_per_sample(mFormat),
4329 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4330 }
Andy Hung98ef9782014-03-04 14:46:50 -08004331 }
4332
Eric Laurent81784c32012-11-19 14:55:58 -08004333 // enable changes in effect chain
4334 unlockEffectChains(effectChains);
4335
Vlad Popafce10862023-02-03 10:37:07 +01004336 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung7535ed92023-07-17 17:05:00 -07004337 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004338 metadataUpdate.playbackMetadataUpdate);
4339 }
4340
Eric Laurentbfb1b832013-01-07 09:53:42 -08004341 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004342 // mSleepTimeUs == 0 means we must write to audio hardware
4343 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004344 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004345 // writePeriodNs is updated >= 0 when ret > 0.
4346 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004347 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004348 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004349 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004350 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004351 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004352 if (ret < 0) {
4353 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004354 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004355 mBytesWritten += ret;
4356 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004357 const int64_t frames = ret / mFrameSize;
4358 mFramesWritten += frames;
4359
4360 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4361 // process information relating to write time.
4362 if (audio_has_proportional_frames(mFormat)) {
4363 // we are in a continuous mixing cycle
4364 if (mMixerStatus == MIXER_TRACKS_READY &&
4365 loopCount == lastLoopCountWritten + 1) {
4366
4367 const double jitterMs =
4368 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4369 {frames, writePeriodNs},
4370 {0, 0} /* lastTimestamp */, mSampleRate);
4371 const double processMs =
4372 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4373
4374 Mutex::Autolock _l(mLock);
4375 mIoJitterMs.add(jitterMs);
4376 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004377
4378 if (mPipeSink.get() != nullptr) {
4379 // Using the Monopipe availableToWrite, we estimate the current
4380 // buffer size.
4381 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4382 const ssize_t
4383 availableToWrite = mPipeSink->availableToWrite();
4384 const size_t pipeFrames = monoPipe->maxFrames();
4385 const size_t
4386 remainingFrames = pipeFrames - max(availableToWrite, 0);
4387 mMonopipePipeDepthStats.add(remainingFrames);
4388 }
Andy Hung446f4df2019-02-21 12:26:41 -08004389 }
4390
4391 // write blocked detection
4392 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004393 if ((mType == MIXER || mType == SPATIALIZER)
4394 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004395 mNumDelayedWrites++;
4396 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4397 ATRACE_NAME("underrun");
4398 ALOGW("write blocked for %lld msecs, "
4399 "%d delayed writes, thread %d",
4400 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4401 mNumDelayedWrites, mId);
4402 lastWarning = lastIoEndNs;
4403 }
4404 }
4405 }
4406 // update timing info.
4407 mLastIoBeginNs = lastIoBeginNs;
4408 mLastIoEndNs = lastIoEndNs;
4409 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004410 }
4411 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4412 (mMixerStatus == MIXER_DRAIN_ALL)) {
4413 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004414 }
Andy Hungd3639922022-04-28 18:00:49 -07004415 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004416
4417 if (mThreadThrottle
4418 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004419 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004420 // Limit MixerThread data processing to no more than twice the
4421 // expected processing rate.
4422 //
4423 // This helps prevent underruns with NuPlayer and other applications
4424 // which may set up buffers that are close to the minimum size, or use
4425 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4426 //
4427 // The throttle smooths out sudden large data drains from the device,
4428 // e.g. when it comes out of standby, which often causes problems with
4429 // (1) mixer threads without a fast mixer (which has its own warm-up)
4430 // (2) minimum buffer sized tracks (even if the track is full,
4431 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004432 //
4433 // Total time spent in last processing cycle equals time spent in
4434 // 1. threadLoop_write, as well as time spent in
4435 // 2. threadLoop_mix (significant for heavy mixing, especially
4436 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004437
Andy Hung446f4df2019-02-21 12:26:41 -08004438 // it's OK if deltaMs is an overestimate.
4439
4440 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004441
Ivan Lozanoea04d392017-11-07 14:37:07 -08004442 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004443 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004444 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004445
Andy Hung08fb1742015-05-31 23:22:10 -07004446 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004447 // notify of throttle start on verbose log
4448 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4449 "mixer(%p) throttle begin:"
4450 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004451 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004452 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004453 // Throttle must be attributed to the previous mixer loop's write time
4454 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004455 // This also ensures proper timing statistics.
4456 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004457 } else {
4458 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4459 if (diff > 0) {
4460 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004461 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004462 ALOGD_IF(!isSingleDeviceType(
4463 outDeviceTypes(), audio_is_a2dp_out_device) &&
4464 !isSingleDeviceType(
4465 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004466 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004467 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4468 }
Andy Hung08fb1742015-05-31 23:22:10 -07004469 }
4470 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004471 }
Eric Laurent81784c32012-11-19 14:55:58 -08004472
Eric Laurentbfb1b832013-01-07 09:53:42 -08004473 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004474 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004475 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004476 // suspended requires accurate metering of sleep time.
4477 if (isSuspended()) {
4478 // advance by expected sleepTime
4479 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4480 const nsecs_t nowNs = systemTime();
4481
4482 // compute expected next time vs current time.
4483 // (negative deltas are treated as delays).
4484 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4485 if (deltaNs < -kMaxNextBufferDelayNs) {
4486 // Delays longer than the max allowed trigger a reset.
4487 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4488 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4489 timeLoopNextNs = nowNs + deltaNs;
4490 } else if (deltaNs < 0) {
4491 // Delays within the max delay allowed: zero the delta/sleepTime
4492 // to help the system catch up in the next iteration(s)
4493 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4494 deltaNs = 0;
4495 }
4496 // update sleep time (which is >= 0)
4497 mSleepTimeUs = deltaNs / 1000;
4498 }
Eric Laurente93cc032016-05-05 10:15:10 -07004499 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4500 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004501 }
Glenn Kastene7754022014-10-31 12:11:26 -07004502 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004503 }
Eric Laurent81784c32012-11-19 14:55:58 -08004504 }
4505
4506 // Finally let go of removed track(s), without the lock held
4507 // since we can't guarantee the destructors won't acquire that
4508 // same lock. This will also mutate and push a new fast mixer state.
4509 threadLoop_removeTracks(tracksToRemove);
4510 tracksToRemove.clear();
4511
4512 // FIXME I don't understand the need for this here;
4513 // it was in the original code but maybe the
4514 // assignment in saveOutputTracks() makes this unnecessary?
4515 clearOutputTracks();
4516
4517 // Effect chains will be actually deleted here if they were removed from
4518 // mEffectChains list during mixing or effects processing
4519 effectChains.clear();
4520
4521 // FIXME Note that the above .clear() is no longer necessary since effectChains
4522 // is now local to this block, but will keep it for now (at least until merge done).
4523 }
4524
Eric Laurentbfb1b832013-01-07 09:53:42 -08004525 threadLoop_exit();
4526
Eric Laurentcf817a22014-08-04 20:36:31 -07004527 if (!mStandby) {
4528 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004529 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004530 }
4531
4532 releaseWakeLock();
4533
4534 ALOGV("Thread %p type %d exiting", this, mType);
4535 return false;
4536}
4537
Andy Hung4b17e882023-07-07 13:47:37 -07004538void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004539{
Dean Wheatley12473e92021-03-18 23:00:55 +11004540 if (mStandby) {
4541 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4542 return;
4543 } else if (mHwPaused) {
4544 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4545 return;
4546 }
4547
4548 // Gather the framesReleased counters for all active tracks,
4549 // and associate with the sink frames written out. We need
4550 // this to convert the sink timestamp to the track timestamp.
4551 bool kernelLocationUpdate = false;
4552 ExtendedTimestamp timestamp; // use private copy to fetch
4553
4554 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4555 // HAL may be draining some small duration buffered data for fade out.
4556 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4557 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4558 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4559 mSampleRate);
4560
4561 if (isTimestampCorrectionEnabled()) {
4562 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4563 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4564 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4565 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4566 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4567 = correctedTimestamp.mFrames;
4568 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4569 = correctedTimestamp.mTimeNs;
4570 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4571 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4572 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4573
4574 // Note: Downstream latency only added if timestamp correction enabled.
4575 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4576 const int64_t newPosition =
4577 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4578 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4579 // prevent retrograde
4580 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4581 newPosition,
4582 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4583 - mSuspendedFrames));
4584 }
4585 }
4586
4587 // We always fetch the timestamp here because often the downstream
4588 // sink will block while writing.
4589
4590 // We keep track of the last valid kernel position in case we are in underrun
4591 // and the normal mixer period is the same as the fast mixer period, or there
4592 // is some error from the HAL.
4593 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4594 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4595 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4596 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4597 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4598
4599 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4600 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4601 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4602 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4603 }
4604
4605 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4606 kernelLocationUpdate = true;
4607 } else {
4608 ALOGVV("getTimestamp error - no valid kernel position");
4609 }
4610
4611 // copy over kernel info
4612 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4613 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4614 + mSuspendedFrames; // add frames discarded when suspended
4615 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4616 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4617 } else {
4618 mTimestampVerifier.error();
4619 }
4620
4621 // mFramesWritten for non-offloaded tracks are contiguous
4622 // even after standby() is called. This is useful for the track frame
4623 // to sink frame mapping.
4624 bool serverLocationUpdate = false;
4625 if (mFramesWritten != mLastFramesWritten) {
4626 serverLocationUpdate = true;
4627 mLastFramesWritten = mFramesWritten;
4628 }
4629 // Only update timestamps if there is a meaningful change.
4630 // Either the kernel timestamp must be valid or we have written something.
4631 if (kernelLocationUpdate || serverLocationUpdate) {
4632 if (serverLocationUpdate) {
4633 // use the time before we called the HAL write - it is a bit more accurate
4634 // to when the server last read data than the current time here.
4635 //
4636 // If we haven't written anything, mLastIoBeginNs will be -1
4637 // and we use systemTime().
4638 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4639 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4640 ? systemTime() : mLastIoBeginNs;
4641 }
4642
Andy Hung11e74242023-06-26 19:20:57 -07004643 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004644 if (!t->isFastTrack()) {
4645 t->updateTrackFrameInfo(
Andy Hung11e74242023-06-26 19:20:57 -07004646 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004647 mFramesWritten,
4648 mSampleRate,
4649 mTimestamp);
4650 }
4651 }
4652 }
4653
4654 if (audio_has_proportional_frames(mFormat)) {
4655 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4656 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4657 mLatencyMs.add(latencyMs);
4658 }
4659 }
4660#if 0
4661 // logFormat example
4662 if (z % 100 == 0) {
4663 timespec ts;
4664 clock_gettime(CLOCK_MONOTONIC, &ts);
4665 LOGT("This is an integer %d, this is a float %f, this is my "
4666 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4667 LOGT("A deceptive null-terminated string %\0");
4668 }
4669 ++z;
4670#endif
4671}
4672
Eric Laurentbfb1b832013-01-07 09:53:42 -08004673// removeTracks_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07004674void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hung920f6572022-10-06 12:09:49 -07004675NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurentbfb1b832013-01-07 09:53:42 -08004676{
Andy Hungfe726a62018-09-27 15:17:25 -07004677 for (const auto& track : tracksToRemove) {
4678 mActiveTracks.remove(track);
4679 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004680 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004681 if (chain != 0) {
4682 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4683 __func__, track->id(), chain.get(), track->sessionId());
4684 chain->decActiveTrackCnt();
4685 }
4686 // If an external client track, inform APM we're no longer active, and remove if needed.
4687 // We do this under lock so that the state is consistent if the Track is destroyed.
4688 if (track->isExternalTrack()) {
4689 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004690 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004691 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004692 }
4693 }
Andy Hungfe726a62018-09-27 15:17:25 -07004694 if (track->isTerminated()) {
4695 // remove from our tracks vector
4696 removeTrack_l(track);
4697 }
jiabineb3bda02020-06-30 14:07:03 -07004698 if (mHapticChannelCount > 0 &&
4699 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4700 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004701 mLock.unlock();
4702 // Unlock due to VibratorService will lock for this call and will
4703 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung76cb9152023-07-20 21:23:42 -07004704 afutils::onExternalVibrationStop(track->getExternalVibration());
jiabin57303cc2018-12-18 15:45:57 -08004705 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004706
4707 // When the track is stop, set the haptic intensity as MUTE
4708 // for the HapticGenerator effect.
4709 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004710 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004711 }
jiabin245cdd92018-12-07 17:55:15 -08004712 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004713 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004714}
Eric Laurent81784c32012-11-19 14:55:58 -08004715
Andy Hung4b17e882023-07-07 13:47:37 -07004716status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004717{
4718 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004719 ExtendedTimestamp ets;
4720 status_t status = mNormalSink->getTimestamp(ets);
4721 if (status == NO_ERROR) {
4722 status = ets.getBestTimestamp(&timestamp);
4723 }
4724 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004725 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004726 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004727 collectTimestamps_l();
4728 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4729 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004730 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004731 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4732 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4733 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4734 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4735 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004736 }
4737 return INVALID_OPERATION;
4738}
Eric Laurent1c333e22014-05-20 10:48:17 -07004739
Eric Laurenteab90452019-06-24 15:17:46 -07004740// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4741// still applied by the mixer.
4742// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4743// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4744// if more than one track are active
Andy Hung4b17e882023-07-07 13:47:37 -07004745status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004746{
4747 status_t result = NO_ERROR;
4748 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4749 if (*volume != mLeftVolFloat) {
4750 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004751 // HAL can return INVALID_OPERATION if operation is not supported.
4752 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004753 "Error when setting output stream volume: %d", result);
4754 if (result == NO_ERROR) {
4755 mLeftVolFloat = *volume;
4756 }
4757 }
4758 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4759 // remove stream volume contribution from software volume.
4760 if (mLeftVolFloat == *volume) {
4761 *volume = 1.0f;
4762 }
4763 }
4764 return result;
4765}
4766
Andy Hung4b17e882023-07-07 13:47:37 -07004767status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004768 audio_patch_handle_t *handle)
4769{
Andy Hungf60abce2016-08-26 11:37:54 -07004770 status_t status;
4771 if (property_get_bool("af.patch_park", false /* default_value */)) {
4772 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4773 // or if HAL does not properly lock against access.
4774 AutoPark<FastMixer> park(mFastMixer);
4775 status = PlaybackThread::createAudioPatch_l(patch, handle);
4776 } else {
4777 status = PlaybackThread::createAudioPatch_l(patch, handle);
4778 }
Eric Laurentb0463942022-12-20 16:31:10 +01004779
4780 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004781 return status;
4782}
4783
Andy Hung4b17e882023-07-07 13:47:37 -07004784status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004785 audio_patch_handle_t *handle)
4786{
4787 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004788
4789 // store new device and send to effects
4790 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004791 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004792 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004793 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4794 && !mOutput->audioHwDev->supportsAudioPatches(),
4795 "Enumerated device type(%#x) must not be used "
4796 "as it does not support audio patches",
4797 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004798 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004799 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4800 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004801 }
4802
François Gaffie0c280aa2018-07-25 10:02:15 +02004803 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004804#ifdef ADD_BATTERY_DATA
4805 // when changing the audio output device, call addBatteryData to notify
4806 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004807 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004808 uint32_t params = 0;
4809 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004810 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004811 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004812 }
4813
Eric Laurent054d9d32015-04-24 08:48:48 -07004814 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004815 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004816 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4817 }
4818
4819 if (params != 0) {
4820 addBatteryData(params);
4821 }
4822 }
4823#endif
4824
4825 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004826 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004827 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004828
jiabinc52b1ff2019-10-31 17:20:42 -07004829 // mPatch.num_sinks is not set when the thread is created so that
4830 // the first patch creation triggers an ioConfigChanged callback
4831 bool configChanged = (mPatch.num_sinks == 0) ||
4832 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004833 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004834 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004835 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004836
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004837 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004838 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4839 status = hwDevice->createAudioPatch(patch->num_sources,
4840 patch->sources,
4841 patch->num_sinks,
4842 patch->sinks,
4843 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004844 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004845 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004846 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004847 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004848 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004849
4850 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004851 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004852 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004853 // also dispatch to active AudioTracks for MediaMetrics
4854 for (const auto &track : mActiveTracks) {
4855 track->logEndInterval();
4856 track->logBeginInterval(patchSinksAsString);
4857 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004858
Eric Laurente8726fe2015-06-26 09:39:24 -07004859 if (configChanged) {
4860 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4861 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004862 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004863 mActiveTracks.setHasChanged();
4864
Eric Laurent1c333e22014-05-20 10:48:17 -07004865 return status;
4866}
4867
Andy Hung4b17e882023-07-07 13:47:37 -07004868status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004869{
Andy Hungf60abce2016-08-26 11:37:54 -07004870 status_t status;
4871 if (property_get_bool("af.patch_park", false /* default_value */)) {
4872 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4873 // or if HAL does not properly lock against access.
4874 AutoPark<FastMixer> park(mFastMixer);
4875 status = PlaybackThread::releaseAudioPatch_l(handle);
4876 } else {
4877 status = PlaybackThread::releaseAudioPatch_l(handle);
4878 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004879 return status;
4880}
4881
Andy Hung4b17e882023-07-07 13:47:37 -07004882status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004883{
4884 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004885
jiabinc52b1ff2019-10-31 17:20:42 -07004886 mPatch = audio_patch{};
4887 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004888
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004889 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004890 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4891 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004892 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004893 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004894 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004895 // Force meteadata update after a route change
4896 mActiveTracks.setHasChanged();
4897
Eric Laurent1c333e22014-05-20 10:48:17 -07004898 return status;
4899}
4900
Andy Hung4b17e882023-07-07 13:47:37 -07004901void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004902{
4903 Mutex::Autolock _l(mLock);
4904 mTracks.add(track);
4905}
4906
Andy Hung4b17e882023-07-07 13:47:37 -07004907void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004908{
4909 Mutex::Autolock _l(mLock);
4910 destroyTrack_l(track);
4911}
4912
Andy Hung4b17e882023-07-07 13:47:37 -07004913void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07004914{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004915 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004916 config->role = AUDIO_PORT_ROLE_SOURCE;
4917 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4918 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004919 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4920 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4921 config->flags.output = mOutput->flags;
4922 }
Eric Laurent83b88082014-06-20 18:31:16 -07004923}
4924
Eric Laurent81784c32012-11-19 14:55:58 -08004925// ----------------------------------------------------------------------------
4926
Andy Hung4b17e882023-07-07 13:47:37 -07004927/* static */
4928sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung7535ed92023-07-17 17:05:00 -07004929 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hung4b17e882023-07-07 13:47:37 -07004930 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung7535ed92023-07-17 17:05:00 -07004931 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hung4b17e882023-07-07 13:47:37 -07004932}
4933
Andy Hung7535ed92023-07-17 17:05:00 -07004934MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004935 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07004936 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004937 // mAudioMixer below
4938 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01004939 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004940 mFastMixerFutex(0),
4941 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004942 // mOutputSink below
4943 // mPipeSink below
4944 // mNormalSink below
4945{
Andy Hung7535ed92023-07-17 17:05:00 -07004946 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004947 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004948 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004949 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004950 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4951 mNormalFrameCount);
4952 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4953
Andy Hungfbfc3952015-01-15 13:33:51 -08004954 if (type == DUPLICATING) {
4955 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4956 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4957 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4958 return;
4959 }
Eric Laurent81784c32012-11-19 14:55:58 -08004960 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004961 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004962 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004963 const NBAIO_Format offers[1] = {Format_from_SR_C(
4964 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004965#if !LOG_NDEBUG
4966 ssize_t index =
4967#else
4968 (void)
4969#endif
4970 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004971 ALOG_ASSERT(index == 0);
4972
4973 // initialize fast mixer depending on configuration
4974 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00004975 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08004976 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004977 } else {
4978 switch (kUseFastMixer) {
4979 case FastMixer_Never:
4980 initFastMixer = false;
4981 break;
4982 case FastMixer_Always:
4983 initFastMixer = true;
4984 break;
4985 case FastMixer_Static:
4986 case FastMixer_Dynamic:
4987 initFastMixer = mFrameCount < mNormalFrameCount;
4988 break;
4989 }
4990 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4991 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4992 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004993 }
4994 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004995 audio_format_t fastMixerFormat;
4996 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4997 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4998 } else {
4999 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5000 }
5001 if (mFormat != fastMixerFormat) {
5002 // change our Sink format to accept our intermediate precision
5003 mFormat = fastMixerFormat;
5004 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005005 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005006 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5007 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5008 }
Eric Laurent81784c32012-11-19 14:55:58 -08005009
5010 // create a MonoPipe to connect our submix to FastMixer
5011 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005012
Andy Hung1258c1a2014-05-23 21:22:17 -07005013 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005014 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005015 format.mFormat = fastMixerFormat;
5016 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5017
Eric Laurent81784c32012-11-19 14:55:58 -08005018 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5019 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5020 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5021 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005022 const NBAIO_Format offersFast[1] = {format};
5023 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005024#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005025 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005026#else
5027 (void)
5028#endif
Andy Hung920f6572022-10-06 12:09:49 -07005029 monoPipe->negotiate(offersFast, std::size(offersFast),
5030 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005031 ALOG_ASSERT(index == 0);
5032 monoPipe->setAvgFrames((mScreenState & 1) ?
5033 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5034 mPipeSink = monoPipe;
5035
Eric Laurent81784c32012-11-19 14:55:58 -08005036 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005037 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005038 FastMixerStateQueue *sq = mFastMixer->sq();
5039#ifdef STATE_QUEUE_DUMP
5040 sq->setObserverDump(&mStateQueueObserverDump);
5041 sq->setMutatorDump(&mStateQueueMutatorDump);
5042#endif
5043 FastMixerState *state = sq->begin();
5044 FastTrack *fastTrack = &state->mFastTracks[0];
5045 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5046 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5047 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005048 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5049 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5050 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005051 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005052 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07005053 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01005054 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005055 fastTrack->mGeneration++;
5056 state->mFastTracksGen++;
5057 state->mTrackMask = 1;
5058 // fast mixer will use the HAL output sink
5059 state->mOutputSink = mOutputSink.get();
5060 state->mOutputSinkGen++;
5061 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005062 // specify sink channel mask when haptic channel mask present as it can not
5063 // be calculated directly from channel count
5064 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005065 ? AUDIO_CHANNEL_NONE
5066 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005067 state->mCommand = FastMixerState::COLD_IDLE;
5068 // already done in constructor initialization list
5069 //mFastMixerFutex = 0;
5070 state->mColdFutexAddr = &mFastMixerFutex;
5071 state->mColdGen++;
5072 state->mDumpState = &mFastMixerDumpState;
Andy Hung7535ed92023-07-17 17:05:00 -07005073 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005074 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005075 sq->end();
5076 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5077
Eric Tan0513b5d2018-09-17 10:32:48 -07005078 NBLog::thread_info_t info;
5079 info.id = mId;
5080 info.type = NBLog::FASTMIXER;
5081 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5082
Eric Laurent81784c32012-11-19 14:55:58 -08005083 // start the fast mixer
5084 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5085 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005086 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005087 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005088
5089#ifdef AUDIO_WATCHDOG
5090 // create and start the watchdog
5091 mAudioWatchdog = new AudioWatchdog();
5092 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5093 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5094 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005095 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005096#endif
Andy Hung8946a282018-04-19 20:04:56 -07005097 } else {
5098#ifdef TEE_SINK
5099 // Only use the MixerThread tee if there is no FastMixer.
5100 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5101 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5102#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005103 }
5104
5105 switch (kUseFastMixer) {
5106 case FastMixer_Never:
5107 case FastMixer_Dynamic:
5108 mNormalSink = mOutputSink;
5109 break;
5110 case FastMixer_Always:
5111 mNormalSink = mPipeSink;
5112 break;
5113 case FastMixer_Static:
5114 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5115 break;
5116 }
5117}
5118
Andy Hung4b17e882023-07-07 13:47:37 -07005119MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005120{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005121 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005122 FastMixerStateQueue *sq = mFastMixer->sq();
5123 FastMixerState *state = sq->begin();
5124 if (state->mCommand == FastMixerState::COLD_IDLE) {
5125 int32_t old = android_atomic_inc(&mFastMixerFutex);
5126 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005127 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005128 }
5129 }
5130 state->mCommand = FastMixerState::EXIT;
5131 sq->end();
5132 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5133 mFastMixer->join();
5134 // Though the fast mixer thread has exited, it's state queue is still valid.
5135 // We'll use that extract the final state which contains one remaining fast track
5136 // corresponding to our sub-mix.
5137 state = sq->begin();
5138 ALOG_ASSERT(state->mTrackMask == 1);
5139 FastTrack *fastTrack = &state->mFastTracks[0];
5140 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5141 delete fastTrack->mBufferProvider;
5142 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005143 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005144#ifdef AUDIO_WATCHDOG
5145 if (mAudioWatchdog != 0) {
5146 mAudioWatchdog->requestExit();
5147 mAudioWatchdog->requestExitAndWait();
5148 mAudioWatchdog.clear();
5149 }
5150#endif
5151 }
Andy Hung7535ed92023-07-17 17:05:00 -07005152 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005153 delete mAudioMixer;
5154}
5155
Andy Hung4b17e882023-07-07 13:47:37 -07005156void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005157 PlaybackThread::onFirstRef();
5158
5159 Mutex::Autolock _l(mLock);
5160 if (mOutput != nullptr && mOutput->stream != nullptr) {
5161 status_t status = mOutput->stream->setLatencyModeCallback(this);
5162 if (status != INVALID_OPERATION) {
5163 updateHalSupportedLatencyModes_l();
5164 }
5165 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5166 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5167 mBluetoothLatencyModesEnabled.store(
5168 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5169 }
5170}
Eric Laurent81784c32012-11-19 14:55:58 -08005171
Andy Hung4b17e882023-07-07 13:47:37 -07005172uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005173{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005174 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005175 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5176 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5177 }
5178 return latency;
5179}
5180
Andy Hung4b17e882023-07-07 13:47:37 -07005181ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005182{
5183 // FIXME we should only do one push per cycle; confirm this is true
5184 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005185 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005186 FastMixerStateQueue *sq = mFastMixer->sq();
5187 FastMixerState *state = sq->begin();
5188 if (state->mCommand != FastMixerState::MIX_WRITE &&
5189 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5190 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005191
5192 // FIXME workaround for first HAL write being CPU bound on some devices
5193 ATRACE_BEGIN("write");
5194 mOutput->write((char *)mSinkBuffer, 0);
5195 ATRACE_END();
5196
Eric Laurent81784c32012-11-19 14:55:58 -08005197 int32_t old = android_atomic_inc(&mFastMixerFutex);
5198 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005199 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005200 }
5201#ifdef AUDIO_WATCHDOG
5202 if (mAudioWatchdog != 0) {
5203 mAudioWatchdog->resume();
5204 }
5205#endif
5206 }
5207 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005208#ifdef FAST_THREAD_STATISTICS
Andy Hung7535ed92023-07-17 17:05:00 -07005209 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005210 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005211#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005212 sq->end();
5213 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5214 if (kUseFastMixer == FastMixer_Dynamic) {
5215 mNormalSink = mPipeSink;
5216 }
5217 } else {
5218 sq->end(false /*didModify*/);
5219 }
5220 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005221 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005222}
5223
Andy Hung4b17e882023-07-07 13:47:37 -07005224void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005225{
5226 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005227 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005228 FastMixerStateQueue *sq = mFastMixer->sq();
5229 FastMixerState *state = sq->begin();
5230 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005231 // Report any frames trapped in the Monopipe
5232 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5233 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5234 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5235 "monoPipeWritten:%lld monoPipeLeft:%lld",
5236 (long long)mFramesWritten, (long long)mSuspendedFrames,
5237 (long long)mPipeSink->framesWritten(), pipeFrames);
5238 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5239
Eric Laurent81784c32012-11-19 14:55:58 -08005240 state->mCommand = FastMixerState::COLD_IDLE;
5241 state->mColdFutexAddr = &mFastMixerFutex;
5242 state->mColdGen++;
5243 mFastMixerFutex = 0;
5244 sq->end();
5245 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5246 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5247 if (kUseFastMixer == FastMixer_Dynamic) {
5248 mNormalSink = mOutputSink;
5249 }
5250#ifdef AUDIO_WATCHDOG
5251 if (mAudioWatchdog != 0) {
5252 mAudioWatchdog->pause();
5253 }
5254#endif
5255 } else {
5256 sq->end(false /*didModify*/);
5257 }
5258 }
5259 PlaybackThread::threadLoop_standby();
5260}
5261
Andy Hung4b17e882023-07-07 13:47:37 -07005262bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005263{
5264 return false;
5265}
5266
Andy Hung4b17e882023-07-07 13:47:37 -07005267bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005268{
5269 return !mStandby;
5270}
5271
Andy Hung4b17e882023-07-07 13:47:37 -07005272bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005273{
5274 Mutex::Autolock _l(mLock);
5275 return waitingAsyncCallback_l();
5276}
5277
Eric Laurent81784c32012-11-19 14:55:58 -08005278// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung4b17e882023-07-07 13:47:37 -07005279void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005280{
5281 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005282 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005283 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005284 // discard any pending drain or write ack by incrementing sequence
5285 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5286 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005287 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005288 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5289 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005290 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005291 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005292 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005293}
5294
Andy Hung4b17e882023-07-07 13:47:37 -07005295void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005296{
5297 ALOGV("signal playback thread");
5298 broadcast_l();
5299}
5300
Andy Hung4b17e882023-07-07 13:47:37 -07005301void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005302{
5303 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5304 invalidateTracks((audio_stream_type_t)i);
5305 }
5306}
5307
Andy Hung4b17e882023-07-07 13:47:37 -07005308void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005309{
Eric Laurent81784c32012-11-19 14:55:58 -08005310 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005311 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005312 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005313 // increase sleep time progressively when application underrun condition clears.
5314 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5315 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5316 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005317 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005318 sleepTimeShift--;
5319 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005320 mSleepTimeUs = 0;
5321 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005322 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005323
Eric Laurent81784c32012-11-19 14:55:58 -08005324}
5325
Andy Hung4b17e882023-07-07 13:47:37 -07005326void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005327{
5328 // If no tracks are ready, sleep once for the duration of an output
5329 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005330 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005331 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005332 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5333 // Using the Monopipe availableToWrite, we estimate the
5334 // sleep time to retry for more data (before we underrun).
5335 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5336 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5337 const size_t pipeFrames = monoPipe->maxFrames();
5338 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5339 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5340 const size_t framesDelay = std::min(
5341 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5342 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5343 pipeFrames, framesLeft, framesDelay);
5344 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5345 } else {
5346 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5347 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5348 mSleepTimeUs = kMinThreadSleepTimeUs;
5349 }
5350 // reduce sleep time in case of consecutive application underruns to avoid
5351 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5352 // duration we would end up writing less data than needed by the audio HAL if
5353 // the condition persists.
5354 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5355 sleepTimeShift++;
5356 }
Eric Laurent81784c32012-11-19 14:55:58 -08005357 }
5358 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005359 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005360 }
5361 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005362 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5363 // before effects processing or output.
5364 if (mMixerBufferValid) {
5365 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005366 if (mType == SPATIALIZER) {
5367 memset(mSinkBuffer, 0, mSinkBufferSize);
5368 }
Andy Hung98ef9782014-03-04 14:46:50 -08005369 } else {
5370 memset(mSinkBuffer, 0, mSinkBufferSize);
5371 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005372 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005373 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5374 "anticipated start");
5375 }
5376 // TODO add standby time extension fct of effect tail
5377}
5378
5379// prepareTracks_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07005380PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07005381 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005382{
Andy Hungc0691382018-09-12 18:01:57 -07005383 // clean up deleted track ids in AudioMixer before allocating new tracks
5384 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5385 // for each trackId, destroy it in the AudioMixer
5386 if (mAudioMixer->exists(trackId)) {
5387 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005388 }
5389 });
Andy Hungc0691382018-09-12 18:01:57 -07005390 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005391
5392 mixer_state mixerStatus = MIXER_IDLE;
5393 // find out which tracks need to be processed
5394 size_t count = mActiveTracks.size();
5395 size_t mixedTracks = 0;
5396 size_t tracksWithEffect = 0;
5397 // counts only _active_ fast tracks
5398 size_t fastTracks = 0;
5399 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5400
5401 float masterVolume = mMasterVolume;
5402 bool masterMute = mMasterMute;
5403
5404 if (masterMute) {
5405 masterVolume = 0;
5406 }
5407 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005408 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005409 if (chain != 0) {
5410 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5411 chain->setVolume_l(&v, &v);
5412 masterVolume = (float)((v + (1 << 23)) >> 24);
5413 chain.clear();
5414 }
5415
5416 // prepare a new state to push
5417 FastMixerStateQueue *sq = NULL;
5418 FastMixerState *state = NULL;
5419 bool didModify = false;
5420 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005421 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005422 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005423 sq = mFastMixer->sq();
5424 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005425 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005426 }
5427
Andy Hung69aed5f2014-02-25 17:24:40 -08005428 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005429 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005430
Andy Hungbd3b2b02018-05-21 10:53:11 -07005431 // DeferredOperations handles statistics after setting mixerStatus.
5432 class DeferredOperations {
5433 public:
Andy Hungea840382020-05-05 21:50:17 -07005434 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5435 : mMixerStatus(mixerStatus)
5436 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005437
5438 // when leaving scope, tally frames properly.
5439 ~DeferredOperations() {
5440 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5441 // because that is when the underrun occurs.
5442 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005443 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005444 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005445 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005446 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005447 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005448 }
5449 }
Andy Hungea840382020-05-05 21:50:17 -07005450 // send the max underrun frames for this mixer period
5451 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005452 }
5453
5454 // tallyUnderrunFrames() is called to update the track counters
5455 // with the number of underrun frames for a particular mixer period.
5456 // We defer tallying until we know the final mixer status.
Andy Hung11e74242023-06-26 19:20:57 -07005457 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005458 mUnderrunFrames.emplace_back(track, underrunFrames);
5459 }
5460
5461 private:
5462 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005463 ThreadMetrics * const mThreadMetrics;
Andy Hung11e74242023-06-26 19:20:57 -07005464 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005465 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005466 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005467
jiabin245cdd92018-12-07 17:55:15 -08005468 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005469 for (size_t i=0 ; i<count ; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07005470 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005471
5472 // this const just means the local variable doesn't change
Andy Hung11e74242023-06-26 19:20:57 -07005473 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005474
5475 // process fast tracks
5476 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005477 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5478 "%s(%d): FastTrack(%d) present without FastMixer",
5479 __func__, id(), track->id());
5480
jiabin245cdd92018-12-07 17:55:15 -08005481 if (track->getHapticPlaybackEnabled()) {
5482 noFastHapticTrack = false;
5483 }
Eric Laurent81784c32012-11-19 14:55:58 -08005484
5485 // It's theoretically possible (though unlikely) for a fast track to be created
5486 // and then removed within the same normal mix cycle. This is not a problem, as
5487 // the track never becomes active so it's fast mixer slot is never touched.
5488 // The converse, of removing an (active) track and then creating a new track
5489 // at the identical fast mixer slot within the same normal mix cycle,
5490 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung11e74242023-06-26 19:20:57 -07005491 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005492 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005493 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5494 FastTrack *fastTrack = &state->mFastTracks[j];
5495
5496 // Determine whether the track is currently in underrun condition,
5497 // and whether it had a recent underrun.
5498 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5499 FastTrackUnderruns underruns = ftDump->mUnderruns;
5500 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung11e74242023-06-26 19:20:57 -07005501 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005502 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung11e74242023-06-26 19:20:57 -07005503 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005504 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung11e74242023-06-26 19:20:57 -07005505 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005506 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung11e74242023-06-26 19:20:57 -07005507 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005508 // don't count underruns that occur while stopping or pausing
5509 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005510 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005511 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5512 recentUnderruns > 0) {
5513 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005514 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005515 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005516 // Immediately account for FastTrack underruns.
Andy Hung11e74242023-06-26 19:20:57 -07005517 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005518
5519 // This is similar to the state machine for normal tracks,
5520 // with a few modifications for fast tracks.
5521 bool isActive = true;
Andy Hung11e74242023-06-26 19:20:57 -07005522 switch (track->state()) {
5523 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005524 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005525 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung11e74242023-06-26 19:20:57 -07005526 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005527 }
5528 break;
Andy Hung11e74242023-06-26 19:20:57 -07005529 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005530 // ramp down is not yet implemented
5531 track->setPaused();
5532 break;
Andy Hung11e74242023-06-26 19:20:57 -07005533 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005534 // ramp up is not yet implemented
Andy Hung11e74242023-06-26 19:20:57 -07005535 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005536 break;
Andy Hung11e74242023-06-26 19:20:57 -07005537 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005538 if (recentFull > 0 || recentPartial > 0) {
5539 // track has provided at least some frames recently: reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07005540 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005541 }
5542 if (recentUnderruns == 0) {
5543 // no recent underruns: stay active
5544 break;
5545 }
5546 // there has recently been an underrun of some kind
5547 if (track->sharedBuffer() == 0) {
5548 // were any of the recent underruns "empty" (no frames available)?
5549 if (recentEmpty == 0) {
5550 // no, then ignore the partial underruns as they are allowed indefinitely
5551 break;
5552 }
5553 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung11e74242023-06-26 19:20:57 -07005554 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005555 break;
5556 }
5557 // indicate to client process that the track was disabled because of underrun;
5558 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005559 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005560 // remove from active list, but state remains ACTIVE [confusing but true]
5561 isActive = false;
5562 break;
5563 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005564 FALLTHROUGH_INTENDED;
Andy Hung11e74242023-06-26 19:20:57 -07005565 case IAfTrackBase::STOPPING_2:
5566 case IAfTrackBase::PAUSED:
5567 case IAfTrackBase::STOPPED:
5568 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005569 // Check for presentation complete if track is inactive
5570 // We have consumed all the buffers of this track.
5571 // This would be incomplete if we auto-paused on underrun
5572 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005573 uint32_t latency = 0;
5574 status_t result = mOutput->stream->getLatency(&latency);
5575 ALOGE_IF(result != OK,
5576 "Error when retrieving output stream latency: %d", result);
5577 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005578 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005579 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5580 // track stays in active list until presentation is complete
5581 break;
5582 }
5583 }
5584 if (track->isStopping_2()) {
Andy Hung11e74242023-06-26 19:20:57 -07005585 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005586 }
5587 if (track->isStopped()) {
5588 // Can't reset directly, as fast mixer is still polling this track
5589 // track->reset();
5590 // So instead mark this track as needing to be reset after push with ack
5591 resetMask |= 1 << i;
5592 }
5593 isActive = false;
5594 break;
Andy Hung11e74242023-06-26 19:20:57 -07005595 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005596 default:
Andy Hung11e74242023-06-26 19:20:57 -07005597 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005598 }
5599
5600 if (isActive) {
5601 // was it previously inactive?
5602 if (!(state->mTrackMask & (1 << j))) {
Andy Hung11e74242023-06-26 19:20:57 -07005603 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5604 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005605 fastTrack->mBufferProvider = eabp;
5606 fastTrack->mVolumeProvider = vp;
Andy Hung11e74242023-06-26 19:20:57 -07005607 fastTrack->mChannelMask = track->channelMask();
5608 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005609 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005610 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005611 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005612 fastTrack->mGeneration++;
5613 state->mTrackMask |= 1 << j;
5614 didModify = true;
5615 // no acknowledgement required for newly active tracks
5616 }
Andy Hung11e74242023-06-26 19:20:57 -07005617 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005618 float volume;
5619 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5620 volume = 0.f;
5621 } else {
5622 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5623 }
5624
5625 handleVoipVolume_l(&volume);
5626
Eric Laurent81784c32012-11-19 14:55:58 -08005627 // cache the combined master volume and stream type volume for fast mixer; this
5628 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005629 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005630 proxy->framesReleased()).first;
5631 volume *= vh;
Andy Hung11e74242023-06-26 19:20:57 -07005632 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005633 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005634 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5635 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5636
Andy Hung7535ed92023-07-17 17:05:00 -07005637 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005638 /*muteState=*/{masterVolume == 0.f,
5639 mStreamTypes[track->streamType()].volume == 0.f,
5640 mStreamTypes[track->streamType()].mute,
5641 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005642 vlf == 0.f && vrf == 0.f,
5643 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005644
5645 vlf *= volume;
5646 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005647
jiabin76d94692022-12-15 21:51:21 +00005648 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005649 ++fastTracks;
5650 } else {
5651 // was it previously active?
5652 if (state->mTrackMask & (1 << j)) {
5653 fastTrack->mBufferProvider = NULL;
5654 fastTrack->mGeneration++;
5655 state->mTrackMask &= ~(1 << j);
5656 didModify = true;
5657 // If any fast tracks were removed, we must wait for acknowledgement
5658 // because we're about to decrement the last sp<> on those tracks.
5659 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5660 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005661 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5662 // AudioTrack may start (which may not be with a start() but with a write()
5663 // after underrun) and immediately paused or released. In that case the
5664 // FastTrack state hasn't had time to update.
5665 // TODO Remove the ALOGW when this theory is confirmed.
5666 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005667 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung11e74242023-06-26 19:20:57 -07005668 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005669 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005670 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005671 }
5672 tracksToRemove->add(track);
5673 // Avoids a misleading display in dumpsys
Andy Hung11e74242023-06-26 19:20:57 -07005674 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005675 }
jiabin245cdd92018-12-07 17:55:15 -08005676 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5677 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5678 didModify = true;
5679 }
Eric Laurent81784c32012-11-19 14:55:58 -08005680 continue;
5681 }
5682
5683 { // local variable scope to avoid goto warning
5684
5685 audio_track_cblk_t* cblk = track->cblk();
5686
5687 // The first time a track is added we wait
5688 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005689 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005690
5691 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005692 // use the trackId as the AudioMixer name.
5693 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005694 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005695 trackId,
Andy Hung11e74242023-06-26 19:20:57 -07005696 track->channelMask(),
5697 track->format(),
5698 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005699 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005700 ALOGW("%s(): AudioMixer cannot create track(%d)"
5701 " mask %#x, format %#x, sessionId %d",
5702 __func__, trackId,
Andy Hung11e74242023-06-26 19:20:57 -07005703 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005704 tracksToRemove->add(track);
5705 track->invalidate(); // consider it dead.
5706 continue;
5707 }
5708 }
5709
Eric Laurent81784c32012-11-19 14:55:58 -08005710 // make sure that we have enough frames to mix one full buffer.
5711 // enforce this condition only once to enable draining the buffer in case the client
5712 // app does not call stop() and relies on underrun to stop:
5713 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5714 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005715 size_t desiredFrames;
Andy Hung11e74242023-06-26 19:20:57 -07005716 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5717 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005718
5719 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005720 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005721 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5722 // add frames already consumed but not yet released by the resampler
5723 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005724 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005725
Eric Laurent81784c32012-11-19 14:55:58 -08005726 uint32_t minFrames = 1;
5727 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5728 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005729 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005730 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005731
5732 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005733 if (ATRACE_ENABLED()) {
5734 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005735 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005736 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005737 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005738 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005739 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005740 !track->isPaused() && !track->isTerminated())
5741 {
Andy Hungc0691382018-09-12 18:01:57 -07005742 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005743
5744 mixedTracks++;
5745
Andy Hung69aed5f2014-02-25 17:24:40 -08005746 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5747 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005748 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005749 if (track->mainBuffer() != mSinkBuffer &&
5750 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005751 if (mEffectBufferEnabled) {
5752 mEffectBufferValid = true; // Later can set directly.
5753 }
Eric Laurent81784c32012-11-19 14:55:58 -08005754 chain = getEffectChain_l(track->sessionId());
5755 // Delegate volume control to effect in track effect chain if needed
5756 if (chain != 0) {
5757 tracksWithEffect++;
5758 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005759 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005760 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005761 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005762 }
5763 }
5764
5765
5766 int param = AudioMixer::VOLUME;
Andy Hung11e74242023-06-26 19:20:57 -07005767 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005768 // no ramp for the first volume setting
Andy Hung11e74242023-06-26 19:20:57 -07005769 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5770 if (track->state() == IAfTrackBase::RESUMING) {
5771 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005772 // If a new track is paused immediately after start, do not ramp on resume.
5773 if (cblk->mServer != 0) {
5774 param = AudioMixer::RAMP_VOLUME;
5775 }
Eric Laurent81784c32012-11-19 14:55:58 -08005776 }
Andy Hungc0691382018-09-12 18:01:57 -07005777 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005778 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005779 // FIXME should not make a decision based on mServer
5780 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005781 // If the track is stopped before the first frame was mixed,
5782 // do not apply ramp
5783 param = AudioMixer::RAMP_VOLUME;
5784 }
5785
5786 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005787 uint32_t vl, vr; // in U8.24 integer format
5788 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005789 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005790 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005791 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung11e74242023-06-26 19:20:57 -07005792 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005793 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung11e74242023-06-26 19:20:57 -07005794 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005795
Eric Laurenteab90452019-06-24 15:17:46 -07005796 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5797 v = 0;
5798 }
5799
5800 handleVoipVolume_l(&v);
5801
5802 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005803 vl = vr = 0;
5804 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005805 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005806 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005807 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005808 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5809 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005810 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005811 if (vlf > GAIN_FLOAT_UNITY) {
5812 ALOGV("Track left volume out of range: %.3g", vlf);
5813 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005814 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005815 if (vrf > GAIN_FLOAT_UNITY) {
5816 ALOGV("Track right volume out of range: %.3g", vrf);
5817 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005818 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005819
Andy Hung7535ed92023-07-17 17:05:00 -07005820 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005821 /*muteState=*/{masterVolume == 0.f,
5822 mStreamTypes[track->streamType()].volume == 0.f,
5823 mStreamTypes[track->streamType()].mute,
5824 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005825 vlf == 0.f && vrf == 0.f,
5826 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005827
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005828 // now apply the master volume and stream type volume and shaper volume
5829 vlf *= v * vh;
5830 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005831 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005832 // then derive vl and vr as U8.24 versions for the effect chain
5833 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5834 vl = (uint32_t) (scaleto8_24 * vlf);
5835 vr = (uint32_t) (scaleto8_24 * vrf);
5836 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005837 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005838 // send level comes from shared memory and so may be corrupt
5839 if (sendLevel > MAX_GAIN_INT) {
5840 ALOGV("Track send level out of range: %04X", sendLevel);
5841 sendLevel = MAX_GAIN_INT;
5842 }
Andy Hung6be49402014-05-30 10:42:03 -07005843 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5844 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005845 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005846
jiabin76d94692022-12-15 21:51:21 +00005847 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005848
Eric Laurent81784c32012-11-19 14:55:58 -08005849 // Delegate volume control to effect in track effect chain if needed
5850 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5851 // Do not ramp volume if volume is controlled by effect
5852 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005853 // Update remaining floating point volume levels
5854 vlf = (float)vl / (1 << 24);
5855 vrf = (float)vr / (1 << 24);
Andy Hung11e74242023-06-26 19:20:57 -07005856 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005857 } else {
5858 // force no volume ramp when volume controller was just disabled or removed
5859 // from effect chain to avoid volume spike
Andy Hung11e74242023-06-26 19:20:57 -07005860 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005861 param = AudioMixer::VOLUME;
5862 }
Andy Hung11e74242023-06-26 19:20:57 -07005863 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005864 }
5865
Eric Laurent81784c32012-11-19 14:55:58 -08005866 // XXX: these things DON'T need to be done each time
Andy Hung11e74242023-06-26 19:20:57 -07005867 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005868 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005869
Andy Hungc0691382018-09-12 18:01:57 -07005870 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5871 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5872 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005873 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005874 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005875 AudioMixer::TRACK,
5876 AudioMixer::FORMAT, (void *)track->format());
5877 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005878 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005879 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005880 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005881
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005882 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005883 mAudioMixer->setParameter(
5884 trackId,
5885 AudioMixer::TRACK,
5886 AudioMixer::MIXER_CHANNEL_MASK,
5887 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5888 } else {
5889 mAudioMixer->setParameter(
5890 trackId,
5891 AudioMixer::TRACK,
5892 AudioMixer::MIXER_CHANNEL_MASK,
5893 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5894 }
5895
Glenn Kastene3aa6592012-12-04 12:22:46 -08005896 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005897 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005898 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005899 if (reqSampleRate == 0) {
5900 reqSampleRate = mSampleRate;
5901 } else if (reqSampleRate > maxSampleRate) {
5902 reqSampleRate = maxSampleRate;
5903 }
Eric Laurent81784c32012-11-19 14:55:58 -08005904 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005905 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005906 AudioMixer::RESAMPLE,
5907 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005908 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005909
Andy Hung8edb8dc2015-03-26 19:13:55 -07005910 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005911 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005912 AudioMixer::TIMESTRETCH,
5913 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07005914 // cast away constness for this generic API.
5915 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005916
Andy Hung69aed5f2014-02-25 17:24:40 -08005917 /*
5918 * Select the appropriate output buffer for the track.
5919 *
Andy Hung98ef9782014-03-04 14:46:50 -08005920 * Tracks with effects go into their own effects chain buffer
5921 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005922 *
5923 * Other tracks can use mMixerBuffer for higher precision
5924 * channel accumulation. If this buffer is enabled
5925 * (mMixerBufferEnabled true), then selected tracks will accumulate
5926 * into it.
5927 *
5928 */
5929 if (mMixerBufferEnabled
5930 && (track->mainBuffer() == mSinkBuffer
5931 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005932 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005933 mAudioMixer->setParameter(
5934 trackId,
5935 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005936 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005937 mAudioMixer->setParameter(
5938 trackId,
5939 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005940 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005941 } else {
5942 mAudioMixer->setParameter(
5943 trackId,
5944 AudioMixer::TRACK,
5945 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5946 mAudioMixer->setParameter(
5947 trackId,
5948 AudioMixer::TRACK,
5949 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5950 // TODO: override track->mainBuffer()?
5951 mMixerBufferValid = true;
5952 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005953 } else {
5954 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005955 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005956 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07005957 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005958 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005959 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005960 AudioMixer::TRACK,
5961 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5962 }
Eric Laurent81784c32012-11-19 14:55:58 -08005963 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005964 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005965 AudioMixer::TRACK,
5966 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005967 mAudioMixer->setParameter(
5968 trackId,
5969 AudioMixer::TRACK,
5970 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005971 mAudioMixer->setParameter(
5972 trackId,
5973 AudioMixer::TRACK,
5974 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung11e74242023-06-26 19:20:57 -07005975 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005976 mAudioMixer->setParameter(
5977 trackId,
5978 AudioMixer::TRACK,
Andy Hung11e74242023-06-26 19:20:57 -07005979 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08005980
5981 // reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07005982 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005983
5984 // If one track is ready, set the mixer ready if:
5985 // - the mixer was not ready during previous round OR
5986 // - no other track is not ready
5987 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5988 mixerStatus != MIXER_TRACKS_ENABLED) {
5989 mixerStatus = MIXER_TRACKS_READY;
5990 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005991
5992 // Enable the next few lines to instrument a test for underrun log handling.
5993 // TODO: Remove when we have a better way of testing the underrun log.
5994#if 0
5995 static int i;
5996 if ((++i & 0xf) == 0) {
5997 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5998 }
5999#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006000 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006001 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006002 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006003 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6004 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006005 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006006 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006007 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006008
Eric Laurent81784c32012-11-19 14:55:58 -08006009 // clear effect chain input buffer if an active track underruns to avoid sending
6010 // previous audio buffer again to effects
6011 chain = getEffectChain_l(track->sessionId());
6012 if (chain != 0) {
6013 chain->clearInputBuffer();
6014 }
6015
Andy Hungc0691382018-09-12 18:01:57 -07006016 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006017 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6018 track->isStopped() || track->isPaused()) {
6019 // We have consumed all the buffers of this track.
6020 // Remove it from the list of active tracks.
6021 // TODO: use actual buffer filling status instead of latency when available from
6022 // audio HAL
6023 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006024 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006025 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6026 if (track->isStopped()) {
6027 track->reset();
6028 }
6029 tracksToRemove->add(track);
6030 }
6031 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006032 // No buffers for this track. Give it a few chances to
6033 // fill a buffer, then remove it from active list.
Andy Hung11e74242023-06-26 19:20:57 -07006034 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07006035 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
6036 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006037 tracksToRemove->add(track);
6038 // indicate to client process that the track was disabled because of underrun;
6039 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006040 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006041 // If one track is not ready, mark the mixer also not ready if:
6042 // - the mixer was ready during previous round OR
6043 // - no other track is ready
6044 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6045 mixerStatus != MIXER_TRACKS_READY) {
6046 mixerStatus = MIXER_TRACKS_ENABLED;
6047 }
6048 }
Andy Hungc0691382018-09-12 18:01:57 -07006049 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006050 }
6051
6052 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006053
6054 }
6055
jiabin245cdd92018-12-07 17:55:15 -08006056 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6057 // When there is no fast track playing haptic and FastMixer exists,
6058 // enabling the first FastTrack, which provides mixed data from normal
6059 // tracks, to play haptic data.
6060 FastTrack *fastTrack = &state->mFastTracks[0];
6061 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6062 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6063 didModify = true;
6064 }
6065 }
6066
Eric Laurent81784c32012-11-19 14:55:58 -08006067 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006068 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006069 if (didModify) {
6070 state->mFastTracksGen++;
6071 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6072 if (kUseFastMixer == FastMixer_Dynamic &&
6073 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6074 state->mCommand = FastMixerState::COLD_IDLE;
6075 state->mColdFutexAddr = &mFastMixerFutex;
6076 state->mColdGen++;
6077 mFastMixerFutex = 0;
6078 if (kUseFastMixer == FastMixer_Dynamic) {
6079 mNormalSink = mOutputSink;
6080 }
6081 // If we go into cold idle, need to wait for acknowledgement
6082 // so that fast mixer stops doing I/O.
6083 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6084 pauseAudioWatchdog = true;
6085 }
Eric Laurent81784c32012-11-19 14:55:58 -08006086 }
6087 if (sq != NULL) {
6088 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006089 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6090 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6091 // when bringing the output sink into standby.)
6092 //
6093 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6094 //
6095 // This occurs with BT suspend when we idle the FastMixer with
6096 // active tracks, which may be added or removed.
6097 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006098 }
6099#ifdef AUDIO_WATCHDOG
6100 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6101 mAudioWatchdog->pause();
6102 }
6103#endif
6104
6105 // Now perform the deferred reset on fast tracks that have stopped
6106 while (resetMask != 0) {
6107 size_t i = __builtin_ctz(resetMask);
6108 ALOG_ASSERT(i < count);
6109 resetMask &= ~(1 << i);
Andy Hung11e74242023-06-26 19:20:57 -07006110 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006111 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6112 track->reset();
6113 }
6114
Andy Hung80d03d22018-04-10 10:32:11 -07006115 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6116 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6117 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6118 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6119 // See also the implementation of destroyTrack_l().
6120 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006121 const int trackId = track->id();
6122 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6123 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006124 }
6125 }
6126
Eric Laurent81784c32012-11-19 14:55:58 -08006127 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006128 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006129
Eric Laurentb3f315a2021-07-13 15:09:05 +02006130 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6131 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006132 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006133 }
6134
6135 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006136 // as long as there are effects we should clear the effects buffer, to avoid
6137 // passing a non-clean buffer to the effect chain
6138 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006139 if (mType == SPATIALIZER) {
6140 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6141 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006142 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006143 // sink or mix buffer must be cleared if all tracks are connected to an
6144 // effect chain as in this case the mixer will not write to the sink or mix buffer
6145 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006146 // always clear sink buffer for spatializer output as the output of the spatializer
6147 // effect will be accumulated into it
6148 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6149 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006150 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006151 if (mMixerBufferValid) {
6152 memset(mMixerBuffer, 0, mMixerBufferSize);
6153 // TODO: In testing, mSinkBuffer below need not be cleared because
6154 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6155 // after mixing.
6156 //
6157 // To enforce this guarantee:
6158 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6159 // (mixedTracks == 0 && fastTracks > 0))
6160 // must imply MIXER_TRACKS_READY.
6161 // Later, we may clear buffers regardless, and skip much of this logic.
6162 }
Andy Hung98ef9782014-03-04 14:46:50 -08006163 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006164 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006165 }
6166
6167 // if any fast tracks, then status is ready
6168 mMixerStatusIgnoringFastTracks = mixerStatus;
6169 if (fastTracks > 0) {
6170 mixerStatus = MIXER_TRACKS_READY;
6171 }
6172 return mixerStatus;
6173}
6174
Eric Laurentad7dd962016-09-22 12:38:37 -07006175// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07006176uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006177{
6178 uint32_t trackCount = 0;
6179 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006180 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006181 trackCount++;
6182 }
6183 }
6184 return trackCount;
6185}
6186
Andy Hung4b17e882023-07-07 13:47:37 -07006187bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006188{
Brian Lindahl65e90012022-07-27 18:01:07 +02006189 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6190 // could falsely detect that the frame position has stalled due to underrun because we haven't
6191 // given the Audio HAL enough time to update.
6192 const nsecs_t nowNs = systemTime();
6193 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6194 return mLatchedValue;
6195 }
6196 mPreviousNs = nowNs;
6197 mLatchedValue = false;
6198 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006199 uint64_t position = 0;
6200 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006201 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006202 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006203 if (position != mPreviousPosition) {
6204 mPreviousPosition = position;
6205 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006206 }
6207 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006208 return mLatchedValue;
6209}
6210
Andy Hung4b17e882023-07-07 13:47:37 -07006211void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006212{
6213 mLatchedValue = true;
6214 mPreviousPosition = 0;
6215 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006216}
6217
Andy Hung1bc088a2018-02-09 15:57:31 -08006218// isTrackAllowed_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07006219bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006220 audio_channel_mask_t channelMask, audio_format_t format,
6221 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006222{
Andy Hung1bc088a2018-02-09 15:57:31 -08006223 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6224 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006225 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006226 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006227 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006228 ALOGW("%s: invalid format: %#x", __func__, format);
6229 return false;
6230 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006231 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006232 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6233 return false;
6234 }
6235 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006236}
6237
Eric Laurent10351942014-05-08 18:49:52 -07006238// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07006239bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006240 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006241{
Eric Laurent81784c32012-11-19 14:55:58 -08006242 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006243 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006244
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006245 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006246
Eric Laurent10351942014-05-08 18:49:52 -07006247 AudioParameter param = AudioParameter(keyValuePair);
6248 int value;
6249 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6250 reconfig = true;
6251 }
6252 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hungd21a2ab2023-07-20 21:44:14 -07006253 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006254 status = BAD_VALUE;
6255 } else {
6256 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006257 reconfig = true;
6258 }
Eric Laurent10351942014-05-08 18:49:52 -07006259 }
6260 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hungd21a2ab2023-07-20 21:44:14 -07006261 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006262 status = BAD_VALUE;
6263 } else {
6264 // no need to save value, since it's constant
6265 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006266 }
Eric Laurent10351942014-05-08 18:49:52 -07006267 }
6268 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6269 // do not accept frame count changes if tracks are open as the track buffer
6270 // size depends on frame count and correct behavior would not be guaranteed
6271 // if frame count is changed after track creation
6272 if (!mTracks.isEmpty()) {
6273 status = INVALID_OPERATION;
6274 } else {
6275 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006276 }
Eric Laurent10351942014-05-08 18:49:52 -07006277 }
6278 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006279 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006280 }
Eric Laurent81784c32012-11-19 14:55:58 -08006281
Eric Laurent10351942014-05-08 18:49:52 -07006282 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006283 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006284 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006285 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6286 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006287 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006288 mThreadMetrics.logEndInterval();
6289 mThreadSnapshot.onEnd();
6290 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006291 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006292 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006293 }
Eric Laurent10351942014-05-08 18:49:52 -07006294 if (status == NO_ERROR && reconfig) {
6295 readOutputParameters_l();
6296 delete mAudioMixer;
6297 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006298 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006299 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006300 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006301 trackId,
Andy Hung11e74242023-06-26 19:20:57 -07006302 track->channelMask(),
6303 track->format(),
6304 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006305 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006306 "%s(): AudioMixer cannot create track(%d)"
6307 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006308 __func__,
Andy Hung11e74242023-06-26 19:20:57 -07006309 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006310 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006311 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006312 }
Eric Laurent81784c32012-11-19 14:55:58 -08006313 }
6314
Dean Wheatley68918102021-03-19 22:09:19 +11006315 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006316}
6317
6318
Andy Hung4b17e882023-07-07 13:47:37 -07006319void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006320{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006321 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006322 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006323 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006324 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006325 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6326 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6327 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006328 if (hasFastMixer()) {
6329 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6330
6331 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6332 // while we are dumping it. It may be inconsistent, but it won't mutate!
6333 // This is a large object so we place it on the heap.
6334 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006335 const std::unique_ptr<FastMixerDumpState> copy =
6336 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006337 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006338
6339#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006340 // Similar for state queue
6341 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6342 observerCopy.dump(fd);
6343 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6344 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006345#endif
6346
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006347#ifdef AUDIO_WATCHDOG
6348 if (mAudioWatchdog != 0) {
6349 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6350 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6351 wdCopy.dump(fd);
6352 }
6353#endif
6354
6355 } else {
6356 dprintf(fd, " No FastMixer\n");
6357 }
Eric Laurent90cea102023-05-15 15:08:27 +02006358
6359 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6360 mBluetoothLatencyModesEnabled ? "" : "not ");
6361 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6362 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6363 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006364}
6365
Andy Hung4b17e882023-07-07 13:47:37 -07006366uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006367{
6368 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6369}
6370
Andy Hung4b17e882023-07-07 13:47:37 -07006371uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006372{
6373 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6374}
6375
Andy Hung4b17e882023-07-07 13:47:37 -07006376void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006377{
6378 PlaybackThread::cacheParameters_l();
6379
6380 // FIXME: Relaxed timing because of a certain device that can't meet latency
6381 // Should be reduced to 2x after the vendor fixes the driver issue
6382 // increase threshold again due to low power audio mode. The way this warning
6383 // threshold is calculated and its usefulness should be reconsidered anyway.
6384 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6385}
6386
Andy Hung4b17e882023-07-07 13:47:37 -07006387void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung7535ed92023-07-17 17:05:00 -07006388 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006389}
6390
Andy Hung4b17e882023-07-07 13:47:37 -07006391void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006392 // Only handle latency mode if:
6393 // - mBluetoothLatencyModesEnabled is true
6394 // - the HAL supports latency modes
6395 // - the selected device is Bluetooth LE or A2DP
6396 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6397 return;
6398 }
6399 if (mOutDeviceTypeAddrs.size() != 1
6400 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6401 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6402 return;
6403 }
6404
6405 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6406 if (mSupportedLatencyModes.size() == 1) {
6407 // If the HAL only support one latency mode currently, confirm the choice
6408 latencyMode = mSupportedLatencyModes[0];
6409 } else if (mSupportedLatencyModes.size() > 1) {
6410 // Request low latency if:
6411 // - At least one active track is either:
6412 // - a fast track with gaming usage or
6413 // - a track with acessibility usage
6414 for (const auto& track : mActiveTracks) {
6415 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6416 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6417 latencyMode = AUDIO_LATENCY_MODE_LOW;
6418 break;
6419 }
6420 }
6421 }
6422
6423 if (latencyMode != mSetLatencyMode) {
6424 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6425 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6426 __func__, mId, toString(latencyMode).c_str(), status);
6427 if (status == NO_ERROR) {
6428 mSetLatencyMode = latencyMode;
6429 }
6430 }
6431}
6432
Andy Hung4b17e882023-07-07 13:47:37 -07006433void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006434
6435 if (mOutput == nullptr || mOutput->stream == nullptr) {
6436 return;
6437 }
6438 std::vector<audio_latency_mode_t> latencyModes;
6439 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6440 if (status != NO_ERROR) {
6441 latencyModes.clear();
6442 }
6443 if (latencyModes != mSupportedLatencyModes) {
6444 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6445 __func__, mId, status, toString(latencyModes).c_str());
6446 mSupportedLatencyModes.swap(latencyModes);
6447 sendHalLatencyModesChangedEvent_l();
6448 }
6449}
6450
Andy Hung4b17e882023-07-07 13:47:37 -07006451status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006452 std::vector<audio_latency_mode_t>* modes) {
6453 if (modes == nullptr) {
6454 return BAD_VALUE;
6455 }
6456 Mutex::Autolock _l(mLock);
6457 *modes = mSupportedLatencyModes;
6458 return NO_ERROR;
6459}
6460
Andy Hung4b17e882023-07-07 13:47:37 -07006461void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006462 std::vector<audio_latency_mode_t> modes) {
6463 Mutex::Autolock _l(mLock);
6464 if (modes != mSupportedLatencyModes) {
6465 ALOGD("%s: thread(%d) supported latency modes: %s",
6466 __func__, mId, toString(modes).c_str());
6467 mSupportedLatencyModes.swap(modes);
6468 sendHalLatencyModesChangedEvent_l();
6469 }
6470}
6471
Andy Hung4b17e882023-07-07 13:47:37 -07006472status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006473 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6474 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6475 return INVALID_OPERATION;
6476 }
6477 mBluetoothLatencyModesEnabled.store(enabled);
6478 return NO_ERROR;
6479}
6480
Eric Laurent81784c32012-11-19 14:55:58 -08006481// ----------------------------------------------------------------------------
6482
Andy Hung4b17e882023-07-07 13:47:37 -07006483/* static */
6484sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung7535ed92023-07-17 17:05:00 -07006485 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07006486 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6487 const audio_offload_info_t& offloadInfo) {
6488 return sp<DirectOutputThread>::make(
Andy Hung7535ed92023-07-17 17:05:00 -07006489 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung4b17e882023-07-07 13:47:37 -07006490}
6491
Andy Hung7535ed92023-07-17 17:05:00 -07006492DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006493 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6494 const audio_offload_info_t& offloadInfo)
Andy Hung7535ed92023-07-17 17:05:00 -07006495 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006496 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006497{
Andy Hung7535ed92023-07-17 17:05:00 -07006498 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006499}
6500
Andy Hung4b17e882023-07-07 13:47:37 -07006501DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006502{
6503}
6504
Andy Hung4b17e882023-07-07 13:47:37 -07006505void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006506{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006507 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006508 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6509 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6510}
6511
Andy Hung4b17e882023-07-07 13:47:37 -07006512void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006513{
6514 Mutex::Autolock _l(mLock);
6515 if (mMasterBalance != balance) {
6516 mMasterBalance.store(balance);
6517 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6518 broadcast_l();
6519 }
6520}
6521
Andy Hung4b17e882023-07-07 13:47:37 -07006522void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006523{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006524 float left, right;
6525
Andy Hung333ab962019-05-28 20:23:35 -07006526 // Ensure volumeshaper state always advances even when muted.
Andy Hung11e74242023-06-26 19:20:57 -07006527 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006528
6529 const size_t framesReleased = proxy->framesReleased();
6530 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6531 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6532
6533 ALOGV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6534 __func__, framesReleased, (long long)frames, (long long)time);
6535
6536 const int64_t volumeShaperFrames =
6537 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6538 const auto [shaperVolume, shaperActive] =
6539 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006540 mVolumeShaperActive = shaperActive;
6541
Vlad Popae2f5aef2022-07-25 16:00:20 +02006542 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6543 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6544 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6545
6546 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6547
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006548 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006549 left = right = 0;
6550 } else {
6551 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006552 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006553
Glenn Kastenc56f3422014-03-21 17:53:17 -07006554 if (left > GAIN_FLOAT_UNITY) {
6555 left = GAIN_FLOAT_UNITY;
6556 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006557 if (right > GAIN_FLOAT_UNITY) {
6558 right = GAIN_FLOAT_UNITY;
6559 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006560 left *= v;
6561 right *= v;
Andy Hung7535ed92023-07-17 17:05:00 -07006562 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006563 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6564 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6565 right *= mMasterBalanceRight;
6566 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006567 }
6568
Andy Hung7535ed92023-07-17 17:05:00 -07006569 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006570 /*muteState=*/{mMasterMute,
6571 mStreamTypes[track->streamType()].volume == 0.f,
6572 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006573 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006574 clientVolumeMute,
6575 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006576
Eric Laurentbfb1b832013-01-07 09:53:42 -08006577 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006578 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006579 if (left != mLeftVolFloat || right != mRightVolFloat) {
6580 mLeftVolFloat = left;
6581 mRightVolFloat = right;
6582
Eric Laurentbfb1b832013-01-07 09:53:42 -08006583 // Delegate volume control to effect in track effect chain if needed
6584 // only one effect chain can be present on DirectOutputThread, so if
6585 // there is one, the track is connected to it
6586 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006587 // if effect chain exists, volume is handled by it.
6588 // Convert volumes from float to 8.24
6589 uint32_t vl = (uint32_t)(left * (1 << 24));
6590 uint32_t vr = (uint32_t)(right * (1 << 24));
6591 // Direct/Offload effect chains set output volume in setVolume_l().
6592 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6593 } else {
6594 // otherwise we directly set the volume.
6595 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006596 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006597 }
6598 }
6599}
6600
Andy Hung4b17e882023-07-07 13:47:37 -07006601void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006602{
Andy Hung11e74242023-06-26 19:20:57 -07006603 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6604 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006605
Eric Laurent0f0631e2015-07-06 18:01:25 -07006606 if (previousTrack != 0 && latestTrack != 0) {
6607 if (mType == DIRECT) {
6608 if (previousTrack.get() != latestTrack.get()) {
6609 mFlushPending = true;
6610 }
6611 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006612 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6613 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006614 mFlushPending = true;
6615 }
6616 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006617 } else if (previousTrack == 0) {
6618 // there could be an old track added back during track transition for direct
6619 // output, so always issues flush to flush data of the previous track if it
6620 // was already destroyed with HAL paused, then flush can resume the playback
6621 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006622 }
6623 PlaybackThread::onAddNewTrack_l();
6624}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006625
Andy Hung4b17e882023-07-07 13:47:37 -07006626PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07006627 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006628)
6629{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006630 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006631 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006632 bool doHwPause = false;
6633 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006634
6635 // find out which tracks need to be processed
Andy Hung11e74242023-06-26 19:20:57 -07006636 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006637 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006638 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006639 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006640 continue;
6641 }
6642
Andy Hung11e74242023-06-26 19:20:57 -07006643 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006644#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006645 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006646#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006647 // Only consider last track started for volume and mixer state control.
6648 // In theory an older track could underrun and restart after the new one starts
6649 // but as we only care about the transition phase between two tracks on a
6650 // direct output, it is not a problem to ignore the underrun case.
Andy Hung11e74242023-06-26 19:20:57 -07006651 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006652 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006653
Kuowei Li23666472021-01-20 10:23:25 +08006654 if (track->isPausePending()) {
6655 track->pauseAck();
6656 // It is possible a track might have been flushed or stopped.
6657 // Other operations such as flush pending might occur on the next prepare.
6658 if (track->isPausing()) {
6659 track->setPaused();
6660 }
6661 // Always perform pause, as an immediate flush will change
6662 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006663 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006664 doHwPause = true;
6665 mHwPaused = true;
6666 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006667 } else if (track->isFlushPending()) {
6668 track->flushAck();
6669 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006670 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006671 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006672 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006673 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006674 if (last) {
6675 mLeftVolFloat = mRightVolFloat = -1.0;
6676 if (mHwPaused) {
6677 doHwResume = true;
6678 mHwPaused = false;
6679 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006680 }
6681 }
6682
Eric Laurent81784c32012-11-19 14:55:58 -08006683 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006684 // for all its buffers to be filled before processing it.
6685 // Allow draining the buffer in case the client
6686 // app does not call stop() and relies on underrun to stop:
Andy Hung11e74242023-06-26 19:20:57 -07006687 // hence the test on (track->retryCount() > 1).
6688 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006689 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6690 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006691 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006692
6693 // target retry count that we will use is based on the time we wait for retries.
6694 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6695 // the retry threshold is when we accept any size for PCM data. This is slightly
6696 // smaller than the retry count so we can push small bits of data without a glitch.
6697 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006698 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006699 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung11e74242023-06-26 19:20:57 -07006700 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006701 minFrames = mNormalFrameCount;
6702 } else {
6703 minFrames = 1;
6704 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006705
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006706 const size_t framesReady = track->framesReady();
6707 const int trackId = track->id();
6708 if (ATRACE_ENABLED()) {
6709 std::string traceName("nRdy");
6710 traceName += std::to_string(trackId);
6711 ATRACE_INT(traceName.c_str(), framesReady);
6712 }
6713 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006714 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006715 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006716 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006717
Andy Hung11e74242023-06-26 19:20:57 -07006718 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6719 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006720 if (last) {
6721 // make sure processVolume_l() will apply new volume even if 0
6722 mLeftVolFloat = mRightVolFloat = -1.0;
6723 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006724 if (!mHwSupportsPause) {
6725 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006726 }
6727 }
6728
6729 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006730 processVolume_l(track, last);
6731 if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07006732 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006733 if (previousTrack != 0) {
6734 if (track != previousTrack.get()) {
6735 // Flush any data still being written from last track
6736 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006737 // Invalidate previous track to force a seek when resuming.
6738 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006739 }
6740 }
6741 mPreviousTrack = track;
6742
Eric Laurentd595b7c2013-04-03 17:27:56 -07006743 // reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07006744 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006745 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006746 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006747 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006748 doHwResume = true;
6749 mHwPaused = false;
6750 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006751 }
Eric Laurent81784c32012-11-19 14:55:58 -08006752 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006753 // clear effect chain input buffer if the last active track started underruns
6754 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006755 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006756 mEffectChains[0]->clearInputBuffer();
6757 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006758 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07006759 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006760 if (last && mHwPaused) {
6761 doHwResume = true;
6762 mHwPaused = false;
6763 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006764 }
6765 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6766 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006767 // We have consumed all the buffers of this track.
6768 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006769 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006770 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006771 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006772 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006773 if (presComplete) {
6774 mOutput->presentationComplete();
6775 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006776 if (track->isStopping_2()) {
Andy Hung11e74242023-06-26 19:20:57 -07006777 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006778 }
Eric Laurent81784c32012-11-19 14:55:58 -08006779 if (track->isStopped()) {
6780 track->reset();
6781 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006782 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006783 }
6784 } else {
6785 // No buffers for this track. Give it a few chances to
6786 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006787 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006788 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006789 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung11e74242023-06-26 19:20:57 -07006790 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006791 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung11e74242023-06-26 19:20:57 -07006792 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006793 } else {
6794 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6795 tracksToRemove->add(track);
6796 // indicate to client process that the track was disabled because of
6797 // underrun; it will then automatically call start() when data is available
6798 track->disable();
6799 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6800 // unlike mixerthread, HAL can be paused for direct output
6801 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6802 "minFrames = %u, mFormat = %#x",
6803 framesReady, minFrames, mFormat);
6804 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6805 doHwPause = true;
6806 mHwPaused = true;
6807 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006808 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006809 } else if (last) {
6810 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006811 }
6812 }
6813 }
6814 }
6815
Eric Laurentd1f69b02014-12-15 14:33:13 -08006816 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006817 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006818 for (size_t i = 0; i < mTracks.size(); i++) {
6819 if (mTracks[i]->isFlushPending()) {
6820 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006821 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006822 }
6823 }
6824 }
6825
6826 // make sure the pause/flush/resume sequence is executed in the right order.
6827 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6828 // before flush and then resume HW. This can happen in case of pause/flush/resume
6829 // if resume is received before pause is executed.
6830 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006831 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006832 status_t result = mOutput->stream->pause();
6833 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006834 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006835 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006836 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006837 flushHw_l();
6838 }
6839 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006840 status_t result = mOutput->stream->resume();
6841 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006842 }
Eric Laurent81784c32012-11-19 14:55:58 -08006843 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006844 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006845
6846 return mixerStatus;
6847}
6848
Andy Hung4b17e882023-07-07 13:47:37 -07006849void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006850{
Eric Laurent81784c32012-11-19 14:55:58 -08006851 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006852 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006853 // output audio to hardware
6854 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006855 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006856 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006857 status_t status = mActiveTrack->getNextBuffer(&buffer);
6858 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006859 // no need to pad with 0 for compressed audio
6860 if (audio_has_proportional_frames(mFormat)) {
6861 memset(curBuf, 0, frameCount * mFrameSize);
6862 }
Eric Laurent81784c32012-11-19 14:55:58 -08006863 break;
6864 }
6865 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6866 frameCount -= buffer.frameCount;
6867 curBuf += buffer.frameCount * mFrameSize;
6868 mActiveTrack->releaseBuffer(&buffer);
6869 }
Andy Hung2098f272014-02-27 14:00:06 -08006870 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006871 mSleepTimeUs = 0;
6872 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006873 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006874}
6875
Andy Hung4b17e882023-07-07 13:47:37 -07006876void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006877{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006878 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006879 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006880 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006881 return;
6882 }
Andy Hung85ba3332021-04-27 17:40:26 -07006883 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6884 mSleepTimeUs = mActiveSleepTimeUs;
6885 } else {
6886 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006887 }
Andy Hung85ba3332021-04-27 17:40:26 -07006888 // Note: In S or later, we do not write zeroes for
6889 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006890}
6891
Andy Hung4b17e882023-07-07 13:47:37 -07006892void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006893{
6894 {
6895 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006896 for (size_t i = 0; i < mTracks.size(); i++) {
6897 if (mTracks[i]->isFlushPending()) {
6898 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006899 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006900 }
6901 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006902 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006903 flushHw_l();
6904 }
6905 }
6906 PlaybackThread::threadLoop_exit();
6907}
6908
6909// must be called with thread mutex locked
Andy Hung4b17e882023-07-07 13:47:37 -07006910bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006911{
6912 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006913 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006914
6915 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6916 // after a timeout and we will enter standby then.
6917 if (mTracks.size() > 0) {
6918 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006919 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung11e74242023-06-26 19:20:57 -07006920 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006921 }
6922
Eric Laurent5cff4032015-05-26 13:49:58 -07006923 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006924}
6925
Eric Laurent10351942014-05-08 18:49:52 -07006926// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07006927bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006928 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006929{
6930 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006931 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006932
Eric Laurent10351942014-05-08 18:49:52 -07006933 AudioParameter param = AudioParameter(keyValuePair);
6934 int value;
6935 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006936 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006937 }
Eric Laurent10351942014-05-08 18:49:52 -07006938 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6939 // do not accept frame count changes if tracks are open as the track buffer
6940 // size depends on frame count and correct behavior would not be garantied
6941 // if frame count is changed after track creation
6942 if (!mTracks.isEmpty()) {
6943 status = INVALID_OPERATION;
6944 } else {
6945 reconfig = true;
6946 }
6947 }
6948 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006949 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006950 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006951 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006952 if (!mStandby) {
6953 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006954 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02006955 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07006956 }
Eric Laurent10351942014-05-08 18:49:52 -07006957 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006958 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006959 }
6960 if (status == NO_ERROR && reconfig) {
6961 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006962 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006963 }
6964 }
6965
Dean Wheatley68918102021-03-19 22:09:19 +11006966 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006967}
6968
Andy Hung4b17e882023-07-07 13:47:37 -07006969uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006970{
6971 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006972 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006973 time = PlaybackThread::activeSleepTimeUs();
6974 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006975 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006976 }
6977 return time;
6978}
6979
Andy Hung4b17e882023-07-07 13:47:37 -07006980uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006981{
6982 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006983 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006984 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6985 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006986 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006987 }
6988 return time;
6989}
6990
Andy Hung4b17e882023-07-07 13:47:37 -07006991uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006992{
6993 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006994 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006995 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6996 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006997 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006998 }
6999 return time;
7000}
7001
Andy Hung4b17e882023-07-07 13:47:37 -07007002void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007003{
7004 PlaybackThread::cacheParameters_l();
7005
7006 // use shorter standby delay as on normal output to release
7007 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007008 // no delay on outputs with HW A/V sync
7009 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007010 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007011 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007012 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007013 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007014 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007015 }
Eric Laurent81784c32012-11-19 14:55:58 -08007016}
7017
Andy Hung4b17e882023-07-07 13:47:37 -07007018void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007019{
ziyangch8f194f12021-12-01 13:48:04 -08007020 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007021 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007022 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007023 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007024 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007025 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007026 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007027}
7028
Andy Hung4b17e882023-07-07 13:47:37 -07007029int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007030 // If a VolumeShaper is active, we must wake up periodically to update volume.
7031 const int64_t NS_PER_MS = 1000000;
7032 return mVolumeShaperActive ?
7033 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7034}
7035
Eric Laurent81784c32012-11-19 14:55:58 -08007036// ----------------------------------------------------------------------------
7037
Andy Hung4b17e882023-07-07 13:47:37 -07007038AsyncCallbackThread::AsyncCallbackThread(
7039 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007040 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007041 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007042 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007043 mDrainSequence(0),
7044 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007045{
7046}
7047
Andy Hung4b17e882023-07-07 13:47:37 -07007048void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007049{
7050 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7051}
7052
Andy Hung4b17e882023-07-07 13:47:37 -07007053bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007054{
7055 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007056 uint32_t writeAckSequence;
7057 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007058 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007059
7060 {
7061 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007062 while (!((mWriteAckSequence & 1) ||
7063 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007064 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007065 exitPending())) {
7066 mWaitWorkCV.wait(mLock);
7067 }
7068
Eric Laurentbfb1b832013-01-07 09:53:42 -08007069 if (exitPending()) {
7070 break;
7071 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007072 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7073 mWriteAckSequence, mDrainSequence);
7074 writeAckSequence = mWriteAckSequence;
7075 mWriteAckSequence &= ~1;
7076 drainSequence = mDrainSequence;
7077 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007078 asyncError = mAsyncError;
7079 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007080 }
7081 {
Andy Hung4b17e882023-07-07 13:47:37 -07007082 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007083 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007084 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007085 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007086 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007087 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007088 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007089 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007090 if (asyncError) {
7091 playbackThread->onAsyncError();
7092 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007093 }
7094 }
7095 }
7096 return false;
7097}
7098
Andy Hung4b17e882023-07-07 13:47:37 -07007099void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007100{
7101 ALOGV("AsyncCallbackThread::exit");
7102 Mutex::Autolock _l(mLock);
7103 requestExit();
7104 mWaitWorkCV.broadcast();
7105}
7106
Andy Hung4b17e882023-07-07 13:47:37 -07007107void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007108{
7109 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007110 // bit 0 is cleared
7111 mWriteAckSequence = sequence << 1;
7112}
7113
Andy Hung4b17e882023-07-07 13:47:37 -07007114void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007115{
7116 Mutex::Autolock _l(mLock);
7117 // ignore unexpected callbacks
7118 if (mWriteAckSequence & 2) {
7119 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007120 mWaitWorkCV.signal();
7121 }
7122}
7123
Andy Hung4b17e882023-07-07 13:47:37 -07007124void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007125{
7126 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007127 // bit 0 is cleared
7128 mDrainSequence = sequence << 1;
7129}
7130
Andy Hung4b17e882023-07-07 13:47:37 -07007131void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007132{
7133 Mutex::Autolock _l(mLock);
7134 // ignore unexpected callbacks
7135 if (mDrainSequence & 2) {
7136 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007137 mWaitWorkCV.signal();
7138 }
7139}
7140
Andy Hung4b17e882023-07-07 13:47:37 -07007141void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007142{
7143 Mutex::Autolock _l(mLock);
7144 mAsyncError = true;
7145 mWaitWorkCV.signal();
7146}
7147
Eric Laurentbfb1b832013-01-07 09:53:42 -08007148
7149// ----------------------------------------------------------------------------
Andy Hung4b17e882023-07-07 13:47:37 -07007150
7151/* static */
7152sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung7535ed92023-07-17 17:05:00 -07007153 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007154 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7155 const audio_offload_info_t& offloadInfo) {
Andy Hung7535ed92023-07-17 17:05:00 -07007156 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung4b17e882023-07-07 13:47:37 -07007157}
7158
Andy Hung7535ed92023-07-17 17:05:00 -07007159OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007160 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7161 const audio_offload_info_t& offloadInfo)
Andy Hung7535ed92023-07-17 17:05:00 -07007162 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007163 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007164{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007165 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007166 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007167 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007168}
7169
Andy Hung4b17e882023-07-07 13:47:37 -07007170void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007171{
7172 if (mFlushPending || mHwPaused) {
7173 // If a flush is pending or track was paused, just discard buffered data
7174 flushHw_l();
7175 } else {
7176 mMixerStatus = MIXER_DRAIN_ALL;
7177 threadLoop_drain();
7178 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007179 if (mUseAsyncWrite) {
7180 ALOG_ASSERT(mCallbackThread != 0);
7181 mCallbackThread->exit();
7182 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007183 PlaybackThread::threadLoop_exit();
7184}
7185
Andy Hung4b17e882023-07-07 13:47:37 -07007186PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07007187 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007188)
7189{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007190 size_t count = mActiveTracks.size();
7191
7192 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007193 bool doHwPause = false;
7194 bool doHwResume = false;
7195
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007196 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007197
Eric Laurentbfb1b832013-01-07 09:53:42 -08007198 // find out which tracks need to be processed
Andy Hung11e74242023-06-26 19:20:57 -07007199 for (const sp<IAfTrack>& t : mActiveTracks) {
7200 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007201#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007202 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007203#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007204 // Only consider last track started for volume and mixer state control.
7205 // In theory an older track could underrun and restart after the new one starts
7206 // but as we only care about the transition phase between two tracks on a
7207 // direct output, it is not a problem to ignore the underrun case.
Andy Hung11e74242023-06-26 19:20:57 -07007208 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007209 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007210
Haynes Mathew George7844f672014-01-15 12:32:55 -08007211 if (track->isInvalid()) {
7212 ALOGW("An invalidated track shouldn't be in active list");
7213 tracksToRemove->add(track);
7214 continue;
7215 }
7216
Andy Hung11e74242023-06-26 19:20:57 -07007217 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007218 ALOGW("An idle track shouldn't be in active list");
7219 continue;
7220 }
7221
Kuowei Li23666472021-01-20 10:23:25 +08007222 if (track->isPausePending()) {
7223 track->pauseAck();
7224 // It is possible a track might have been flushed or stopped.
7225 // Other operations such as flush pending might occur on the next prepare.
7226 if (track->isPausing()) {
7227 track->setPaused();
7228 }
7229 // Always perform pause if last, as an immediate flush will change
7230 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007231 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007232 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007233 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007234 mHwPaused = true;
7235 }
7236 // If we were part way through writing the mixbuffer to
7237 // the HAL we must save this until we resume
7238 // BUG - this will be wrong if a different track is made active,
7239 // in that case we want to discard the pending data in the
7240 // mixbuffer and tell the client to present it again when the
7241 // track is resumed
7242 mPausedWriteLength = mCurrentWriteLength;
7243 mPausedBytesRemaining = mBytesRemaining;
7244 mBytesRemaining = 0; // stop writing
7245 }
7246 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007247 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007248 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007249 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007250 } else {
Andy Hung11e74242023-06-26 19:20:57 -07007251 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007252 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007253 track->flushAck();
7254 if (last) {
7255 mFlushPending = true;
7256 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007257 } else if (track->isResumePending()){
7258 track->resumeAck();
7259 if (last) {
7260 if (mPausedBytesRemaining) {
7261 // Need to continue write that was interrupted
7262 mCurrentWriteLength = mPausedWriteLength;
7263 mBytesRemaining = mPausedBytesRemaining;
7264 mPausedBytesRemaining = 0;
7265 }
7266 if (mHwPaused) {
7267 doHwResume = true;
7268 mHwPaused = false;
7269 // threadLoop_mix() will handle the case that we need to
7270 // resume an interrupted write
7271 }
7272 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007273 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007274
Eric Laurent3df841a2016-07-15 15:15:40 -07007275 mLeftVolFloat = mRightVolFloat = -1.0;
7276
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007277 // Do not handle new data in this iteration even if track->framesReady()
7278 mixerStatus = MIXER_TRACKS_ENABLED;
7279 }
7280 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007281 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007282 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung11e74242023-06-26 19:20:57 -07007283 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7284 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007285 if (last) {
7286 // make sure processVolume_l() will apply new volume even if 0
7287 mLeftVolFloat = mRightVolFloat = -1.0;
7288 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007289 }
7290
7291 if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07007292 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007293 if (previousTrack != 0) {
7294 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007295 // Flush any data still being written from last track
7296 mBytesRemaining = 0;
7297 if (mPausedBytesRemaining) {
7298 // Last track was paused so we also need to flush saved
7299 // mixbuffer state and invalidate track so that it will
7300 // re-submit that unwritten data when it is next resumed
7301 mPausedBytesRemaining = 0;
7302 // Invalidate is a bit drastic - would be more efficient
7303 // to have a flag to tell client that some of the
7304 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007305 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007306 }
7307 // flush data already sent to the DSP if changing audio session as audio
7308 // comes from a different source. Also invalidate previous track to force a
7309 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007310 if (previousTrack->sessionId() != track->sessionId()) {
7311 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007312 }
7313 }
7314 }
7315 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007316 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007317 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007318 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007319 } else {
Andy Hung11e74242023-06-26 19:20:57 -07007320 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007321 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007322 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007323 mixerStatus = MIXER_TRACKS_READY;
7324 }
7325 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007326 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007327 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007328 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007329 // Hardware buffer can hold a large amount of audio so we must
7330 // wait for all current track's data to drain before we say
7331 // that the track is stopped.
7332 if (mBytesRemaining == 0) {
7333 // Only start draining when all data in mixbuffer
7334 // has been written
7335 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung11e74242023-06-26 19:20:57 -07007336 track->setState(IAfTrackBase::STOPPING_2);
7337 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007338 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7339 if (last && !mStandby) {
7340 // do not modify drain sequence if we are already draining. This happens
7341 // when resuming from pause after drain.
7342 if ((mDrainSequence & 1) == 0) {
7343 mSleepTimeUs = 0;
7344 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7345 mixerStatus = MIXER_DRAIN_TRACK;
7346 mDrainSequence += 2;
7347 }
7348 if (mHwPaused) {
7349 // It is possible to move from PAUSED to STOPPING_1 without
7350 // a resume so we must ensure hardware is running
7351 doHwResume = true;
7352 mHwPaused = false;
7353 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007354 }
7355 }
Eric Laurente93cc032016-05-05 10:15:10 -07007356 } else if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07007357 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007358 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007359 }
7360 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007361 // Drain has completed or we are in standby, signal presentation complete
7362 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung11e74242023-06-26 19:20:57 -07007363 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007364 mOutput->presentationComplete();
7365 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007366 track->reset();
7367 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007368 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007369 if (!mUseAsyncWrite) {
7370 // If we don't get explicit drain notification we must
7371 // register discontinuity regardless of whether this is
7372 // the previous (!last) or the upcoming (last) track
7373 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007374 mTimestampVerifier.discontinuity(
7375 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007376 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007377 }
7378 } else {
7379 // No buffers for this track. Give it a few chances to
7380 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007381 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007382 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung11e74242023-06-26 19:20:57 -07007383 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007384 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung11e74242023-06-26 19:20:57 -07007385 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007386 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007387 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7388 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007389 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007390 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007391 // it will then automatically call start() when data is available
7392 track->disable();
7393 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007394 } else if (last){
7395 mixerStatus = MIXER_TRACKS_ENABLED;
7396 }
7397 }
7398 }
7399 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007400 if (track->isReady()) { // check ready to prevent premature start.
7401 processVolume_l(track, last);
7402 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007403 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007404
Eric Laurentea0fade2013-10-04 16:23:48 -07007405 // make sure the pause/flush/resume sequence is executed in the right order.
7406 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7407 // before flush and then resume HW. This can happen in case of pause/flush/resume
7408 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007409 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007410 status_t result = mOutput->stream->pause();
7411 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007412 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007413 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007414 if (mFlushPending) {
7415 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007416 }
Eric Laurentfd477972013-10-25 18:10:40 -07007417 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007418 status_t result = mOutput->stream->resume();
7419 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007420 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007421
Eric Laurentbfb1b832013-01-07 09:53:42 -08007422 // remove all the tracks that need to be...
7423 removeTracks_l(*tracksToRemove);
7424
7425 return mixerStatus;
7426}
7427
Eric Laurentbfb1b832013-01-07 09:53:42 -08007428// must be called with thread mutex locked
Andy Hung4b17e882023-07-07 13:47:37 -07007429bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007430{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007431 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7432 mWriteAckSequence, mDrainSequence);
7433 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007434 return true;
7435 }
7436 return false;
7437}
7438
Andy Hung4b17e882023-07-07 13:47:37 -07007439bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007440{
7441 Mutex::Autolock _l(mLock);
7442 return waitingAsyncCallback_l();
7443}
7444
Andy Hung4b17e882023-07-07 13:47:37 -07007445void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007446{
Eric Laurente659ef42014-09-29 13:06:46 -07007447 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007448 // Flush anything still waiting in the mixbuffer
7449 mCurrentWriteLength = 0;
7450 mBytesRemaining = 0;
7451 mPausedWriteLength = 0;
7452 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007453 // reset bytes written count to reflect that DSP buffers are empty after flush.
7454 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007455
Eric Laurentbfb1b832013-01-07 09:53:42 -08007456 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007457 // discard any pending drain or write ack by incrementing sequence
7458 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7459 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007460 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007461 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7462 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007463 }
7464}
7465
Andy Hung4b17e882023-07-07 13:47:37 -07007466void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007467{
7468 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007469 if (PlaybackThread::invalidateTracks_l(streamType)) {
7470 mFlushPending = true;
7471 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007472}
7473
Andy Hung4b17e882023-07-07 13:47:37 -07007474void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08007475 Mutex::Autolock _l(mLock);
7476 if (PlaybackThread::invalidateTracks_l(portIds)) {
7477 mFlushPending = true;
7478 }
7479}
7480
Eric Laurentbfb1b832013-01-07 09:53:42 -08007481// ----------------------------------------------------------------------------
7482
Andy Hung4b17e882023-07-07 13:47:37 -07007483/* static */
7484sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -07007485 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007486 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -07007487 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -07007488}
7489
Andy Hung7535ed92023-07-17 17:05:00 -07007490DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung0c1e11e2023-07-06 20:56:16 -07007491 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -07007492 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007493 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007494 mWaitTimeMs(UINT_MAX)
7495{
7496 addOutputTrack(mainThread);
7497}
7498
Andy Hung4b17e882023-07-07 13:47:37 -07007499DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007500{
7501 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7502 mOutputTracks[i]->destroy();
7503 }
7504}
7505
Andy Hung4b17e882023-07-07 13:47:37 -07007506void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007507{
7508 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007509 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007510 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007511 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007512 if (mMixerBufferValid) {
7513 memset(mMixerBuffer, 0, mMixerBufferSize);
7514 } else {
7515 memset(mSinkBuffer, 0, mSinkBufferSize);
7516 }
Eric Laurent81784c32012-11-19 14:55:58 -08007517 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007518 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007519 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007520 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007521 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007522}
7523
Andy Hung4b17e882023-07-07 13:47:37 -07007524void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007525{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007526 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007527 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007528 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007529 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007530 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007531 }
7532 } else if (mBytesWritten != 0) {
7533 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7534 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007535 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007536 } else {
7537 // flush remaining overflow buffers in output tracks
7538 writeFrames = 0;
7539 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007540 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007541 }
7542}
7543
Andy Hung4b17e882023-07-07 13:47:37 -07007544ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007545{
7546 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007547 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7548
7549 // Consider the first OutputTrack for timestamp and frame counting.
7550
7551 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7552 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7553 // we always claim success.
7554 if (i == 0) {
7555 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7556 ALOGD_IF(correction != 0 && writeFrames != 0,
7557 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7558 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7559 mFramesWritten -= correction;
7560 }
7561
7562 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007563 }
Andy Hungcf10d742020-04-28 15:38:24 -07007564 if (mStandby) {
7565 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007566 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007567 mStandby = false;
7568 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007569 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007570}
7571
Andy Hung4b17e882023-07-07 13:47:37 -07007572void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007573{
7574 // DuplicatingThread implements standby by stopping all tracks
7575 for (size_t i = 0; i < outputTracks.size(); i++) {
7576 outputTracks[i]->stop();
7577 }
7578}
7579
Andy Hung4b17e882023-07-07 13:47:37 -07007580void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007581{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007582 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007583
7584 std::stringstream ss;
7585 const size_t numTracks = mOutputTracks.size();
7586 ss << " " << numTracks << " OutputTracks";
7587 if (numTracks > 0) {
7588 ss << ":";
7589 for (const auto &track : mOutputTracks) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007590 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007591 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007592 if (thread.get() != nullptr) {
7593 ss << thread.get() << ", " << thread->id();
7594 } else {
7595 ss << "null";
7596 }
7597 ss << ")";
7598 }
7599 }
7600 ss << "\n";
7601 std::string result = ss.str();
7602 write(fd, result.c_str(), result.size());
7603}
7604
Andy Hung4b17e882023-07-07 13:47:37 -07007605void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007606{
7607 outputTracks = mOutputTracks;
7608}
7609
Andy Hung4b17e882023-07-07 13:47:37 -07007610void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007611{
7612 outputTracks.clear();
7613}
7614
Andy Hung4b17e882023-07-07 13:47:37 -07007615void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007616{
7617 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007618 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7619 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7620 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7621 const size_t frameCount =
7622 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7623 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7624 // from different OutputTracks and their associated MixerThreads (e.g. one may
7625 // nearly empty and the other may be dropping data).
7626
Svet Ganov33761132021-05-13 22:51:08 +00007627 // TODO b/182392769: use attribution source util, move to server edge
7628 AttributionSourceState attributionSource = AttributionSourceState();
7629 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007630 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007631 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007632 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007633 attributionSource.token = sp<BBinder>::make();
Andy Hung11e74242023-06-26 19:20:57 -07007634 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007635 this,
7636 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007637 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007638 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007639 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007640 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007641 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7642 if (status != NO_ERROR) {
7643 ALOGE("addOutputTrack() initCheck failed %d", status);
7644 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007645 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007646 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7647 mOutputTracks.add(outputTrack);
7648 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7649 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007650}
7651
Andy Hung4b17e882023-07-07 13:47:37 -07007652void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007653{
7654 Mutex::Autolock _l(mLock);
7655 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7656 if (mOutputTracks[i]->thread() == thread) {
7657 mOutputTracks[i]->destroy();
7658 mOutputTracks.removeAt(i);
7659 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007660 if (thread->getOutput() == mOutput) {
7661 mOutput = NULL;
7662 }
Eric Laurent81784c32012-11-19 14:55:58 -08007663 return;
7664 }
7665 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007666 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007667}
7668
7669// caller must hold mLock
Andy Hung4b17e882023-07-07 13:47:37 -07007670void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007671{
7672 mWaitTimeMs = UINT_MAX;
7673 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007674 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007675 if (strong != 0) {
7676 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7677 if (waitTimeMs < mWaitTimeMs) {
7678 mWaitTimeMs = waitTimeMs;
7679 }
7680 }
7681 }
7682}
7683
Andy Hung4b17e882023-07-07 13:47:37 -07007684bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007685{
7686 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007687 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007688 if (thread == 0) {
7689 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7690 outputTracks[i].get());
7691 return false;
7692 }
Andy Hung0c1e11e2023-07-06 20:56:16 -07007693 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007694 // see note at standby() declaration
Andy Hung3e4c8742023-06-29 21:19:25 -07007695 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007696 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7697 thread.get());
7698 return false;
7699 }
7700 }
7701 return true;
7702}
7703
Andy Hung4b17e882023-07-07 13:47:37 -07007704void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007705 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007706{
Kevin Rocard12381092018-04-11 09:19:59 -07007707 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7708 outputTrack->setMetadatas(metadata.tracks);
7709 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007710}
7711
Andy Hung4b17e882023-07-07 13:47:37 -07007712uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007713{
7714 return (mWaitTimeMs * 1000) / 2;
7715}
7716
Andy Hung4b17e882023-07-07 13:47:37 -07007717void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007718{
7719 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7720 updateWaitTime_l();
7721
7722 MixerThread::cacheParameters_l();
7723}
7724
Eric Laurentb3f315a2021-07-13 15:09:05 +02007725// ----------------------------------------------------------------------------
7726
Andy Hung4b17e882023-07-07 13:47:37 -07007727/* static */
7728sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung7535ed92023-07-17 17:05:00 -07007729 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007730 AudioStreamOut* output,
7731 audio_io_handle_t id,
7732 bool systemReady,
7733 audio_config_base_t* mixerConfig) {
Andy Hung7535ed92023-07-17 17:05:00 -07007734 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hung4b17e882023-07-07 13:47:37 -07007735}
7736
Andy Hung7535ed92023-07-17 17:05:00 -07007737SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007738 AudioStreamOut* output,
7739 audio_io_handle_t id,
7740 bool systemReady,
7741 audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07007742 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007743{
7744}
7745
Andy Hung4b17e882023-07-07 13:47:37 -07007746void SpatializerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01007747 MixerThread::onFirstRef();
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007748
Andy Hung41ccf7f2022-12-14 14:25:49 -08007749 const pid_t tid = getTid();
7750 if (tid == -1) {
7751 // Unusual: PlaybackThread::onFirstRef() should set the threadLoop running.
7752 ALOGW("%s: Cannot update Spatializer mixer thread priority, not running", __func__);
7753 } else {
7754 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
7755 if (priorityBoost > 0) {
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007756 stream()->setHalThreadPriority(priorityBoost);
7757 }
7758 }
Eric Laurent68a40a82022-05-03 18:15:04 +02007759}
7760
Andy Hung4b17e882023-07-07 13:47:37 -07007761void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007762 // if mSupportedLatencyModes is empty, the HAL stream does not support
7763 // latency mode control and we can exit.
7764 if (mSupportedLatencyModes.empty()) {
7765 return;
7766 }
7767 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7768 if (mSupportedLatencyModes.size() == 1) {
7769 // If the HAL only support one latency mode currently, confirm the choice
7770 latencyMode = mSupportedLatencyModes[0];
7771 } else if (mSupportedLatencyModes.size() > 1) {
7772 // Request low latency if:
7773 // - The low latency mode is requested by the spatializer controller
7774 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7775 // AND
7776 // - At least one active track is spatialized
7777 bool hasSpatializedActiveTrack = false;
7778 for (const auto& track : mActiveTracks) {
7779 if (track->isSpatialized()) {
7780 hasSpatializedActiveTrack = true;
7781 break;
7782 }
7783 }
7784 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7785 latencyMode = AUDIO_LATENCY_MODE_LOW;
7786 }
7787 }
7788
7789 if (latencyMode != mSetLatencyMode) {
7790 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007791 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7792 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007793 if (status == NO_ERROR) {
7794 mSetLatencyMode = latencyMode;
7795 }
7796 }
7797}
7798
Andy Hung4b17e882023-07-07 13:47:37 -07007799status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007800 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7801 return BAD_VALUE;
7802 }
7803 Mutex::Autolock _l(mLock);
7804 mRequestedLatencyMode = mode;
7805 return NO_ERROR;
7806}
7807
Andy Hung4b17e882023-07-07 13:47:37 -07007808void SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007809{
7810 bool hasVirtualizer = false;
7811 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007812 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007813 {
7814 Mutex::Autolock _l(mLock);
Andy Hung116bc262023-06-20 18:56:17 -07007815 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007816 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007817 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007818 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7819 }
7820
7821 finalDownMixer = mFinalDownMixer;
7822 mFinalDownMixer.clear();
7823 }
7824
7825 if (hasVirtualizer) {
7826 if (finalDownMixer != nullptr) {
7827 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007828 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007829 }
7830 finalDownMixer.clear();
7831 } else if (!hasDownMixer) {
7832 std::vector<effect_descriptor_t> descriptors;
Andy Hung7535ed92023-07-17 17:05:00 -07007833 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007834 EFFECT_UIID_DOWNMIX, &descriptors);
7835 if (status != NO_ERROR) {
7836 return;
7837 }
7838 ALOG_ASSERT(!descriptors.empty(),
7839 "%s getDescriptors() returned no error but empty list", __func__);
7840
7841 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7842 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007843 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007844
7845 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7846 ALOGW("%s error creating downmixer %d", __func__, status);
7847 finalDownMixer.clear();
7848 } else {
7849 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007850 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007851 }
7852 }
7853
7854 {
7855 Mutex::Autolock _l(mLock);
7856 mFinalDownMixer = finalDownMixer;
7857 }
7858}
7859
Eric Laurent81784c32012-11-19 14:55:58 -08007860// ----------------------------------------------------------------------------
7861// Record
7862// ----------------------------------------------------------------------------
7863
Andy Hung7535ed92023-07-17 17:05:00 -07007864sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung0c1e11e2023-07-06 20:56:16 -07007865 AudioStreamIn* input,
7866 audio_io_handle_t id,
7867 bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -07007868 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung0c1e11e2023-07-06 20:56:16 -07007869}
7870
Andy Hung7535ed92023-07-17 17:05:00 -07007871RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007872 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007873 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007874 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007875 ) :
Andy Hung7535ed92023-07-17 17:05:00 -07007876 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007877 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007878 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007879 mActiveTracks(&this->mLocalLog),
7880 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007881 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007882 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007883 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7884 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007885 // mFastCapture below
7886 , mFastCaptureFutex(0)
7887 // mInputSource
7888 // mPipeSink
7889 // mPipeSource
7890 , mPipeFramesP2(0)
7891 // mPipeMemory
7892 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007893 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007894 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007895{
Glenn Kastend7dca052015-03-05 16:05:54 -08007896 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung7535ed92023-07-17 17:05:00 -07007897 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007898
George Burgess IVa8f90c12020-05-14 11:27:19 -07007899 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007900 mIsMsdDevice = strcmp(
7901 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7902 }
7903
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007904 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007905
Andy Hungc8fddf32018-08-08 18:32:37 -07007906 // TODO: We may also match on address as well as device type for
7907 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007908 // TODO: This property should be ensure that only contains one single device type.
7909 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7910 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007911 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7912 : AUDIO_DEVICE_NONE));
7913
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007914 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007915 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007916 size_t numCounterOffers = 0;
7917 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007918#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007919 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007920#else
7921 (void)
7922#endif
7923 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007924 ALOG_ASSERT(index == 0);
7925
7926 // initialize fast capture depending on configuration
7927 bool initFastCapture;
7928 switch (kUseFastCapture) {
7929 case FastCapture_Never:
7930 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007931 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007932 break;
7933 case FastCapture_Always:
7934 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007935 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007936 break;
7937 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007938 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
7939 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7940 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d "
7941 "mIsMsdDevice = %d", this, (long long)mFrameCount, mSampleRate,
7942 kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007943 break;
7944 // case FastCapture_Dynamic:
7945 }
7946
7947 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007948 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007949 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007950 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7951 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007952 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007953 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007954 const sp<MemoryDealer> roHeap(readOnlyHeap());
7955 sp<IMemory> pipeMemory;
7956 if ((roHeap == 0) ||
7957 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007958 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007959 ALOGE("not enough memory for pipe buffer size=%zu; "
7960 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7961 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7962 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007963 goto failed;
7964 }
7965 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7966 memset(pipeBuffer, 0, pipeSize);
7967 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07007968 const NBAIO_Format offersFast[1] = {format};
7969 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007970 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07007971 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007972 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007973 mPipeSink = pipe;
7974 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07007975 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007976 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07007977 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007978 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007979 mPipeSource = pipeReader;
7980 mPipeFramesP2 = pipeFramesP2;
7981 mPipeMemory = pipeMemory;
7982
7983 // create fast capture
7984 mFastCapture = new FastCapture();
7985 FastCaptureStateQueue *sq = mFastCapture->sq();
7986#ifdef STATE_QUEUE_DUMP
7987 // FIXME
7988#endif
7989 FastCaptureState *state = sq->begin();
7990 state->mCblk = NULL;
7991 state->mInputSource = mInputSource.get();
7992 state->mInputSourceGen++;
7993 state->mPipeSink = pipe;
7994 state->mPipeSinkGen++;
7995 state->mFrameCount = mFrameCount;
7996 state->mCommand = FastCaptureState::COLD_IDLE;
7997 // already done in constructor initialization list
7998 //mFastCaptureFutex = 0;
7999 state->mColdFutexAddr = &mFastCaptureFutex;
8000 state->mColdGen++;
8001 state->mDumpState = &mFastCaptureDumpState;
8002#ifdef TEE_SINK
8003 // FIXME
8004#endif
Andy Hung7535ed92023-07-17 17:05:00 -07008005 mFastCaptureNBLogWriter =
8006 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008007 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8008 sq->end();
8009 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8010
8011 // start the fast capture
8012 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8013 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008014 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008015 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008016#ifdef AUDIO_WATCHDOG
8017 // FIXME
8018#endif
8019
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008020 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008021 }
Andy Hung8946a282018-04-19 20:04:56 -07008022#ifdef TEE_SINK
8023 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8024 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8025#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008026failed: ;
8027
8028 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008029}
8030
Andy Hung4b17e882023-07-07 13:47:37 -07008031RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008032{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008033 if (mFastCapture != 0) {
8034 FastCaptureStateQueue *sq = mFastCapture->sq();
8035 FastCaptureState *state = sq->begin();
8036 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8037 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8038 if (old == -1) {
8039 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8040 }
8041 }
8042 state->mCommand = FastCaptureState::EXIT;
8043 sq->end();
8044 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8045 mFastCapture->join();
8046 mFastCapture.clear();
8047 }
Andy Hung7535ed92023-07-17 17:05:00 -07008048 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8049 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008050 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008051}
8052
Andy Hung4b17e882023-07-07 13:47:37 -07008053void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008054{
Glenn Kastend7dca052015-03-05 16:05:54 -08008055 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008056}
8057
Andy Hung4b17e882023-07-07 13:47:37 -07008058void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008059{
8060 ALOGV(" preExit()");
8061 Mutex::Autolock _l(mLock);
8062 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07008063 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008064 track->invalidate();
8065 }
8066 mActiveTracks.clear();
8067 mStartStopCond.broadcast();
8068}
8069
Andy Hung4b17e882023-07-07 13:47:37 -07008070bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008071{
Eric Laurent81784c32012-11-19 14:55:58 -08008072 nsecs_t lastWarning = 0;
8073
8074 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008075
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008076reacquire_wakelock:
Andy Hung11e74242023-06-26 19:20:57 -07008077 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008078 {
8079 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07008080 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008081 }
8082
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008083 // used to request a deferred sleep, to be executed later while mutex is unlocked
8084 uint32_t sleepUs = 0;
8085
Andy Hung446f4df2019-02-21 12:26:41 -08008086 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8087
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008088 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008089 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung116bc262023-06-20 18:56:17 -07008090 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008091
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008092 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung11e74242023-06-26 19:20:57 -07008093 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008094
Glenn Kasten735f45f2014-08-18 15:51:59 -07008095 // reference to the (first and only) active fast track
Andy Hung11e74242023-06-26 19:20:57 -07008096 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008097
Glenn Kasten735f45f2014-08-18 15:51:59 -07008098 // reference to a fast track which is about to be removed
Andy Hung11e74242023-06-26 19:20:57 -07008099 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008100
Eric Laurent33403f02020-05-29 18:35:06 -07008101 bool silenceFastCapture = false;
8102
Eric Laurent81784c32012-11-19 14:55:58 -08008103 { // scope for mLock
8104 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08008105
Eric Laurent021cf962014-05-13 10:18:14 -07008106 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008107
Eric Laurent000a4192014-01-29 15:17:32 -08008108 // check exitPending here because checkForNewParameters_l() and
8109 // checkForNewParameters_l() can temporarily release mLock
8110 if (exitPending()) {
8111 break;
8112 }
8113
Eric Laurent5c25d562016-07-13 17:17:45 -07008114 // sleep with mutex unlocked
8115 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008116 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07008117 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
8118 ATRACE_END();
8119 sleepUs = 0;
8120 continue;
8121 }
8122
Glenn Kasten2b806402013-11-20 16:37:38 -08008123 // if no active track(s), then standby and release wakelock
8124 size_t size = mActiveTracks.size();
8125 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008126 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008127 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008128 releaseWakeLock_l();
8129 ALOGV("RecordThread: loop stopping");
8130 // go to sleep
8131 mWaitWorkCV.wait(mLock);
8132 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008133 goto reacquire_wakelock;
8134 }
8135
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008136 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008137 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008138 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008139
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008140 activeTrack = mActiveTracks[i];
8141 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008142 if (activeTrack->isFastTrack()) {
8143 ALOG_ASSERT(fastTrackToRemove == 0);
8144 fastTrackToRemove = activeTrack;
8145 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008146 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008147 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008148 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008149 continue;
8150 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008151
Andy Hung11e74242023-06-26 19:20:57 -07008152 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008153 switch (activeTrackState) {
8154
Andy Hung11e74242023-06-26 19:20:57 -07008155 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008156 mActiveTracks.remove(activeTrack);
Andy Hung11e74242023-06-26 19:20:57 -07008157 activeTrack->setState(IAfTrackBase::PAUSED);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008158 doBroadcast = true;
8159 size--;
8160 continue;
8161
Andy Hung11e74242023-06-26 19:20:57 -07008162 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008163 sleepUs = 10000;
8164 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008165 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008166 continue;
8167
Andy Hung11e74242023-06-26 19:20:57 -07008168 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008169 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008170 if (mStandby) {
8171 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008172 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008173 mStandby = false;
8174 }
Andy Hung11e74242023-06-26 19:20:57 -07008175 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008176 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008177 break;
8178
Andy Hung11e74242023-06-26 19:20:57 -07008179 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008180 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008181 break;
8182
Andy Hung11e74242023-06-26 19:20:57 -07008183 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8184 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8185 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008186 default:
Andy Hungce685402018-10-05 17:23:27 -07008187 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8188 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008189 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008190
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008191 if (activeTrack->isFastTrack()) {
8192 ALOG_ASSERT(!mFastTrackAvail);
8193 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008194 // if the active fast track is silenced either:
8195 // 1) silence the whole capture from fast capture buffer if this is
8196 // the only active track
8197 // 2) invalidate this track: this will cause the client to reconnect and possibly
8198 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008199 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008200 if (activeTrack->isSilenced()) {
8201 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008202 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008203 } else {
8204 silenceFastCapture = true;
8205 }
8206 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008207 // Invalidate fast tracks if access to audio history is required as this is not
8208 // possible with fast tracks. Once the fast track has been invalidated, no new
8209 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8210 if (mMaxSharedAudioHistoryMs != 0) {
8211 invalidate = true;
8212 }
8213 if (invalidate) {
8214 activeTrack->invalidate();
8215 ALOG_ASSERT(fastTrackToRemove == 0);
8216 fastTrackToRemove = activeTrack;
8217 removeTrack_l(activeTrack);
8218 mActiveTracks.remove(activeTrack);
8219 size--;
8220 continue;
8221 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008222 fastTrack = activeTrack;
8223 }
Eric Laurent33403f02020-05-29 18:35:06 -07008224
8225 activeTracks.add(activeTrack);
8226 i++;
8227
Glenn Kasten9e982352013-08-14 14:39:50 -07008228 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008229
Andy Hungdae27702016-10-31 14:01:16 -07008230 mActiveTracks.updatePowerState(this);
8231
Kevin Rocard069c2712018-03-29 19:09:14 -07008232 updateMetadata_l();
8233
Eric Laurent5c25d562016-07-13 17:17:45 -07008234 if (allStopped) {
8235 standbyIfNotAlreadyInStandby();
8236 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008237 if (doBroadcast) {
8238 mStartStopCond.broadcast();
8239 }
8240
8241 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008242 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008243 if (sleepUs == 0) {
8244 sleepUs = kRecordThreadSleepUs;
8245 }
8246 continue;
8247 }
8248 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008249
Eric Laurent81784c32012-11-19 14:55:58 -08008250 lockEffectChains_l(effectChains);
8251 }
8252
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008253 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008254
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008255 size_t size = effectChains.size();
8256 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008257 // thread mutex is not locked, but effect chain is locked
8258 effectChains[i]->process_l();
8259 }
8260
Glenn Kasten735f45f2014-08-18 15:51:59 -07008261 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008262 if (mFastCapture != 0) {
8263 FastCaptureStateQueue *sq = mFastCapture->sq();
8264 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008265 bool didModify = false;
8266 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008267 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8268 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8269 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8270 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8271 if (old == -1) {
8272 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8273 }
8274 }
8275 state->mCommand = FastCaptureState::READ_WRITE;
8276#if 0 // FIXME
Andy Hung7535ed92023-07-17 17:05:00 -07008277 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008278 FastThreadDumpState::kSamplingNforLowRamDevice :
8279 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008280#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008281 didModify = true;
8282 }
8283 audio_track_cblk_t *cblkOld = state->mCblk;
8284 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8285 if (cblkNew != cblkOld) {
8286 state->mCblk = cblkNew;
8287 // block until acked if removing a fast track
8288 if (cblkOld != NULL) {
8289 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8290 }
8291 didModify = true;
8292 }
jiabin01c8f562018-07-19 17:47:28 -07008293 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8294 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8295 if (state->mFastPatchRecordBufferProvider != abp) {
8296 state->mFastPatchRecordBufferProvider = abp;
8297 state->mFastPatchRecordFormat = fastTrack == 0 ?
8298 AUDIO_FORMAT_INVALID : fastTrack->format();
8299 didModify = true;
8300 }
Eric Laurent33403f02020-05-29 18:35:06 -07008301 if (state->mSilenceCapture != silenceFastCapture) {
8302 state->mSilenceCapture = silenceFastCapture;
8303 didModify = true;
8304 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008305 sq->end(didModify);
8306 if (didModify) {
8307 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008308#if 0
8309 if (kUseFastCapture == FastCapture_Dynamic) {
8310 mNormalSource = mPipeSource;
8311 }
8312#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008313 }
8314 }
8315
Glenn Kasten735f45f2014-08-18 15:51:59 -07008316 // now run the fast track destructor with thread mutex unlocked
8317 fastTrackToRemove.clear();
8318
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008319 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8320 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8321 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8322 // If destination is non-contiguous, first read past the nominal end of buffer, then
8323 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008324
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008325 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008326 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008327 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008328
8329 // If an NBAIO source is present, use it to read the normal capture's data
8330 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008331 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008332
8333 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8334 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8335 // we immediately retry the read() to get data and prevent another overflow.
8336 for (int retries = 0; retries <= 2; ++retries) {
8337 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8338 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8339 framesToRead);
8340 if (framesRead != OVERRUN) break;
8341 }
8342
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008343 const ssize_t availableToRead = mPipeSource->availableToRead();
8344 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008345 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008346 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008347 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8348 "more frames to read than fifo size, %zd > %zu",
8349 availableToRead, mPipeFramesP2);
8350 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8351 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8352 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8353 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008354 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8355 }
8356 if (framesRead < 0) {
8357 status_t status = (status_t) framesRead;
8358 switch (status) {
8359 case OVERRUN:
8360 ALOGW("overrun on read from pipe");
8361 framesRead = 0;
8362 break;
8363 case NEGOTIATE:
8364 ALOGE("re-negotiation is needed");
8365 framesRead = -1; // Will cause an attempt to recover.
8366 break;
8367 default:
8368 ALOGE("unknown error %d on read from pipe", status);
8369 break;
8370 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008371 }
8372 // otherwise use the HAL / AudioStreamIn directly
8373 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008374 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008375 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008376 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008377 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008378 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008379 if (result < 0) {
8380 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008381 } else {
8382 framesRead = bytesRead / mFrameSize;
8383 }
8384 }
8385
Andy Hung446f4df2019-02-21 12:26:41 -08008386 const int64_t lastIoEndNs = systemTime(); // end IO timing
8387
Andy Hung3f0c9022016-01-15 17:49:46 -08008388 // Update server timestamp with server stats
8389 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008390 if (framesRead >= 0) {
8391 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8392 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8393 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008394
8395 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008396 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008397 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008398 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008399 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8400 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8401 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008402 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008403 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8404
8405 mTimestampVerifier.add(position, time, mSampleRate);
8406
8407 // Correct timestamps
8408 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008409 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008410 id(), (long long)time, (long long)position);
8411 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8412 position = correctedTimestamp.mFrames;
8413 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008414 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008415 id(), (long long)time, (long long)position);
8416 }
8417
Andy Hung3f0c9022016-01-15 17:49:46 -08008418 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8419 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8420 // Note: In general record buffers should tend to be empty in
8421 // a properly running pipeline.
8422 //
8423 // Also, it is not advantageous to call get_presentation_position during the read
8424 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008425 } else {
8426 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008427 }
8428 }
Andy Hunge6c37112019-02-26 17:38:10 -08008429
8430 // From the timestamp, input read latency is negative output write latency.
8431 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung11e74242023-06-26 19:20:57 -07008432 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008433 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8434 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8435 mLatencyMs.add(latencyMs);
8436 }
8437
Andy Hung3f0c9022016-01-15 17:49:46 -08008438 // Use this to track timestamp information
8439 // ALOGD("%s", mTimestamp.toString().c_str());
8440
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008441 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008442 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008443 // Force input into standby so that it tries to recover at next read attempt
8444 inputStandBy();
8445 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008446 }
8447 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008448 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008449 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008450 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008451 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008452
Andy Hung8946a282018-04-19 20:04:56 -07008453#ifdef TEE_SINK
8454 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8455#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008456 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008457 {
8458 size_t part1 = mRsmpInFramesP2 - rear;
8459 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008460 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008461 (framesRead - part1) * mFrameSize);
8462 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008463 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008464 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008465
8466 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008467
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008468 // loop over each active track
8469 for (size_t i = 0; i < size; i++) {
8470 activeTrack = activeTracks[i];
8471
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008472 // skip fast tracks, as those are handled directly by FastCapture
8473 if (activeTrack->isFastTrack()) {
8474 continue;
8475 }
8476
Andy Hung73c02e42015-03-29 01:13:58 -07008477 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008478 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8479
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008480 enum {
8481 OVERRUN_UNKNOWN,
8482 OVERRUN_TRUE,
8483 OVERRUN_FALSE
8484 } overrun = OVERRUN_UNKNOWN;
8485
8486 // loop over getNextBuffer to handle circular sink
8487 for (;;) {
8488
Andy Hung11e74242023-06-26 19:20:57 -07008489 activeTrack->sinkBuffer().frameCount = ~0;
8490 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8491 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008492 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8493
Andy Hung73c02e42015-03-29 01:13:58 -07008494 // check available frames and handle overrun conditions
8495 // if the record track isn't draining fast enough.
8496 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008497 size_t framesIn;
Andy Hung11e74242023-06-26 19:20:57 -07008498 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008499 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008500 overrun = OVERRUN_TRUE;
8501 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008502 if (framesOut == 0 || framesIn == 0) {
8503 break;
8504 }
8505
Andy Hung6770c6f2015-04-07 13:43:36 -07008506 // Don't allow framesOut to be larger than what is possible with resampling
8507 // from framesIn.
8508 // This isn't strictly necessary but helps limit buffer resizing in
8509 // RecordBufferConverter. TODO: remove when no longer needed.
8510 framesOut = min(framesOut,
8511 destinationFramesPossible(
Andy Hung11e74242023-06-26 19:20:57 -07008512 framesIn, mSampleRate, activeTrack->sampleRate()));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008513
8514 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008515 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008516 // straight from RecordThread buffer to RecordTrack buffer.
8517 AudioBufferProvider::Buffer buffer;
8518 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008519 const status_t getNextBufferStatus =
Andy Hung11e74242023-06-26 19:20:57 -07008520 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008521 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008522 ALOGV_IF(buffer.frameCount != framesOut,
8523 "%s() read less than expected (%zu vs %zu)",
8524 __func__, buffer.frameCount, framesOut);
8525 framesOut = buffer.frameCount;
Andy Hung11e74242023-06-26 19:20:57 -07008526 memcpy(activeTrack->sinkBuffer().raw,
8527 buffer.raw, buffer.frameCount * mFrameSize);
8528 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008529 } else {
8530 framesOut = 0;
8531 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008532 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008533 }
8534 } else {
8535 // process frames from the RecordThread buffer provider to the RecordTrack
8536 // buffer
Andy Hung11e74242023-06-26 19:20:57 -07008537 framesOut = activeTrack->recordBufferConverter()->convert(
8538 activeTrack->sinkBuffer().raw,
8539 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008540 framesOut);
8541 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008542
8543 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8544 overrun = OVERRUN_FALSE;
8545 }
8546
Andy Hung93bb5732023-05-04 21:16:34 -07008547 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8548 const ssize_t framesToDrop =
Andy Hung11e74242023-06-26 19:20:57 -07008549 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008550 if (framesToDrop == 0) {
8551 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008552 if (framesOut > 0) {
Andy Hung11e74242023-06-26 19:20:57 -07008553 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008554 // Sanitize before releasing if the track has no access to the source data
8555 // An idle UID receives silence from non virtual devices until active
8556 if (activeTrack->isSilenced()) {
Andy Hung11e74242023-06-26 19:20:57 -07008557 memset(activeTrack->sinkBuffer().raw,
8558 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008559 }
Andy Hung11e74242023-06-26 19:20:57 -07008560 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008561 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008562 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008563 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008564 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008565 }
8566 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008567
8568 switch (overrun) {
8569 case OVERRUN_TRUE:
8570 // client isn't retrieving buffers fast enough
8571 if (!activeTrack->setOverflow()) {
8572 nsecs_t now = systemTime();
8573 // FIXME should lastWarning per track?
8574 if ((now - lastWarning) > kWarningThrottleNs) {
8575 ALOGW("RecordThread: buffer overflow");
8576 lastWarning = now;
8577 }
8578 }
8579 break;
8580 case OVERRUN_FALSE:
8581 activeTrack->clearOverflow();
8582 break;
8583 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008584 break;
8585 }
8586
Andy Hung3f0c9022016-01-15 17:49:46 -08008587 // update frame information and push timestamp out
8588 activeTrack->updateTrackFrameInfo(
Andy Hung11e74242023-06-26 19:20:57 -07008589 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008590 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8591 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008592 }
8593
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008594unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008595 // enable changes in effect chain
8596 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008597 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008598 if (audio_has_proportional_frames(mFormat)
8599 && loopCount == lastLoopCountRead + 1) {
8600 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8601 const double jitterMs =
8602 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8603 {framesRead, readPeriodNs},
8604 {0, 0} /* lastTimestamp */, mSampleRate);
8605 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8606
8607 Mutex::Autolock _l(mLock);
8608 mIoJitterMs.add(jitterMs);
8609 mProcessTimeMs.add(processMs);
8610 }
8611 // update timing info.
8612 mLastIoBeginNs = lastIoBeginNs;
8613 mLastIoEndNs = lastIoEndNs;
8614 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008615 }
8616
Glenn Kasten93e471f2013-08-19 08:40:07 -07008617 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008618
8619 {
8620 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008621 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07008622 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008623 track->invalidate();
8624 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008625 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008626 mStartStopCond.broadcast();
8627 }
8628
8629 releaseWakeLock();
8630
8631 ALOGV("RecordThread %p exiting", this);
8632 return false;
8633}
8634
Andy Hung4b17e882023-07-07 13:47:37 -07008635void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008636{
8637 if (!mStandby) {
8638 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008639 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008640 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008641 mStandby = true;
8642 }
8643}
8644
Andy Hung4b17e882023-07-07 13:47:37 -07008645void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008646{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008647 // Idle the fast capture if it's currently running
8648 if (mFastCapture != 0) {
8649 FastCaptureStateQueue *sq = mFastCapture->sq();
8650 FastCaptureState *state = sq->begin();
8651 if (!(state->mCommand & FastCaptureState::IDLE)) {
8652 state->mCommand = FastCaptureState::COLD_IDLE;
8653 state->mColdFutexAddr = &mFastCaptureFutex;
8654 state->mColdGen++;
8655 mFastCaptureFutex = 0;
8656 sq->end();
8657 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8658 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8659#if 0
8660 if (kUseFastCapture == FastCapture_Dynamic) {
8661 // FIXME
8662 }
8663#endif
8664#ifdef AUDIO_WATCHDOG
8665 // FIXME
8666#endif
8667 } else {
8668 sq->end(false /*didModify*/);
8669 }
8670 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008671 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008672 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008673
8674 // If going into standby, flush the pipe source.
8675 if (mPipeSource.get() != nullptr) {
8676 const ssize_t flushed = mPipeSource->flush();
8677 if (flushed > 0) {
8678 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8679 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8680 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8681 }
8682 }
Eric Laurent81784c32012-11-19 14:55:58 -08008683}
8684
Glenn Kasten05997e22014-03-13 15:08:33 -07008685// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07008686sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008687 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008688 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008689 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008690 audio_format_t format,
8691 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008692 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008693 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008694 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008695 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008696 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008697 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008698 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008699 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008700 audio_port_handle_t portId,
8701 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008702{
Glenn Kasten74935e42013-12-19 08:56:45 -08008703 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008704 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung11e74242023-06-26 19:20:57 -07008705 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008706 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008707 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008708 audio_input_flags_t requestedFlags = *flags;
8709 uint32_t sampleRate;
8710
8711 lStatus = initCheck();
8712 if (lStatus != NO_ERROR) {
8713 ALOGE("createRecordTrack_l() audio driver not initialized");
8714 goto Exit;
8715 }
8716
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008717 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8718 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8719 lStatus = BAD_VALUE;
8720 goto Exit;
8721 }
8722
Eric Laurentec376dc2021-04-08 20:41:22 +02008723 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008724 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008725 lStatus = PERMISSION_DENIED;
8726 goto Exit;
8727 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008728 if (maxSharedAudioHistoryMs < 0
8729 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8730 lStatus = BAD_VALUE;
8731 goto Exit;
8732 }
8733 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008734 if (*pSampleRate == 0) {
8735 *pSampleRate = mSampleRate;
8736 }
8737 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008738
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008739 // special case for FAST flag considered OK if fast capture is present and access to
8740 // audio history is not required
8741 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008742 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8743 }
8744
Eric Laurentf14db3c2017-12-08 14:20:36 -08008745 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008746 if ((*flags & inputFlags) != *flags) {
8747 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8748 " input flags (%08x)",
8749 *flags, inputFlags);
8750 *flags = (audio_input_flags_t)(*flags & inputFlags);
8751 }
Eric Laurent81784c32012-11-19 14:55:58 -08008752
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008753 // client expresses a preference for FAST and no access to audio history,
8754 // but we get the final say
8755 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008756 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008757 // we formerly checked for a callback handler (non-0 tid),
8758 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008759 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008760 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008761 // Frame count is not specified (0), or is less than or equal the pipe depth.
8762 // It is OK to provide a higher capacity than requested.
8763 // We will force it to mPipeFramesP2 below.
8764 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008765 // PCM data
8766 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008767 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008768 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008769 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008770 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008771 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008772 hasFastCapture() &&
8773 // there are sufficient fast track slots available
8774 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008775 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008776 // check compatibility with audio effects.
8777 Mutex::Autolock _l(mLock);
8778 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008779 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008780 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008781 audio_input_flags_t old = *flags;
8782 chain->checkInputFlagCompatibility(flags);
8783 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008784 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8785 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008786 }
8787 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008788 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008789 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8790 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008791 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008792 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8793 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008794 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008795 this, frameCount, mFrameCount, mPipeFramesP2,
8796 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008797 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008798 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008799 }
8800 }
8801
Eric Laurentf14db3c2017-12-08 14:20:36 -08008802 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8803 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8804 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8805 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8806 lStatus = BAD_TYPE;
8807 goto Exit;
8808 }
8809
Glenn Kasten74105912014-07-03 12:28:53 -07008810 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008811 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008812 // fast track: frame count is exactly the pipe depth
8813 frameCount = mPipeFramesP2;
8814 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008815 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008816 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008817 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8818 // or 20 ms if there is a fast capture
8819 // TODO This could be a roundupRatio inline, and const
8820 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8821 * sampleRate + mSampleRate - 1) / mSampleRate;
8822 // minimum number of notification periods is at least kMinNotifications,
8823 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8824 static const size_t kMinNotifications = 3;
8825 static const uint32_t kMinMs = 30;
8826 // TODO This could be a roundupRatio inline
8827 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8828 // TODO This could be a roundupRatio inline
8829 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8830 maxNotificationFrames;
8831 const size_t minFrameCount = maxNotificationFrames *
8832 max(kMinNotifications, minNotificationsByMs);
8833 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008834 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8835 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008836 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008837 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008838 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008839 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008840
8841 { // scope for mLock
8842 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008843 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008844 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008845 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008846 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008847 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008848 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008849 }
Eric Laurent81784c32012-11-19 14:55:58 -08008850
Andy Hung11e74242023-06-26 19:20:57 -07008851 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008852 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008853 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung11e74242023-06-26 19:20:57 -07008854 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008855 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008856
Glenn Kasten03003332013-08-06 15:40:54 -07008857 lStatus = track->initCheck();
8858 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008859 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008860 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008861 goto Exit;
8862 }
8863 mTracks.add(track);
8864
Eric Laurent05067782016-06-01 18:27:28 -07008865 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008866 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8867 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8868 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008869 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008870 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008871
8872 if (maxSharedAudioHistoryMs != 0) {
8873 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8874 }
Eric Laurent81784c32012-11-19 14:55:58 -08008875 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008876
Eric Laurent81784c32012-11-19 14:55:58 -08008877 lStatus = NO_ERROR;
8878
8879Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008880 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008881 return track;
8882}
8883
Andy Hung4b17e882023-07-07 13:47:37 -07008884status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08008885 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008886 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008887{
8888 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8889 sp<ThreadBase> strongMe = this;
8890 status_t status = NO_ERROR;
8891
8892 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008893 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008894 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung11e74242023-06-26 19:20:57 -07008895 recordTrack->synchronizedRecordState().startRecording(
Andy Hung7535ed92023-07-17 17:05:00 -07008896 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07008897 event, triggerSession,
8898 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08008899 }
8900
8901 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008902 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008903 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008904 if (recordTrack->isInvalid()) {
8905 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008906 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8907 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008908 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008909 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung11e74242023-06-26 19:20:57 -07008910 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008911 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8912 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008913 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung11e74242023-06-26 19:20:57 -07008914 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008915 } else {
Andy Hung11e74242023-06-26 19:20:57 -07008916 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008917 }
8918 return status;
8919 }
8920
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008921 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8922 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8923 // or using a separate command thread
Andy Hung11e74242023-06-26 19:20:57 -07008924 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08008925 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008926 if (recordTrack->isExternalTrack()) {
8927 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008928 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008929 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008930 if (recordTrack->isInvalid()) {
8931 recordTrack->clearSyncStartEvent();
Andy Hung11e74242023-06-26 19:20:57 -07008932 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
8933 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07008934 // STARTING_2 forces destroy to call stopInput.
8935 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008936 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8937 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008938 }
Andy Hung11e74242023-06-26 19:20:57 -07008939 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07008940 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung11e74242023-06-26 19:20:57 -07008941 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07008942 // Someone else has changed state, let them take over,
8943 // leave mState in the new state.
8944 recordTrack->clearSyncStartEvent();
8945 return INVALID_OPERATION;
8946 }
8947 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008948 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008949 ALOGW("%s(%d): startInput failed, status %d",
8950 __func__, recordTrack->id(), status);
8951 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8952 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008953 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008954 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008955 return status;
8956 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008957 sendIoConfigEvent_l(
8958 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008959 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008960
8961 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8962
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008963 // Catch up with current buffer indices if thread is already running.
8964 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8965 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8966 // see previously buffered data before it called start(), but with greater risk of overrun.
8967
Andy Hung11e74242023-06-26 19:20:57 -07008968 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008969 if (!recordTrack->isDirect()) {
8970 // clear any converter state as new data will be discontinuous
Andy Hung11e74242023-06-26 19:20:57 -07008971 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008972 }
Andy Hung11e74242023-06-26 19:20:57 -07008973 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08008974 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008975 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008976 return status;
8977 }
Eric Laurent81784c32012-11-19 14:55:58 -08008978}
8979
Andy Hung4b17e882023-07-07 13:47:37 -07008980void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08008981{
Andy Hung4b17e882023-07-07 13:47:37 -07008982 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08008983
8984 if (strongEvent != 0) {
Andy Hungfafbebc2023-06-23 19:27:19 -07008985 sp<IAfTrackBase> ptr =
8986 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
8987 if (ptr != nullptr) {
Andy Hungeb6b5f82023-07-14 11:00:08 -07008988 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungfafbebc2023-06-23 19:27:19 -07008989 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08008990 }
Eric Laurent81784c32012-11-19 14:55:58 -08008991 }
8992}
8993
Andy Hung4b17e882023-07-07 13:47:37 -07008994bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008995 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008996 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008997 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung11e74242023-06-26 19:20:57 -07008998 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008999 return false;
9000 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009001 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung11e74242023-06-26 19:20:57 -07009002 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009003
Andy Hungabfab202019-03-07 19:45:54 -08009004 // NOTE: Waiting here is important to keep stop synchronous.
9005 // This is needed for proper patchRecord peer release.
Andy Hung11e74242023-06-26 19:20:57 -07009006 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungce685402018-10-05 17:23:27 -07009007 mWaitWorkCV.broadcast(); // signal thread to stop
9008 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08009009 }
Andy Hungce685402018-10-05 17:23:27 -07009010
Andy Hung11e74242023-06-26 19:20:57 -07009011 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009012 ALOGV("Record stopped OK");
9013 return true;
9014 }
Andy Hungce685402018-10-05 17:23:27 -07009015
9016 // don't handle anything - we've been invalidated or restarted and in a different state
9017 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung11e74242023-06-26 19:20:57 -07009018 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009019 return false;
9020}
9021
Andy Hung4b17e882023-07-07 13:47:37 -07009022bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009023{
9024 return false;
9025}
9026
Andy Hung4b17e882023-07-07 13:47:37 -07009027status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009028{
9029#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9030 if (!isValidSyncEvent(event)) {
9031 return BAD_VALUE;
9032 }
9033
Glenn Kastend848eb42016-03-08 13:42:11 -08009034 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009035 status_t ret = NAME_NOT_FOUND;
9036
9037 Mutex::Autolock _l(mLock);
9038
9039 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009040 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009041 if (eventSession == track->sessionId()) {
9042 (void) track->setSyncEvent(event);
9043 ret = NO_ERROR;
9044 }
9045 }
9046 return ret;
9047#else
9048 return BAD_VALUE;
9049#endif
9050}
9051
Andy Hung4b17e882023-07-07 13:47:37 -07009052status_t RecordThread::getActiveMicrophones(
Andy Hung0c1e11e2023-07-06 20:56:16 -07009053 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009054{
9055 ALOGV("RecordThread::getActiveMicrophones");
9056 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009057 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009058 return NO_INIT;
9059 }
jiabin9ff780e2018-03-19 18:19:52 -07009060 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9061 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009062}
9063
Andy Hung4b17e882023-07-07 13:47:37 -07009064status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009065 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009066{
Paul McLean12340082019-03-19 09:35:05 -06009067 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009068 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009069 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009070 return NO_INIT;
9071 }
Paul McLean12340082019-03-19 09:35:05 -06009072 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009073}
9074
Andy Hung4b17e882023-07-07 13:47:37 -07009075status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009076{
Paul McLean12340082019-03-19 09:35:05 -06009077 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009078 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009079 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009080 return NO_INIT;
9081 }
Paul McLean12340082019-03-19 09:35:05 -06009082 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009083}
9084
Andy Hung4b17e882023-07-07 13:47:37 -07009085status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009086 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9087 int64_t sharedAudioStartMs) {
9088 AutoMutex _l(mLock);
9089 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9090}
9091
Andy Hung4b17e882023-07-07 13:47:37 -07009092status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009093 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9094 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009095
Eric Laurentec376dc2021-04-08 20:41:22 +02009096 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9097 return BAD_VALUE;
9098 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009099
9100 if (sharedAudioStartMs < 0
9101 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009102 return BAD_VALUE;
9103 }
9104
Eric Laurent2407ce32021-04-26 14:56:03 +02009105 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9106 // As we cannot detect more than one wraparound, only accept values up current write position
9107 // after one wraparound
9108 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9109 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009110 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009111 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9112 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009113 // Bring the start frame position within the input buffer to match the documented
9114 // "best effort" behavior of the API.
9115 if (sharedOffset < 0) {
9116 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009117 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009118 sharedAudioStartFrames =
9119 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009120 }
9121
Eric Laurentec376dc2021-04-08 20:41:22 +02009122 mSharedAudioPackageName = sharedAudioPackageName;
9123 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009124 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009125 } else {
9126 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009127 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009128 }
9129 return NO_ERROR;
9130}
9131
Andy Hung4b17e882023-07-07 13:47:37 -07009132void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009133 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9134 mSharedAudioStartFrames = -1;
9135 mSharedAudioPackageName = "";
9136}
9137
Andy Hung4b17e882023-07-07 13:47:37 -07009138ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009139{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009140 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009141 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009142 }
9143 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009144 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung11e74242023-06-26 19:20:57 -07009145 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009146 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009147 }
9148 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009149 MetadataUpdate change;
9150 change.recordMetadataUpdate = metadata.tracks;
9151 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009152}
9153
Eric Laurent81784c32012-11-19 14:55:58 -08009154// destroyTrack_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07009155void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009156{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009157 track->terminate();
Andy Hung11e74242023-06-26 19:20:57 -07009158 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009159
Eric Laurent81784c32012-11-19 14:55:58 -08009160 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009161 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009162 removeTrack_l(track);
9163 }
9164}
9165
Andy Hung4b17e882023-07-07 13:47:37 -07009166void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009167{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009168 String8 result;
9169 track->appendDump(result, false /* active */);
9170 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
9171
Eric Laurent81784c32012-11-19 14:55:58 -08009172 mTracks.remove(track);
9173 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009174 if (track->isFastTrack()) {
9175 ALOG_ASSERT(!mFastTrackAvail);
9176 mFastTrackAvail = true;
9177 }
Eric Laurent81784c32012-11-19 14:55:58 -08009178}
9179
Andy Hung4b17e882023-07-07 13:47:37 -07009180void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009181{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009182 AudioStreamIn *input = mInput;
9183 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9184 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009185 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009186 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009187 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009188 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009189 }
Andy Hungbfa64962017-06-12 14:43:19 -07009190
9191 if (input != nullptr) {
9192 dprintf(fd, " Hal stream dump:\n");
9193 (void)input->stream->dump(fd);
9194 }
9195
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009196 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009197 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009198
Glenn Kasten2f90c512015-12-02 11:40:09 -08009199 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9200 // while we are dumping it. It may be inconsistent, but it won't mutate!
9201 // This is a large object so we place it on the heap.
9202 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009203 const std::unique_ptr<FastCaptureDumpState> copy =
9204 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009205 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009206}
9207
Andy Hung4b17e882023-07-07 13:47:37 -07009208void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009209{
Eric Laurent81784c32012-11-19 14:55:58 -08009210 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009211 size_t numtracks = mTracks.size();
9212 size_t numactive = mActiveTracks.size();
9213 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009214 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009215 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009216 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009217 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009218 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009219 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009220 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07009221 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009222 if (track != 0) {
9223 bool active = mActiveTracks.indexOf(track) >= 0;
9224 if (active) {
9225 numactiveseen++;
9226 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009227 result.append(prefix);
9228 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009229 }
Eric Laurent81784c32012-11-19 14:55:58 -08009230 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009231 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009232 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009233 }
9234
Marco Nelissenb2208842014-02-07 14:00:50 -08009235 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009236 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009237 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009238 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009239 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009240 for (size_t i = 0; i < numactive; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07009241 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009242 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009243 result.append(prefix);
9244 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009245 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009246 }
Eric Laurent81784c32012-11-19 14:55:58 -08009247
9248 }
9249 write(fd, result.string(), result.size());
9250}
9251
Andy Hung4b17e882023-07-07 13:47:37 -07009252void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009253{
9254 Mutex::Autolock _l(mLock);
9255 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009256 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009257 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009258 track->setSilenced(silenced);
9259 }
9260 }
9261}
Andy Hung73c02e42015-03-29 01:13:58 -07009262
Andy Hung11e74242023-06-26 19:20:57 -07009263void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009264{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009265 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung4b17e882023-07-07 13:47:37 -07009266 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009267 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009268 const int32_t rear = recordThread->mRsmpInRear;
9269 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009270 if (mRecordTrack->startFrames() >= 0) {
9271 int32_t startFrames = mRecordTrack->startFrames();
9272 // Accept a recent wraparound of mRsmpInRear
9273 if (startFrames <= rear) {
9274 deltaFrames = rear - startFrames;
9275 } else {
9276 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009277 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009278 // start frame cannot be further in the past than start of resampling buffer
9279 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9280 deltaFrames = recordThread->mRsmpInFrames;
9281 }
9282 }
9283 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009284}
9285
Andy Hung11e74242023-06-26 19:20:57 -07009286void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009287 size_t *framesAvailable, bool *hasOverrun)
9288{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009289 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung4b17e882023-07-07 13:47:37 -07009290 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009291 const int32_t rear = recordThread->mRsmpInRear;
9292 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009293 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009294
9295 size_t framesIn;
9296 bool overrun = false;
9297 if (filled < 0) {
9298 // should not happen, but treat like a massive overrun and re-sync
9299 framesIn = 0;
9300 mRsmpInFront = rear;
9301 overrun = true;
9302 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9303 framesIn = (size_t) filled;
9304 } else {
9305 // client is not keeping up with server, but give it latest data
9306 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009307 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9308 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009309 overrun = true;
9310 }
9311 if (framesAvailable != NULL) {
9312 *framesAvailable = framesIn;
9313 }
9314 if (hasOverrun != NULL) {
9315 *hasOverrun = overrun;
9316 }
9317}
9318
Eric Laurent81784c32012-11-19 14:55:58 -08009319// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07009320status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009321 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009322{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009323 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009324 if (threadBase == 0) {
9325 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009326 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009327 return NOT_ENOUGH_DATA;
9328 }
Andy Hung4b17e882023-07-07 13:47:37 -07009329 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009330 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009331 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009332 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009333 // FIXME should not be P2 (don't want to increase latency)
9334 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009335 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009336 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009337
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009338 front &= recordThread->mRsmpInFramesP2 - 1;
9339 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009340 if (part1 > (size_t) filled) {
9341 part1 = filled;
9342 }
9343 size_t ask = buffer->frameCount;
9344 ALOG_ASSERT(ask > 0);
9345 if (part1 > ask) {
9346 part1 = ask;
9347 }
9348 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009349 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009350 buffer->raw = NULL;
9351 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009352 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009353 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009354 }
9355
Andy Hung57446612015-04-19 23:56:46 -07009356 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009357 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009358 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009359 return NO_ERROR;
9360}
9361
9362// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07009363void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009364 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009365{
Hongwei Wang95e37682019-04-12 11:13:36 -07009366 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009367 if (stepCount == 0) {
9368 return;
9369 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009370 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009371 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009372 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009373 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009374 buffer->frameCount = 0;
9375}
9376
Andy Hung4b17e882023-07-07 13:47:37 -07009377void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009378{
9379 Mutex::Autolock _l(mLock);
9380 checkBtNrec_l();
9381}
9382
Andy Hung4b17e882023-07-07 13:47:37 -07009383void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009384{
9385 // disable AEC and NS if the device is a BT SCO headset supporting those
9386 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009387 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Andy Hung7535ed92023-07-17 17:05:00 -07009388 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009389 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9390 for (size_t i = 0; i < mEffectChains.size(); i++) {
9391 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9392 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9393 }
9394 }
9395}
9396
Andy Hung97a893e2015-03-29 01:03:07 -07009397
Andy Hung4b17e882023-07-07 13:47:37 -07009398bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009399 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009400{
9401 bool reconfig = false;
9402
Eric Laurent10351942014-05-08 18:49:52 -07009403 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009404
Eric Laurent10351942014-05-08 18:49:52 -07009405 audio_format_t reqFormat = mFormat;
9406 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009407 // 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 +08009408 [[maybe_unused]] audio_channel_mask_t channelMask =
9409 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009410
9411 AudioParameter param = AudioParameter(keyValuePair);
9412 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009413
9414 // scope for AutoPark extends to end of method
9415 AutoPark<FastCapture> park(mFastCapture);
9416
Eric Laurent10351942014-05-08 18:49:52 -07009417 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9418 // channel count change can be requested. Do we mandate the first client defines the
9419 // HAL sampling rate and channel count or do we allow changes on the fly?
9420 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9421 samplingRate = value;
9422 reconfig = true;
9423 }
9424 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009425 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009426 status = BAD_VALUE;
9427 } else {
9428 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009429 reconfig = true;
9430 }
Eric Laurent10351942014-05-08 18:49:52 -07009431 }
9432 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9433 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009434 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009435 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009436 status = BAD_VALUE;
9437 } else {
9438 channelMask = mask;
9439 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009440 }
Eric Laurent10351942014-05-08 18:49:52 -07009441 }
9442 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9443 // do not accept frame count changes if tracks are open as the track buffer
9444 // size depends on frame count and correct behavior would not be guaranteed
9445 // if frame count is changed after track creation
9446 if (mActiveTracks.size() > 0) {
9447 status = INVALID_OPERATION;
9448 } else {
9449 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009450 }
Eric Laurent10351942014-05-08 18:49:52 -07009451 }
9452 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009453 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009454 }
9455 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9456 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009457 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009458 }
Glenn Kastene198c362013-08-13 09:13:36 -07009459
Eric Laurent10351942014-05-08 18:49:52 -07009460 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009461 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009462 if (status == INVALID_OPERATION) {
9463 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009464 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009465 }
9466 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009467 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009468 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9469 if (mInput->stream->getAudioProperties(&config) == OK &&
9470 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9471 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009472 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009473 status = NO_ERROR;
9474 }
Eric Laurent81784c32012-11-19 14:55:58 -08009475 }
Eric Laurent10351942014-05-08 18:49:52 -07009476 if (status == NO_ERROR) {
9477 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009478 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009479 }
9480 }
Eric Laurent81784c32012-11-19 14:55:58 -08009481 }
Eric Laurent10351942014-05-08 18:49:52 -07009482
Eric Laurent81784c32012-11-19 14:55:58 -08009483 return reconfig;
9484}
9485
Andy Hung4b17e882023-07-07 13:47:37 -07009486String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009487{
Eric Laurent81784c32012-11-19 14:55:58 -08009488 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009489 if (initCheck() == NO_ERROR) {
9490 String8 out_s8;
9491 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9492 return out_s8;
9493 }
Eric Laurent81784c32012-11-19 14:55:58 -08009494 }
Andy Hung920f6572022-10-06 12:09:49 -07009495 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009496}
9497
Andy Hung4b17e882023-07-07 13:47:37 -07009498void RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009499 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009500 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009501 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009502 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009503 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009504 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009505 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9506 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009507 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009508 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009509 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009510 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009511 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009512 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009513 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009514 break;
9515 }
Andy Hung7535ed92023-07-17 17:05:00 -07009516 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009517}
9518
Andy Hung4b17e882023-07-07 13:47:37 -07009519void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009520{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009521 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9522 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009523 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009524 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9525 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009526 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9527 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009528 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009529 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009530 ALOGI("HAL format %#x is not linear pcm", mFormat);
9531 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009532 result = mInput->stream->getFrameSize(&mFrameSize);
9533 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009534 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9535 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009536 result = mInput->stream->getBufferSize(&mBufferSize);
9537 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009538 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009539 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9540 "mBufferSize=%zu, mFrameCount=%zu",
9541 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009542
Eric Laurentec376dc2021-04-08 20:41:22 +02009543 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9544 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009545 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009546
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009547 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9548 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009549
9550 audio_input_flags_t flags = mInput->flags;
9551 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9552 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9553 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9554 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9555 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9556 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9557 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9558 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9559 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009560}
9561
Andy Hung4b17e882023-07-07 13:47:37 -07009562uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009563{
9564 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009565 uint32_t result;
9566 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9567 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009568 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009569 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009570}
9571
Andy Hung4b17e882023-07-07 13:47:37 -07009572KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009573{
Glenn Kastend848eb42016-03-08 13:42:11 -08009574 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009575 Mutex::Autolock _l(mLock);
9576 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung11e74242023-06-26 19:20:57 -07009577 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009578 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009579 if (ids.indexOfKey(sessionId) < 0) {
9580 ids.add(sessionId, true);
9581 }
9582 }
9583 return ids;
9584}
9585
Andy Hung4b17e882023-07-07 13:47:37 -07009586AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009587{
9588 Mutex::Autolock _l(mLock);
9589 AudioStreamIn *input = mInput;
9590 mInput = NULL;
9591 return input;
9592}
9593
9594// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hung4b17e882023-07-07 13:47:37 -07009595sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009596{
9597 if (mInput == NULL) {
9598 return NULL;
9599 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009600 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009601}
9602
Andy Hung4b17e882023-07-07 13:47:37 -07009603status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009604{
Eric Laurent81784c32012-11-19 14:55:58 -08009605 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009606 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009607 chain->setInBuffer(NULL);
9608 chain->setOutBuffer(NULL);
9609
9610 checkSuspendOnAddEffectChain_l(chain);
9611
Eric Laurent1b928682014-10-02 19:41:47 -07009612 // make sure enabled pre processing effects state is communicated to the HAL as we
9613 // just moved them to a new input stream.
9614 chain->syncHalEffectsState();
9615
Eric Laurent81784c32012-11-19 14:55:58 -08009616 mEffectChains.add(chain);
9617
9618 return NO_ERROR;
9619}
9620
Andy Hung4b17e882023-07-07 13:47:37 -07009621size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009622{
9623 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009624
9625 for (size_t i = 0; i < mEffectChains.size(); i++) {
9626 if (chain == mEffectChains[i]) {
9627 mEffectChains.removeAt(i);
9628 break;
9629 }
Eric Laurent81784c32012-11-19 14:55:58 -08009630 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009631 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009632}
9633
Andy Hung4b17e882023-07-07 13:47:37 -07009634status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009635 audio_patch_handle_t *handle)
9636{
9637 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009638
9639 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009640 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009641 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009642 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009643 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009644 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009645 }
9646
Eric Laurentd8365c52017-07-16 15:27:05 -07009647 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009648
9649 // store new source and send to effects
9650 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9651 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009652 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009653 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009654 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009655 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009656
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009657 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009658 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9659 status = hwDevice->createAudioPatch(patch->num_sources,
9660 patch->sources,
9661 patch->num_sinks,
9662 patch->sinks,
9663 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009664 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009665 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9666 patch->sinks[0].ext.mix.usecase.source,
9667 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009668 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009669 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009670
jiabinc52b1ff2019-10-31 17:20:42 -07009671 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009672 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009673 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009674 }
Eric Laurent296fb132015-05-01 11:38:42 -07009675
Andy Hungc2b11cb2020-04-22 09:04:01 -07009676 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009677 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009678 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009679 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009680 // also dispatch to active AudioRecords
9681 for (const auto &track : mActiveTracks) {
9682 track->logEndInterval();
9683 track->logBeginInterval(pathSourcesAsString);
9684 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009685 // Force meteadata update after a route change
9686 mActiveTracks.setHasChanged();
9687
Eric Laurent1c333e22014-05-20 10:48:17 -07009688 return status;
9689}
9690
Andy Hung4b17e882023-07-07 13:47:37 -07009691status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009692{
9693 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009694
jiabinc52b1ff2019-10-31 17:20:42 -07009695 mPatch = audio_patch{};
9696 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009697
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009698 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009699 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9700 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009701 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009702 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009703 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009704 // Force meteadata update after a route change
9705 mActiveTracks.setHasChanged();
9706
Eric Laurent1c333e22014-05-20 10:48:17 -07009707 return status;
9708}
9709
Andy Hung4b17e882023-07-07 13:47:37 -07009710void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009711{
wendy lin56aa82b2020-12-02 15:19:55 +08009712 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009713 mOutDevices = outDevices;
9714 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9715 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009716 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009717 }
9718}
9719
Andy Hung4b17e882023-07-07 13:47:37 -07009720int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009721{
9722 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009723 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009724 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009725 int32_t oldestFront = mRsmpInRear;
9726 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009727 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009728 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009729 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009730 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009731 if (filled > maxFilled) {
9732 oldestFront = front;
9733 maxFilled = filled;
9734 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009735 }
Andy Hung920f6572022-10-06 12:09:49 -07009736 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009737 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9738 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009739 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009740}
9741
Andy Hung4b17e882023-07-07 13:47:37 -07009742void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009743{
9744 if (offset == 0) {
9745 return;
9746 }
9747 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009748 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009749 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung11e74242023-06-26 19:20:57 -07009750 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009751 }
9752}
9753
Andy Hung4b17e882023-07-07 13:47:37 -07009754void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009755{
9756 // This is the formula for calculating the temporary buffer size.
9757 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9758 // 1 full output buffer, regardless of the alignment of the available input.
9759 // The value is somewhat arbitrary, and could probably be even larger.
9760 // A larger value should allow more old data to be read after a track calls start(),
9761 // without increasing latency.
9762 //
9763 // Note this is independent of the maximum downsampling ratio permitted for capture.
9764 size_t minRsmpInFrames = mFrameCount * 7;
9765
9766 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9767 // capture history available to another client using the same session ID:
9768 // dimension the resampler input buffer accordingly.
9769
9770 // Get oldest client read position: getOldestFront_l() must be called before altering
9771 // mRsmpInRear, or mRsmpInFrames
9772 int32_t previousFront = getOldestFront_l();
9773 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9774 int32_t previousRear = mRsmpInRear;
9775 mRsmpInRear = 0;
9776
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009777 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hung4b17e882023-07-07 13:47:37 -07009778 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009779 "resizeInputBuffer_l() called with invalid max shared history %d",
9780 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009781 if (maxSharedAudioHistoryMs != 0) {
9782 // resizeInputBuffer_l should never be called with a non zero shared history if the
9783 // buffer was not already allocated
9784 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9785 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9786 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9787 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009788 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009789 return;
9790 }
9791 mRsmpInFrames = rsmpInFrames;
9792 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009793 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009794 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9795 // initialized
9796 if (mRsmpInFrames < minRsmpInFrames) {
9797 mRsmpInFrames = minRsmpInFrames;
9798 }
9799 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9800
9801 // TODO optimize audio capture buffer sizes ...
9802 // Here we calculate the size of the sliding buffer used as a source
9803 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9804 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9805 // be better to have it derived from the pipe depth in the long term.
9806 // The current value is higher than necessary. However it should not add to latency.
9807
9808 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9809 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9810
9811 void *rsmpInBuffer;
9812 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9813 // if posix_memalign fails, will segv here.
9814 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9815
9816 // Copy audio history if any from old buffer before freeing it
9817 if (previousRear != 0) {
9818 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9819 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9820
9821 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9822 previousFront &= previousRsmpInFramesP2 - 1;
9823 size_t part1 = previousRsmpInFramesP2 - previousFront;
9824 if (part1 > (size_t) unread) {
9825 part1 = unread;
9826 }
9827 if (part1 != 0) {
9828 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9829 part1 * mFrameSize);
9830 mRsmpInRear = part1;
9831 part1 = unread - part1;
9832 if (part1 != 0) {
9833 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9834 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9835 mRsmpInRear += part1;
9836 }
9837 }
9838 // Update front for all clients according to new rear
9839 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9840 } else {
9841 mRsmpInRear = 0;
9842 }
9843 free(mRsmpInBuffer);
9844 mRsmpInBuffer = rsmpInBuffer;
9845}
9846
Andy Hung4b17e882023-07-07 13:47:37 -07009847void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009848{
9849 Mutex::Autolock _l(mLock);
9850 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009851 if (record->getSource()) {
9852 mSource = record->getSource();
9853 }
Eric Laurent83b88082014-06-20 18:31:16 -07009854}
9855
Andy Hung4b17e882023-07-07 13:47:37 -07009856void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009857{
9858 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009859 if (mSource == record->getSource()) {
9860 mSource = mInput;
9861 }
Eric Laurent83b88082014-06-20 18:31:16 -07009862 destroyTrack_l(record);
9863}
9864
Andy Hung4b17e882023-07-07 13:47:37 -07009865void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07009866{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009867 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009868 config->role = AUDIO_PORT_ROLE_SINK;
9869 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9870 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009871 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9872 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9873 config->flags.input = mInput->flags;
9874 }
Eric Laurent83b88082014-06-20 18:31:16 -07009875}
Eric Laurent1c333e22014-05-20 10:48:17 -07009876
Eric Laurent6acd1d42017-01-04 14:23:29 -08009877// ----------------------------------------------------------------------------
9878// Mmap
9879// ----------------------------------------------------------------------------
9880
Andy Hung765de282023-07-07 15:58:48 -07009881// Mmap stream control interface implementation. Each MmapThreadHandle controls one
9882// MmapPlaybackThread or MmapCaptureThread instance.
9883class MmapThreadHandle : public MmapStreamInterface {
9884public:
9885 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
9886 ~MmapThreadHandle() override;
9887
9888 // MmapStreamInterface virtuals
9889 status_t createMmapBuffer(int32_t minSizeFrames,
9890 struct audio_mmap_buffer_info* info) final;
9891 status_t getMmapPosition(struct audio_mmap_position* position) final;
9892 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
9893 status_t start(const AudioClient& client,
9894 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
9895 status_t stop(audio_port_handle_t handle) final;
9896 status_t standby() final;
9897 status_t reportData(const void* buffer, size_t frameCount) final;
9898private:
9899 const sp<IAfMmapThread> mThread;
9900};
9901
9902/* static */
9903sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
9904 const sp<IAfMmapThread>& mmapThread) {
9905 return sp<MmapThreadHandle>::make(mmapThread);
9906}
9907
9908MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009909 : mThread(thread)
9910{
Phil Burk9fabbf82017-08-03 12:02:00 -07009911 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009912}
9913
Andy Hung765de282023-07-07 15:58:48 -07009914// MmapStreamInterface could be directly implemented by MmapThread excepting this
9915// special handling on adapter dtor.
9916MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009917{
Phil Burk9fabbf82017-08-03 12:02:00 -07009918 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009919}
9920
Andy Hung765de282023-07-07 15:58:48 -07009921status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009922 struct audio_mmap_buffer_info *info)
9923{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009924 return mThread->createMmapBuffer(minSizeFrames, info);
9925}
9926
Andy Hung765de282023-07-07 15:58:48 -07009927status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009928{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009929 return mThread->getMmapPosition(position);
9930}
9931
Andy Hung765de282023-07-07 15:58:48 -07009932status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -07009933 int64_t *timeNanos) {
9934 return mThread->getExternalPosition(position, timeNanos);
9935}
9936
Andy Hung765de282023-07-07 15:58:48 -07009937status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009938 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009939{
jiabind1f1cb62020-03-24 11:57:57 -07009940 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009941}
9942
Andy Hung765de282023-07-07 15:58:48 -07009943status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009944{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009945 return mThread->stop(handle);
9946}
9947
Andy Hung765de282023-07-07 15:58:48 -07009948status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -08009949{
Eric Laurent18b57012017-02-13 16:23:52 -08009950 return mThread->standby();
9951}
9952
Andy Hung765de282023-07-07 15:58:48 -07009953status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
9954{
jiabinfc791ee2023-02-15 19:43:40 +00009955 return mThread->reportData(buffer, frameCount);
9956}
9957
Eric Laurent6acd1d42017-01-04 14:23:29 -08009958
Andy Hung4b17e882023-07-07 13:47:37 -07009959MmapThread::MmapThread(
Andy Hung7535ed92023-07-17 17:05:00 -07009960 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -07009961 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung7535ed92023-07-17 17:05:00 -07009962 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009963 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009964 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009965 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009966 mActiveTracks(&this->mLocalLog),
9967 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9968 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009969{
Eric Laurent18b57012017-02-13 16:23:52 -08009970 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009971 readHalParameters_l();
9972}
9973
Andy Hung4b17e882023-07-07 13:47:37 -07009974void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009975{
9976 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9977}
9978
Andy Hung4b17e882023-07-07 13:47:37 -07009979void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009980{
Andy Hung11e74242023-06-26 19:20:57 -07009981 ActiveTracks<IAfMmapTrack> activeTracks;
Eric Laurent331679c2018-04-16 17:03:16 -07009982 {
9983 Mutex::Autolock _l(mLock);
Andy Hung11e74242023-06-26 19:20:57 -07009984 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -07009985 activeTracks.add(t);
9986 }
9987 }
Andy Hung11e74242023-06-26 19:20:57 -07009988 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009989 stop(t->portId());
9990 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009991 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009992 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009993 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009994 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009995 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009996 }
9997}
9998
9999
Andy Hung4b17e882023-07-07 13:47:37 -070010000void MmapThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010001 audio_stream_type_t streamType __unused,
10002 audio_session_t sessionId,
10003 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010004 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010005 audio_port_handle_t portId)
10006{
10007 mAttr = *attr;
10008 mSessionId = sessionId;
10009 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010010 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010011 mPortId = portId;
10012}
10013
Andy Hung4b17e882023-07-07 13:47:37 -070010014status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010015 struct audio_mmap_buffer_info *info)
10016{
10017 if (mHalStream == 0) {
10018 return NO_INIT;
10019 }
Eric Laurent18b57012017-02-13 16:23:52 -080010020 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010021 return mHalStream->createMmapBuffer(minSizeFrames, info);
10022}
10023
Andy Hung4b17e882023-07-07 13:47:37 -070010024status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010025{
10026 if (mHalStream == 0) {
10027 return NO_INIT;
10028 }
10029 return mHalStream->getMmapPosition(position);
10030}
10031
Andy Hung4b17e882023-07-07 13:47:37 -070010032status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010033{
Eric Laurentdda206a2022-07-08 17:28:35 +020010034 // The HAL must receive track metadata before starting the stream
10035 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010036 status_t ret = mHalStream->start();
10037 if (ret != NO_ERROR) {
10038 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10039 return ret;
10040 }
Andy Hungcf10d742020-04-28 15:38:24 -070010041 if (mStandby) {
10042 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010043 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010044 mStandby = false;
10045 }
Eric Laurent331679c2018-04-16 17:03:16 -070010046 return NO_ERROR;
10047}
10048
Andy Hung4b17e882023-07-07 13:47:37 -070010049status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010050 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010051 audio_port_handle_t *handle)
10052{
Eric Laurenta54f1282017-07-01 19:39:32 -070010053 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010054 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010055 if (mHalStream == 0) {
10056 return NO_INIT;
10057 }
10058
10059 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010060
Eric Laurentdda206a2022-07-08 17:28:35 +020010061 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010062 if (*handle == mPortId) {
Eric Laurentdda206a2022-07-08 17:28:35 +020010063 acquireWakeLock();
10064 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010065 }
10066
10067 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10068
10069 audio_io_handle_t io = mId;
Andy Hungc3af0112023-07-19 16:56:19 -070010070 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010071 client.attributionSource);
10072
Eric Laurenta54f1282017-07-01 19:39:32 -070010073 if (isOutput()) {
10074 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10075 config.sample_rate = mSampleRate;
10076 config.channel_mask = mChannelMask;
10077 config.format = mFormat;
10078 audio_stream_type_t stream = streamType();
10079 audio_output_flags_t flags =
10080 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010081 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010082 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010083 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010084 bool isBitPerfect;
Eric Laurenta54f1282017-07-01 19:39:32 -070010085 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
10086 mSessionId,
10087 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010088 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010089 &config,
10090 flags,
10091 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010092 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010093 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010094 &isSpatialized,
10095 &isBitPerfect);
Kevin Rocard153f92d2018-12-18 18:33:28 -080010096 ALOGD_IF(!secondaryOutputs.empty(),
10097 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010098 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010099 audio_config_base_t config;
10100 config.sample_rate = mSampleRate;
10101 config.channel_mask = mChannelMask;
10102 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010103 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -070010104 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010105 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -070010106 mSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010107 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010108 &config,
10109 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10110 &deviceId,
10111 &portId);
10112 }
10113 // APM should not chose a different input or output stream for the same set of attributes
10114 // and audo configuration
10115 if (ret != NO_ERROR || io != mId) {
10116 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10117 __FUNCTION__, ret, io, mId);
10118 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010119 }
10120
10121 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010122 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010123 } else {
jiabin09609032022-06-15 19:26:01 +000010124 {
10125 // Add the track record before starting input so that the silent status for the
10126 // client can be cached.
10127 Mutex::Autolock _l(mLock);
10128 setClientSilencedState_l(portId, false /*silenced*/);
10129 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010130 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010131 }
10132
Eric Laurent331679c2018-04-16 17:03:16 -070010133 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010134 // abort if start is rejected by audio policy manager
10135 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010136 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010137 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -070010138 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010139 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010140 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010141 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010142 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010143 }
Eric Laurent331679c2018-04-16 17:03:16 -070010144 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010145 } else {
10146 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010147 }
jiabin09609032022-06-15 19:26:01 +000010148 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010149 return PERMISSION_DENIED;
10150 }
10151
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010152 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung11e74242023-06-26 19:20:57 -070010153 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10154 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010155 mChannelMask, mSessionId, isOutput(),
10156 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010157 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010158 if (!isOutput()) {
10159 track->setSilenced_l(isClientSilenced_l(portId));
10160 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010161
Eric Laurent4eb58f12018-12-07 16:41:02 -080010162 if (isOutput()) {
10163 // force volume update when a new track is added
10164 mHalVolFloat = -1.0f;
10165 } else if (!track->isSilenced_l()) {
Andy Hung11e74242023-06-26 19:20:57 -070010166 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010167 if (t->isSilenced_l()
10168 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010169 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010170 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010171 }
10172 }
10173
Eric Laurent6acd1d42017-01-04 14:23:29 -080010174 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010175 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010176 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +020010177 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010178 chain->incTrackCnt();
10179 chain->incActiveTrackCnt();
10180 }
10181
Andy Hungc2b11cb2020-04-22 09:04:01 -070010182 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010183 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010184
10185 if (mActiveTracks.size() == 1) {
10186 ret = exitStandby_l();
10187 }
10188
Eric Laurent6acd1d42017-01-04 14:23:29 -080010189 broadcast_l();
10190
Eric Laurentdda206a2022-07-08 17:28:35 +020010191 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010192
Eric Laurentdda206a2022-07-08 17:28:35 +020010193 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010194}
10195
Andy Hung4b17e882023-07-07 13:47:37 -070010196status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010197{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010198 ALOGV("%s handle %d", __FUNCTION__, handle);
10199
10200 if (mHalStream == 0) {
10201 return NO_INIT;
10202 }
10203
Eric Laurenta54f1282017-07-01 19:39:32 -070010204 if (handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +000010205 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -070010206 return NO_ERROR;
10207 }
10208
Eric Laurent331679c2018-04-16 17:03:16 -070010209 Mutex::Autolock _l(mLock);
10210
Andy Hung11e74242023-06-26 19:20:57 -070010211 sp<IAfMmapTrack> track;
10212 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010213 if (handle == t->portId()) {
10214 track = t;
10215 break;
10216 }
10217 }
10218 if (track == 0) {
10219 return BAD_VALUE;
10220 }
10221
10222 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010223 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010224
Eric Laurent331679c2018-04-16 17:03:16 -070010225 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010226 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010227 AudioSystem::stopOutput(track->portId());
10228 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010229 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010230 AudioSystem::stopInput(track->portId());
10231 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010232 }
Eric Laurent331679c2018-04-16 17:03:16 -070010233 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010234
Andy Hung116bc262023-06-20 18:56:17 -070010235 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010236 if (chain != 0) {
10237 chain->decActiveTrackCnt();
10238 chain->decTrackCnt();
10239 }
10240
Eric Laurentdda206a2022-07-08 17:28:35 +020010241 if (mActiveTracks.isEmpty()) {
10242 mHalStream->stop();
10243 }
10244
Eric Laurent6acd1d42017-01-04 14:23:29 -080010245 broadcast_l();
10246
Eric Laurent6acd1d42017-01-04 14:23:29 -080010247 return NO_ERROR;
10248}
10249
Andy Hung4b17e882023-07-07 13:47:37 -070010250status_t MmapThread::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010251{
10252 ALOGV("%s", __FUNCTION__);
10253
10254 if (mHalStream == 0) {
10255 return NO_INIT;
10256 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010257 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010258 return INVALID_OPERATION;
10259 }
10260 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010261 if (!mStandby) {
10262 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010263 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010264 mStandby = true;
10265 }
Eric Laurent18b57012017-02-13 16:23:52 -080010266 releaseWakeLock();
10267 return NO_ERROR;
10268}
10269
Andy Hung4b17e882023-07-07 13:47:37 -070010270status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010271 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10272 return INVALID_OPERATION;
10273}
10274
Andy Hung4b17e882023-07-07 13:47:37 -070010275void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010276{
10277 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10278 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10279 mFormat = mHALFormat;
10280 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10281 result = mHalStream->getFrameSize(&mFrameSize);
10282 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010283 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10284 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010285 result = mHalStream->getBufferSize(&mBufferSize);
10286 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10287 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010288
Andy Hungcf10d742020-04-28 15:38:24 -070010289 // TODO: make a readHalParameters call?
10290 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010291 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
10292 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
10293 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10294 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10295 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10296 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10297 /*
10298 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10299 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10300 (int32_t)mHapticChannelMask)
10301 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10302 (int32_t)mHapticChannelCount)
10303 */
10304 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
10305 formatToString(mHALFormat).c_str())
10306 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10307 (int32_t)mFrameCount) // sic - added HAL
10308 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010309}
10310
Andy Hung4b17e882023-07-07 13:47:37 -070010311bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010312{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010313 checkSilentMode_l();
10314
10315 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10316
10317 while (!exitPending())
10318 {
Andy Hung116bc262023-06-20 18:56:17 -070010319 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010320
Andy Hung13850be2019-03-14 11:33:09 -070010321 { // under Thread lock
10322 Mutex::Autolock _l(mLock);
10323
Eric Laurent6acd1d42017-01-04 14:23:29 -080010324 if (mSignalPending) {
10325 // A signal was raised while we were unlocked
10326 mSignalPending = false;
10327 } else {
10328 if (mConfigEvents.isEmpty()) {
10329 // we're about to wait, flush the binder command buffer
10330 IPCThreadState::self()->flushCommands();
10331
10332 if (exitPending()) {
10333 break;
10334 }
10335
Eric Laurent6acd1d42017-01-04 14:23:29 -080010336 // wait until we have something to do...
10337 ALOGV("%s going to sleep", myName.string());
10338 mWaitWorkCV.wait(mLock);
10339 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010340
10341 checkSilentMode_l();
10342
10343 continue;
10344 }
10345 }
10346
10347 processConfigEvents_l();
10348
10349 processVolume_l();
10350
10351 checkInvalidTracks_l();
10352
10353 mActiveTracks.updatePowerState(this);
10354
Kevin Rocard069c2712018-03-29 19:09:14 -070010355 updateMetadata_l();
10356
Eric Laurent6acd1d42017-01-04 14:23:29 -080010357 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010358 } // release Thread lock
10359
Eric Laurent6acd1d42017-01-04 14:23:29 -080010360 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010361 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010362 }
Andy Hung13850be2019-03-14 11:33:09 -070010363
10364 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010365 unlockEffectChains(effectChains);
10366 // Effect chains will be actually deleted here if they were removed from
10367 // mEffectChains list during mixing or effects processing
10368 }
10369
10370 threadLoop_exit();
10371
10372 if (!mStandby) {
10373 threadLoop_standby();
10374 mStandby = true;
10375 }
10376
Eric Laurent6acd1d42017-01-04 14:23:29 -080010377 ALOGV("Thread %p type %d exiting", this, mType);
10378 return false;
10379}
10380
10381// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -070010382bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010383 status_t& status)
10384{
10385 AudioParameter param = AudioParameter(keyValuePair);
10386 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010387 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010388 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010389 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010390 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010391 if (sendToHal) {
10392 status = mHalStream->setParameters(keyValuePair);
10393 } else {
10394 status = NO_ERROR;
10395 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010396
10397 return false;
10398}
10399
Andy Hung4b17e882023-07-07 13:47:37 -070010400String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010401{
10402 Mutex::Autolock _l(mLock);
10403 String8 out_s8;
10404 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10405 return out_s8;
10406 }
Andy Hung920f6572022-10-06 12:09:49 -070010407 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010408}
10409
Andy Hung4b17e882023-07-07 13:47:37 -070010410void MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010411 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010412 sp<AudioIoDescriptor> desc;
10413 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010414 switch (event) {
10415 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010416 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010417 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010418 isInput = true;
10419 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010420 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010421 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010422 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010423 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10424 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010425 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010426 case AUDIO_INPUT_CLOSED:
10427 case AUDIO_OUTPUT_CLOSED:
10428 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010429 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010430 break;
10431 }
Andy Hung7535ed92023-07-17 17:05:00 -070010432 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010433}
10434
Andy Hung4b17e882023-07-07 13:47:37 -070010435status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010436 audio_patch_handle_t *handle)
Andy Hung920f6572022-10-06 12:09:49 -070010437NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010438{
10439 status_t status = NO_ERROR;
10440
10441 // store new device and send to effects
10442 audio_devices_t type = AUDIO_DEVICE_NONE;
10443 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010444 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10445 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10446 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010447 if (isOutput()) {
10448 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010449 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10450 && !mAudioHwDev->supportsAudioPatches(),
10451 "Enumerated device type(%#x) must not be used "
10452 "as it does not support audio patches",
10453 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010454 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010455 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10456 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010457 }
10458 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010459 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010460 } else {
10461 type = patch->sources[0].ext.device.type;
10462 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010463 numDevices = mPatch.num_sources;
10464 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010465 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010466 }
10467
10468 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010469 if (isOutput()) {
10470 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10471 } else {
10472 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10473 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010474 }
10475
jiabinc52b1ff2019-10-31 17:20:42 -070010476 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010477 // store new source and send to effects
10478 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10479 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10480 for (size_t i = 0; i < mEffectChains.size(); i++) {
10481 mEffectChains[i]->setAudioSource_l(mAudioSource);
10482 }
10483 }
10484 }
10485
10486 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010487 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10488 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010489 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010490 audio_port_config port;
10491 std::optional<audio_source_t> source;
10492 if (isOutput()) {
10493 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010494 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010495 port = patch->sources[0];
10496 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010497 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010498 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010499 *handle = AUDIO_PATCH_HANDLE_NONE;
10500 }
10501
jiabinc52b1ff2019-10-31 17:20:42 -070010502 if (numDevices == 0 || mDeviceId != deviceId) {
10503 if (isOutput()) {
10504 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10505 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010506 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010507 } else {
10508 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10509 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10510 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010511 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010512 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010513 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010514 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -070010515 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010516 }
jiabinc52b1ff2019-10-31 17:20:42 -070010517 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010518 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010519 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010520 // Force meteadata update after a route change
10521 mActiveTracks.setHasChanged();
10522
Eric Laurent6acd1d42017-01-04 14:23:29 -080010523 return status;
10524}
10525
Andy Hung4b17e882023-07-07 13:47:37 -070010526status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010527{
10528 status_t status = NO_ERROR;
10529
jiabinc52b1ff2019-10-31 17:20:42 -070010530 mPatch = audio_patch{};
10531 mOutDeviceTypeAddrs.clear();
10532 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010533
10534 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10535 supportsAudioPatches : false;
10536
10537 if (supportsAudioPatches) {
10538 status = mHalDevice->releaseAudioPatch(handle);
10539 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010540 status = mHalStream->legacyReleaseAudioPatch();
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 Hung4b17e882023-07-07 13:47:37 -070010548void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010549{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010550 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010551 if (isOutput()) {
10552 config->role = AUDIO_PORT_ROLE_SOURCE;
10553 config->ext.mix.hw_module = mAudioHwDev->handle();
10554 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10555 } else {
10556 config->role = AUDIO_PORT_ROLE_SINK;
10557 config->ext.mix.hw_module = mAudioHwDev->handle();
10558 config->ext.mix.usecase.source = mAudioSource;
10559 }
10560}
10561
Andy Hung4b17e882023-07-07 13:47:37 -070010562status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010563{
10564 audio_session_t session = chain->sessionId();
10565
10566 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10567 // Attach all tracks with same session ID to this chain.
10568 // indicate all active tracks in the chain
Andy Hung11e74242023-06-26 19:20:57 -070010569 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010570 if (session == track->sessionId()) {
10571 chain->incTrackCnt();
10572 chain->incActiveTrackCnt();
10573 }
10574 }
10575
10576 chain->setThread(this);
10577 chain->setInBuffer(nullptr);
10578 chain->setOutBuffer(nullptr);
10579 chain->syncHalEffectsState();
10580
10581 mEffectChains.add(chain);
10582 checkSuspendOnAddEffectChain_l(chain);
10583 return NO_ERROR;
10584}
10585
Andy Hung4b17e882023-07-07 13:47:37 -070010586size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010587{
10588 audio_session_t session = chain->sessionId();
10589
10590 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10591
10592 for (size_t i = 0; i < mEffectChains.size(); i++) {
10593 if (chain == mEffectChains[i]) {
10594 mEffectChains.removeAt(i);
10595 // detach all active tracks from the chain
10596 // detach all tracks with same session ID from this chain
Andy Hung11e74242023-06-26 19:20:57 -070010597 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010598 if (session == track->sessionId()) {
10599 chain->decActiveTrackCnt();
10600 chain->decTrackCnt();
10601 }
10602 }
10603 break;
10604 }
10605 }
10606 return mEffectChains.size();
10607}
10608
Andy Hung4b17e882023-07-07 13:47:37 -070010609void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010610{
10611 mHalStream->standby();
10612}
10613
Andy Hung4b17e882023-07-07 13:47:37 -070010614void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010615{
Phil Burk7dce7282017-09-27 13:51:41 -070010616 // Do not call callback->onTearDown() because it is redundant for thread exit
10617 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010618}
10619
Andy Hung4b17e882023-07-07 13:47:37 -070010620status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010621{
10622 return BAD_VALUE;
10623}
10624
Andy Hung4b17e882023-07-07 13:47:37 -070010625bool MmapThread::isValidSyncEvent(
10626 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010627{
10628 return false;
10629}
10630
Andy Hung4b17e882023-07-07 13:47:37 -070010631status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010632 const effect_descriptor_t *desc, audio_session_t sessionId)
10633{
10634 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010635 if (audio_is_global_session(sessionId)) {
10636 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010637 desc->name, mThreadName);
10638 return BAD_VALUE;
10639 }
10640
10641 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10642 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10643 desc->name);
10644 return BAD_VALUE;
10645 }
10646 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010647 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10648 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010649 return BAD_VALUE;
10650 }
10651
10652 // Only allow effects without processing load or latency
10653 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10654 return BAD_VALUE;
10655 }
10656
Andy Hung116bc262023-06-20 18:56:17 -070010657 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010658 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10659 return BAD_VALUE;
10660 }
10661
Eric Laurent6acd1d42017-01-04 14:23:29 -080010662 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010663}
10664
Andy Hung4b17e882023-07-07 13:47:37 -070010665void MmapThread::checkInvalidTracks_l()
Andy Hung920f6572022-10-06 12:09:49 -070010666NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010667{
Eric Laurent039c24a2022-10-07 14:01:59 +020010668 sp<MmapStreamCallback> callback;
Andy Hung11e74242023-06-26 19:20:57 -070010669 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010670 if (track->isInvalid()) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010671 callback = mCallback.promote();
10672 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10673 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10674 mNoCallbackWarningCount++;
10675 }
10676 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010677 }
10678 }
Eric Laurent039c24a2022-10-07 14:01:59 +020010679 if (callback != 0) {
10680 mLock.unlock();
10681 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10682 mLock.lock();
jiabindfa32482022-10-06 19:45:50 +000010683 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010684}
10685
Andy Hung4b17e882023-07-07 13:47:37 -070010686void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010687{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010688 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10689 mAttr.content_type, mAttr.usage, mAttr.source);
10690 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010691 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010692 dprintf(fd, " No active clients\n");
10693 }
10694}
10695
Andy Hung4b17e882023-07-07 13:47:37 -070010696void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010697{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010698 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010699 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010700 dprintf(fd, " %zu Tracks\n", numtracks);
10701 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010702 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010703 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010704 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010705 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -070010706 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010707 result.append(prefix);
10708 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010709 }
10710 } else {
10711 dprintf(fd, "\n");
10712 }
10713 write(fd, result.string(), result.size());
10714}
10715
Andy Hung4b17e882023-07-07 13:47:37 -070010716/* static */
10717sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -070010718 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung4b17e882023-07-07 13:47:37 -070010719 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070010720 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070010721}
10722
10723MmapPlaybackThread::MmapPlaybackThread(
Andy Hung7535ed92023-07-17 17:05:00 -070010724 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010725 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070010726 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010727 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010728 mStreamVolume(1.0),
10729 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010730 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010731{
10732 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10733 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung7535ed92023-07-17 17:05:00 -070010734 mMasterVolume = afThreadCallback->masterVolume_l();
10735 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010736 if (mAudioHwDev) {
10737 if (mAudioHwDev->canSetMasterVolume()) {
10738 mMasterVolume = 1.0;
10739 }
10740
10741 if (mAudioHwDev->canSetMasterMute()) {
10742 mMasterMute = false;
10743 }
10744 }
10745}
10746
Andy Hung4b17e882023-07-07 13:47:37 -070010747void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010748 audio_stream_type_t streamType,
10749 audio_session_t sessionId,
10750 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010751 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010752 audio_port_handle_t portId)
10753{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010754 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010755 mStreamType = streamType;
10756}
10757
Andy Hung4b17e882023-07-07 13:47:37 -070010758AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010759{
10760 Mutex::Autolock _l(mLock);
10761 AudioStreamOut *output = mOutput;
10762 mOutput = NULL;
10763 return output;
10764}
10765
Andy Hung4b17e882023-07-07 13:47:37 -070010766void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010767{
10768 Mutex::Autolock _l(mLock);
10769 // Don't apply master volume in SW if our HAL can do it for us.
10770 if (mAudioHwDev &&
10771 mAudioHwDev->canSetMasterVolume()) {
10772 mMasterVolume = 1.0;
10773 } else {
10774 mMasterVolume = value;
10775 }
10776}
10777
Andy Hung4b17e882023-07-07 13:47:37 -070010778void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010779{
10780 Mutex::Autolock _l(mLock);
10781 // Don't apply master mute in SW if our HAL can do it for us.
10782 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10783 mMasterMute = false;
10784 } else {
10785 mMasterMute = muted;
10786 }
10787}
10788
Andy Hung4b17e882023-07-07 13:47:37 -070010789void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010790{
10791 Mutex::Autolock _l(mLock);
10792 if (stream == mStreamType) {
10793 mStreamVolume = value;
10794 broadcast_l();
10795 }
10796}
10797
Andy Hung4b17e882023-07-07 13:47:37 -070010798float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010799{
10800 Mutex::Autolock _l(mLock);
10801 if (stream == mStreamType) {
10802 return mStreamVolume;
10803 }
10804 return 0.0f;
10805}
10806
Andy Hung4b17e882023-07-07 13:47:37 -070010807void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010808{
10809 Mutex::Autolock _l(mLock);
10810 if (stream == mStreamType) {
10811 mStreamMute= muted;
10812 broadcast_l();
10813 }
10814}
10815
Andy Hung4b17e882023-07-07 13:47:37 -070010816void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010817{
10818 Mutex::Autolock _l(mLock);
10819 if (streamType == mStreamType) {
Andy Hung11e74242023-06-26 19:20:57 -070010820 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010821 track->invalidate();
10822 }
10823 broadcast_l();
10824 }
10825}
10826
Andy Hung4b17e882023-07-07 13:47:37 -070010827void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010828{
10829 Mutex::Autolock _l(mLock);
10830 bool trackMatch = false;
Andy Hung11e74242023-06-26 19:20:57 -070010831 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010832 if (portIds.find(track->portId()) != portIds.end()) {
10833 track->invalidate();
10834 trackMatch = true;
10835 portIds.erase(track->portId());
10836 }
10837 if (portIds.empty()) {
10838 break;
10839 }
10840 }
10841 if (trackMatch) {
10842 broadcast_l();
10843 }
10844}
10845
Andy Hung4b17e882023-07-07 13:47:37 -070010846void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070010847NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080010848{
10849 float volume;
10850
10851 if (mMasterMute || mStreamMute) {
10852 volume = 0;
10853 } else {
10854 volume = mMasterVolume * mStreamVolume;
10855 }
10856
10857 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010858
10859 // Convert volumes from float to 8.24
10860 uint32_t vol = (uint32_t)(volume * (1 << 24));
10861
10862 // Delegate volume control to effect in track effect chain if needed
10863 // only one effect chain can be present on DirectOutputThread, so if
10864 // there is one, the track is connected to it
10865 if (!mEffectChains.isEmpty()) {
10866 mEffectChains[0]->setVolume_l(&vol, &vol);
10867 volume = (float)vol / (1 << 24);
10868 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010869 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010870 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10871 mHalVolFloat = volume; // HW volume control worked, so update value.
10872 mNoCallbackWarningCount = 0;
10873 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010874 sp<MmapStreamCallback> callback = mCallback.promote();
10875 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010876 mHalVolFloat = volume; // SW volume control worked, so update value.
10877 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010878 mLock.unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010879 callback->onVolumeChanged(volume);
Eric Laurent734046e2018-04-16 14:50:52 -070010880 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010881 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010882 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10883 ALOGW("Could not set MMAP stream volume: no volume callback!");
10884 mNoCallbackWarningCount++;
10885 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010886 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010887 }
Andy Hung11e74242023-06-26 19:20:57 -070010888 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010889 track->setMetadataHasChanged();
Andy Hung7535ed92023-07-17 17:05:00 -070010890 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010891 /*muteState=*/{mMasterMute,
10892 mStreamVolume == 0.f,
10893 mStreamMute,
10894 // TODO(b/241533526): adjust logic to include mute from AppOps
10895 false /*muteFromPlaybackRestricted*/,
10896 false /*muteFromClientVolume*/,
10897 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010898 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010899 }
10900}
10901
Andy Hung4b17e882023-07-07 13:47:37 -070010902ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070010903{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010904 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010010905 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010906 }
10907 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung11e74242023-06-26 19:20:57 -070010908 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070010909 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010910 playback_track_metadata_v7_t trackMetadata;
10911 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010912 .usage = track->attributes().usage,
10913 .content_type = track->attributes().content_type,
10914 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010915 };
10916 trackMetadata.channel_mask = track->channelMask(),
10917 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10918 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010919 }
10920 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010010921
10922 MetadataUpdate change;
10923 change.playbackMetadataUpdate = metadata.tracks;
10924 return change;
10925};
Kevin Rocard069c2712018-03-29 19:09:14 -070010926
Andy Hung4b17e882023-07-07 13:47:37 -070010927void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010928{
10929 if (!mMasterMute) {
10930 char value[PROPERTY_VALUE_MAX];
10931 if (property_get("ro.audio.silent", value, "0") > 0) {
10932 char *endptr;
10933 unsigned long ul = strtoul(value, &endptr, 0);
10934 if (*endptr == '\0' && ul != 0) {
10935 ALOGD("Silence is golden");
10936 // The setprop command will not allow a property to be changed after
10937 // the first time it is set, so we don't have to worry about un-muting.
10938 setMasterMute_l(true);
10939 }
10940 }
10941 }
10942}
10943
Andy Hung4b17e882023-07-07 13:47:37 -070010944void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010945{
10946 MmapThread::toAudioPortConfig(config);
10947 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10948 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10949 config->flags.output = mOutput->flags;
10950 }
10951}
10952
Andy Hung4b17e882023-07-07 13:47:37 -070010953status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung3e4c8742023-06-29 21:19:25 -070010954 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070010955{
10956 if (mOutput == nullptr) {
10957 return NO_INIT;
10958 }
10959 struct timespec timestamp;
10960 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10961 if (status == NO_ERROR) {
10962 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10963 }
10964 return status;
10965}
10966
Andy Hung4b17e882023-07-07 13:47:37 -070010967status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010968 // Send to MelProcessor for sound dose measurement.
10969 auto processor = mMelProcessor.load();
10970 if (processor) {
10971 processor->process(buffer, frameCount * mFrameSize);
10972 }
10973
jiabinfc791ee2023-02-15 19:43:40 +000010974 return NO_ERROR;
10975}
10976
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010977// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -070010978void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010979 const sp<audio_utils::MelProcessor>& processor)
10980{
10981 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010982 mMelProcessor.store(processor);
10983 if (processor) {
10984 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010985 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010986
10987 // no need to update output format for MMapPlaybackThread since it is
10988 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010989}
10990
10991// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -070010992void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010993{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010994 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
10995 auto melProcessor = mMelProcessor.load();
10996 if (melProcessor != nullptr) {
10997 melProcessor->pause();
10998 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010999}
11000
Andy Hung4b17e882023-07-07 13:47:37 -070011001void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011002{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011003 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011004
Glenn Kastend3bb6452016-12-05 18:14:37 -080011005 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
11006 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011007 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11008}
11009
Andy Hung4b17e882023-07-07 13:47:37 -070011010/* static */
11011sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -070011012 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung4b17e882023-07-07 13:47:37 -070011013 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070011014 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070011015}
11016
11017MmapCaptureThread::MmapCaptureThread(
Andy Hung7535ed92023-07-17 17:05:00 -070011018 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011019 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070011020 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011021 mInput(input)
11022{
11023 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11024 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11025}
11026
Andy Hung4b17e882023-07-07 13:47:37 -070011027status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011028{
Phil Burkf054fc32018-12-06 09:45:59 -080011029 {
11030 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011031 if (mInput != nullptr && mInput->stream != nullptr) {
11032 mInput->stream->setGain(1.0f);
11033 }
11034 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011035 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011036}
11037
Andy Hung4b17e882023-07-07 13:47:37 -070011038AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011039{
11040 Mutex::Autolock _l(mLock);
11041 AudioStreamIn *input = mInput;
11042 mInput = NULL;
11043 return input;
11044}
Kevin Rocard069c2712018-03-29 19:09:14 -070011045
Andy Hung4b17e882023-07-07 13:47:37 -070011046void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011047{
11048 bool changed = false;
11049 bool silenced = false;
11050
11051 sp<MmapStreamCallback> callback = mCallback.promote();
11052 if (callback == 0) {
11053 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11054 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11055 mNoCallbackWarningCount++;
11056 }
11057 }
11058
11059 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11060 // track is silenced and unmute otherwise
11061 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11062 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11063 changed = true;
11064 silenced = mActiveTracks[i]->isSilenced_l();
11065 }
11066 }
11067
11068 if (changed) {
11069 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11070 }
11071}
11072
Andy Hung4b17e882023-07-07 13:47:37 -070011073ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011074{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011075 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011076 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011077 }
11078 StreamInHalInterface::SinkMetadata metadata;
Andy Hung11e74242023-06-26 19:20:57 -070011079 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011080 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011081 record_track_metadata_v7_t trackMetadata;
11082 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011083 .source = track->attributes().source,
11084 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011085 };
11086 trackMetadata.channel_mask = track->channelMask(),
11087 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11088 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011089 }
11090 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011091 MetadataUpdate change;
11092 change.recordMetadataUpdate = metadata.tracks;
11093 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011094}
11095
Andy Hung4b17e882023-07-07 13:47:37 -070011096void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011097{
11098 Mutex::Autolock _l(mLock);
11099 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011100 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011101 mActiveTracks[i]->setSilenced_l(silenced);
11102 broadcast_l();
11103 }
11104 }
jiabin09609032022-06-15 19:26:01 +000011105 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011106}
11107
Andy Hung4b17e882023-07-07 13:47:37 -070011108void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011109{
11110 MmapThread::toAudioPortConfig(config);
11111 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11112 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11113 config->flags.input = mInput->flags;
11114 }
11115}
11116
Andy Hung4b17e882023-07-07 13:47:37 -070011117status_t MmapCaptureThread::getExternalPosition(
Andy Hung3e4c8742023-06-29 21:19:25 -070011118 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011119{
11120 if (mInput == nullptr) {
11121 return NO_INIT;
11122 }
11123 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11124}
11125
jiabinc658e452022-10-21 20:52:21 +000011126// ----------------------------------------------------------------------------
11127
Andy Hung4b17e882023-07-07 13:47:37 -070011128/* static */
11129sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung7535ed92023-07-17 17:05:00 -070011130 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -070011131 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070011132 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070011133}
11134
Andy Hung7535ed92023-07-17 17:05:00 -070011135BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011136 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070011137 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011138
Andy Hung4b17e882023-07-07 13:47:37 -070011139PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -070011140 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011141 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11142 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011143 float volumeLeft = 1.0f;
11144 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011145 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11146 const int trackId = mActiveTracks[0]->id();
11147 mAudioMixer->setParameter(
11148 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11149 mAudioMixer->setParameter(
11150 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11151 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011152 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011153 mIsBitPerfect = true;
11154 } else {
11155 mIsBitPerfect = false;
11156 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11157 // active.
11158 for (const auto& track : mActiveTracks) {
11159 const int trackId = track->id();
11160 mAudioMixer->setParameter(
11161 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11162 }
11163 }
jiabin76d94692022-12-15 21:51:21 +000011164 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11165 mVolumeLeft = volumeLeft;
11166 mVolumeRight = volumeRight;
11167 setVolumeForOutput_l(volumeLeft, volumeRight);
11168 }
jiabinc658e452022-10-21 20:52:21 +000011169 return result;
11170}
11171
Andy Hung4b17e882023-07-07 13:47:37 -070011172void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011173 MixerThread::threadLoop_mix();
11174 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11175}
11176
Glenn Kasten63238ef2015-03-02 15:50:29 -080011177} // namespace android