blob: 37b8fe8be93340c544909b4e8c4c5e23dff90953 [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"
20//#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>
jiabinc52b1ff2019-10-31 17:20:42 -070034#include <media/AudioContainers.h>
35#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070036#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070037#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080038#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070039#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080041#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070044#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010045#include <audio_utils/Balance.h>
jiabinf6eb4c32020-02-25 14:06:25 -080046#include <audio_utils/Metadata.h>
jiabin245cdd92018-12-07 17:55:15 -080047#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080048#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080049#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080050#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070051#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070052#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070053#include <system/audio_effects/effect_aec.h>
Eric Laurentb3f315a2021-07-13 15:09:05 +020054#include <system/audio_effects/effect_downmix.h>
55#include <system/audio_effects/effect_ns.h>
Eric Laurent1c5e2e32021-08-18 18:50:28 +020056#include <system/audio_effects/effect_spatializer.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070057#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080058
59// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080061#include <media/nbaio/AudioStreamOutSink.h>
62#include <media/nbaio/MonoPipe.h>
63#include <media/nbaio/MonoPipeReader.h>
64#include <media/nbaio/Pipe.h>
65#include <media/nbaio/PipeReader.h>
66#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080067#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070068#include <mediautils/Process.h>
Eric Laurent81784c32012-11-19 14:55:58 -080069
Mikhail Naganov2996f672019-04-18 12:29:59 -070070#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080071#include <powermanager/PowerManager.h>
72
Kevin Rocard7588ff42018-01-08 11:11:30 -080073#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070074#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080075
Eric Laurent81784c32012-11-19 14:55:58 -080076#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080077#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070078#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070079#include <mediautils/SchedulingPolicyService.h>
80#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080081
Eric Laurent81784c32012-11-19 14:55:58 -080082#ifdef ADD_BATTERY_DATA
83#include <media/IMediaPlayerService.h>
84#include <media/IMediaDeathNotifier.h>
85#endif
86
Eric Laurent81784c32012-11-19 14:55:58 -080087#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070088#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080089#include <cpustats/ThreadCpuUsage.h>
90#endif
91
Glenn Kastenc05b8d72016-03-24 09:48:17 -070092#include "AutoPark.h"
93
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080094#include <pthread.h>
95#include "TypedLogger.h"
96
Eric Laurent81784c32012-11-19 14:55:58 -080097// ----------------------------------------------------------------------------
98
99// Note: the following macro is used for extremely verbose logging message. In
100// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
101// 0; but one side effect of this is to turn all LOGV's as well. Some messages
102// are so verbose that we want to suppress them even when we have ALOG_ASSERT
103// turned on. Do not uncomment the #def below unless you really know what you
104// are doing and want to see all of the extremely verbose messages.
105//#define VERY_VERY_VERBOSE_LOGGING
106#ifdef VERY_VERY_VERBOSE_LOGGING
107#define ALOGVV ALOGV
108#else
109#define ALOGVV(a...) do { } while(0)
110#endif
111
Andy Hung6770c6f2015-04-07 13:43:36 -0700112// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700113#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700114
Andy Hung6770c6f2015-04-07 13:43:36 -0700115template <typename T>
116static inline T min(const T& a, const T& b)
117{
118 return a < b ? a : b;
119}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700120
Eric Laurent81784c32012-11-19 14:55:58 -0800121namespace android {
122
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700123using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000124using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700125
Eric Laurent81784c32012-11-19 14:55:58 -0800126// retry counts for buffer fill timeout
127// 50 * ~20msecs = 1 second
128static const int8_t kMaxTrackRetries = 50;
129static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700130
Eric Laurent81784c32012-11-19 14:55:58 -0800131// allow less retry attempts on direct output thread.
132// direct outputs can be a scarce resource in audio hardware and should
133// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700134// Notes:
135// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
136// in case the data write is bursty for the AudioTrack. The application
137// should endeavor to write at least once every kMaxTrackRetriesDirectMs
138// to prevent an underrun situation. If the data is bursty, then
139// the application can also throttle the data sent to be even.
140// 2) For compressed audio data, any data present in the AudioTrack buffer
141// will be sent and reset the retry count. This delivers data as
142// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
143// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
144// of data to be available, then any remaining data is delivered.
145// This is required to ensure the last bit of data is delivered before underrun.
146//
147// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
148// or the size of the HAL period for proportional / linear PCM tracks.
149static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800150
151// don't warn about blocked writes or record buffer overflows more often than this
152static const nsecs_t kWarningThrottleNs = seconds(5);
153
154// RecordThread loop sleep time upon application overrun or audio HAL read error
155static const int kRecordThreadSleepUs = 5000;
156
Eric Laurent10351942014-05-08 18:49:52 -0700157// maximum time to wait in sendConfigEvent_l() for a status to be received
158static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800159
160// minimum sleep time for the mixer thread loop when tracks are active but in underrun
161static const uint32_t kMinThreadSleepTimeUs = 5000;
162// maximum divider applied to the active sleep time in the mixer thread loop
163static const uint32_t kMaxThreadSleepTimeShift = 2;
164
Andy Hung09a50072014-02-27 14:30:47 -0800165// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700166// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800167static const uint32_t kMinNormalSinkBufferSizeMs = 20;
168// maximum normal sink buffer size
169static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800170
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700171// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
172// FIXME This should be based on experimentally observed scheduling jitter
173static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
174
Eric Laurent972a1732013-09-04 09:42:59 -0700175// Offloaded output thread standby delay: allows track transition without going to standby
176static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
177
Eric Laurent51716182016-02-29 18:00:56 -0800178// Direct output thread minimum sleep time in idle or active(underrun) state
179static const nsecs_t kDirectMinSleepTimeUs = 10000;
180
Brian Lindahl9e661ad2022-07-27 18:01:07 +0200181// Minimum amount of time between checking to see if the timestamp is advancing
182// for underrun detection. If we check too frequently, we may not detect a
183// timestamp update and will falsely detect underrun.
184static const nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1000;
185
Glenn Kasten1b291842016-07-18 14:55:21 -0700186// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
187// balance between power consumption and latency, and allows threads to be scheduled reliably
188// by the CFS scheduler.
189// FIXME Express other hardcoded references to 20ms with references to this constant and move
190// it appropriately.
191#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800192
Eric Laurent81784c32012-11-19 14:55:58 -0800193// Whether to use fast mixer
194static const enum {
195 FastMixer_Never, // never initialize or use: for debugging only
196 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
197 // normal mixer multiplier is 1
198 FastMixer_Static, // initialize if needed, then use all the time if initialized,
199 // multiplier is calculated based on min & max normal mixer buffer size
200 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
201 // multiplier is calculated based on min & max normal mixer buffer size
202 // FIXME for FastMixer_Dynamic:
203 // Supporting this option will require fixing HALs that can't handle large writes.
204 // For example, one HAL implementation returns an error from a large write,
205 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
206 // We could either fix the HAL implementations, or provide a wrapper that breaks
207 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
208} kUseFastMixer = FastMixer_Static;
209
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700210// Whether to use fast capture
211static const enum {
212 FastCapture_Never, // never initialize or use: for debugging only
213 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
214 FastCapture_Static, // initialize if needed, then use all the time if initialized
215} kUseFastCapture = FastCapture_Static;
216
Eric Laurent81784c32012-11-19 14:55:58 -0800217// Priorities for requestPriority
218static const int kPriorityAudioApp = 2;
219static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700220static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800221
Glenn Kastenea38ee72016-04-18 11:08:01 -0700222// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
223// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
224// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700225
226// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800227static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800228
Glenn Kasten03490092014-05-27 12:30:54 -0700229// The minimum and maximum allowed values
230static const int kFastTrackMultiplierMin = 1;
231static const int kFastTrackMultiplierMax = 2;
232
233// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
234static int sFastTrackMultiplier = kFastTrackMultiplier;
235
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700236// See Thread::readOnlyHeap().
237// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
238// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
239// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700240static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700241
Eric Laurent81784c32012-11-19 14:55:58 -0800242// ----------------------------------------------------------------------------
243
Andy Hungb68f5eb2019-12-03 16:49:17 -0800244// TODO: move all toString helpers to audio.h
245// under #ifdef __cplusplus #endif
246static std::string patchSinksToString(const struct audio_patch *patch)
247{
248 std::stringstream ss;
249 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700250 if (i > 0) {
251 ss << "|";
252 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800253 ss << "(" << toString(patch->sinks[i].ext.device.type)
254 << ", " << patch->sinks[i].ext.device.address << ")";
255 }
256 return ss.str();
257}
258
259static std::string patchSourcesToString(const struct audio_patch *patch)
260{
261 std::stringstream ss;
262 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700263 if (i > 0) {
264 ss << "|";
265 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800266 ss << "(" << toString(patch->sources[i].ext.device.type)
267 << ", " << patch->sources[i].ext.device.address << ")";
268 }
269 return ss.str();
270}
271
Andy Hung4bd53e72022-11-17 17:21:45 -0800272static std::string toString(audio_latency_mode_t mode) {
273 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganova77d5552022-12-18 02:48:14 +0000274 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
275 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800276}
277
278// Could be made a template, but other toString overloads for std::vector are confused.
279static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
280 std::string s("{ ");
281 for (const auto& e : elements) {
282 s.append(toString(e));
283 s.append(" ");
284 }
285 s.append("}");
286 return s;
287}
288
Glenn Kasten03490092014-05-27 12:30:54 -0700289static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
290
291static void sFastTrackMultiplierInit()
292{
293 char value[PROPERTY_VALUE_MAX];
294 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
295 char *endptr;
296 unsigned long ul = strtoul(value, &endptr, 0);
297 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
298 sFastTrackMultiplier = (int) ul;
299 }
300 }
301}
302
303// ----------------------------------------------------------------------------
304
Eric Laurent81784c32012-11-19 14:55:58 -0800305#ifdef ADD_BATTERY_DATA
306// To collect the amplifier usage
307static void addBatteryData(uint32_t params) {
308 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
309 if (service == NULL) {
310 // it already logged
311 return;
312 }
313
314 service->addBatteryData(params);
315}
316#endif
317
Andy Hung3f0c9022016-01-15 17:49:46 -0800318// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
319struct {
320 // call when you acquire a partial wakelock
321 void acquire(const sp<IBinder> &wakeLockToken) {
322 pthread_mutex_lock(&mLock);
323 if (wakeLockToken.get() == nullptr) {
324 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
325 } else {
326 if (mCount == 0) {
327 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
328 }
329 ++mCount;
330 }
331 pthread_mutex_unlock(&mLock);
332 }
333
334 // call when you release a partial wakelock.
335 void release(const sp<IBinder> &wakeLockToken) {
336 if (wakeLockToken.get() == nullptr) {
337 return;
338 }
339 pthread_mutex_lock(&mLock);
340 if (--mCount < 0) {
341 ALOGE("negative wakelock count");
342 mCount = 0;
343 }
344 pthread_mutex_unlock(&mLock);
345 }
346
347 // retrieves the boottime timebase offset from monotonic.
348 int64_t getBoottimeOffset() {
349 pthread_mutex_lock(&mLock);
350 int64_t boottimeOffset = mBoottimeOffset;
351 pthread_mutex_unlock(&mLock);
352 return boottimeOffset;
353 }
354
355 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
356 // and the selected timebase.
357 // Currently only TIMEBASE_BOOTTIME is allowed.
358 //
359 // This only needs to be called upon acquiring the first partial wakelock
360 // after all other partial wakelocks are released.
361 //
362 // We do an empirical measurement of the offset rather than parsing
363 // /proc/timer_list since the latter is not a formal kernel ABI.
364 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
365 int clockbase;
366 switch (timebase) {
367 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
368 clockbase = SYSTEM_TIME_BOOTTIME;
369 break;
370 default:
371 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
372 break;
373 }
374 // try three times to get the clock offset, choose the one
375 // with the minimum gap in measurements.
376 const int tries = 3;
377 nsecs_t bestGap, measured;
378 for (int i = 0; i < tries; ++i) {
379 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
380 const nsecs_t tbase = systemTime(clockbase);
381 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
382 const nsecs_t gap = tmono2 - tmono;
383 if (i == 0 || gap < bestGap) {
384 bestGap = gap;
385 measured = tbase - ((tmono + tmono2) >> 1);
386 }
387 }
388
389 // to avoid micro-adjusting, we don't change the timebase
390 // unless it is significantly different.
391 //
392 // Assumption: It probably takes more than toleranceNs to
393 // suspend and resume the device.
394 static int64_t toleranceNs = 10000; // 10 us
395 if (llabs(*offset - measured) > toleranceNs) {
396 ALOGV("Adjusting timebase offset old: %lld new: %lld",
397 (long long)*offset, (long long)measured);
398 *offset = measured;
399 }
400 }
401
402 pthread_mutex_t mLock;
403 int32_t mCount;
404 int64_t mBoottimeOffset;
405} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800406
407// ----------------------------------------------------------------------------
408// CPU Stats
409// ----------------------------------------------------------------------------
410
411class CpuStats {
412public:
413 CpuStats();
414 void sample(const String8 &title);
415#ifdef DEBUG_CPU_USAGE
416private:
417 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700418 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800419
Andy Hung16698b82018-08-01 10:48:38 -0700420 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800421
422 int mCpuNum; // thread's current CPU number
423 int mCpukHz; // frequency of thread's current CPU in kHz
424#endif
425};
426
427CpuStats::CpuStats()
428#ifdef DEBUG_CPU_USAGE
429 : mCpuNum(-1), mCpukHz(-1)
430#endif
431{
432}
433
Glenn Kasten0f11b512014-01-31 16:18:54 -0800434void CpuStats::sample(const String8 &title
435#ifndef DEBUG_CPU_USAGE
436 __unused
437#endif
438 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800439#ifdef DEBUG_CPU_USAGE
440 // get current thread's delta CPU time in wall clock ns
441 double wcNs;
442 bool valid = mCpuUsage.sampleAndEnable(wcNs);
443
444 // record sample for wall clock statistics
445 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700446 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800447 }
448
449 // get the current CPU number
450 int cpuNum = sched_getcpu();
451
452 // get the current CPU frequency in kHz
453 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
454
455 // check if either CPU number or frequency changed
456 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
457 mCpuNum = cpuNum;
458 mCpukHz = cpukHz;
459 // ignore sample for purposes of cycles
460 valid = false;
461 }
462
463 // if no change in CPU number or frequency, then record sample for cycle statistics
464 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700465 const double cycles = wcNs * cpukHz * 0.000001;
466 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800467 }
468
Eric Tan5b13ff82018-07-27 11:20:17 -0700469 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800470 // mCpuUsage.elapsed() is expensive, so don't call it every loop
471 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700472 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800473 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700474 const double perLoop = elapsed / (double) n;
475 const double perLoop100 = perLoop * 0.01;
476 const double perLoop1k = perLoop * 0.001;
477 const double mean = mWcStats.getMean();
478 const double stddev = mWcStats.getStdDev();
479 const double minimum = mWcStats.getMin();
480 const double maximum = mWcStats.getMax();
481 const double meanCycles = mHzStats.getMean();
482 const double stddevCycles = mHzStats.getStdDev();
483 const double minCycles = mHzStats.getMin();
484 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800485 mCpuUsage.resetElapsed();
486 mWcStats.reset();
487 mHzStats.reset();
488 ALOGD("CPU usage for %s over past %.1f secs\n"
489 " (%u mixer loops at %.1f mean ms per loop):\n"
490 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
491 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
492 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
493 title.string(),
494 elapsed * .000000001, n, perLoop * .000001,
495 mean * .001,
496 stddev * .001,
497 minimum * .001,
498 maximum * .001,
499 mean / perLoop100,
500 stddev / perLoop100,
501 minimum / perLoop100,
502 maximum / perLoop100,
503 meanCycles / perLoop1k,
504 stddevCycles / perLoop1k,
505 minCycles / perLoop1k,
506 maxCycles / perLoop1k);
507
508 }
509 }
510#endif
511};
512
513// ----------------------------------------------------------------------------
514// ThreadBase
515// ----------------------------------------------------------------------------
516
Glenn Kasten97b7b752014-09-28 13:04:24 -0700517// static
518const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
519{
520 switch (type) {
521 case MIXER:
522 return "MIXER";
523 case DIRECT:
524 return "DIRECT";
525 case DUPLICATING:
526 return "DUPLICATING";
527 case RECORD:
528 return "RECORD";
529 case OFFLOAD:
530 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700531 case MMAP_PLAYBACK:
532 return "MMAP_PLAYBACK";
533 case MMAP_CAPTURE:
534 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200535 case SPATIALIZER:
536 return "SPATIALIZER";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700537 default:
538 return "unknown";
539 }
540}
541
Eric Laurent81784c32012-11-19 14:55:58 -0800542AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700543 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800544 : Thread(false /*canCallJava*/),
545 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700546 mAudioFlinger(audioFlinger),
Andy Hungcf10d742020-04-28 15:38:24 -0700547 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
548 isOut),
549 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700550 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800551 // are set by PlaybackThread::readOutputParameters_l() or
552 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700553 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700554 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700555 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800556 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700557 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800558 mSystemReady(systemReady),
559 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800560{
Andy Hungcf10d742020-04-28 15:38:24 -0700561 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700562 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800563}
564
565AudioFlinger::ThreadBase::~ThreadBase()
566{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700567 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700568 mConfigEvents.clear();
569
Eric Laurent81784c32012-11-19 14:55:58 -0800570 // do not lock the mutex in destructor
571 releaseWakeLock_l();
572 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800573 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800574 binder->unlinkToDeath(mDeathRecipient);
575 }
Andy Hungd0979812019-02-21 15:51:44 -0800576
577 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800578}
579
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700580status_t AudioFlinger::ThreadBase::readyToRun()
581{
582 status_t status = initCheck();
583 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800584 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700585 } else {
586 ALOGE("No working audio driver found.");
587 }
588 return status;
589}
590
Eric Laurent81784c32012-11-19 14:55:58 -0800591void AudioFlinger::ThreadBase::exit()
592{
593 ALOGV("ThreadBase::exit");
594 // do any cleanup required for exit to succeed
595 preExit();
596 {
597 // This lock prevents the following race in thread (uniprocessor for illustration):
598 // if (!exitPending()) {
599 // // context switch from here to exit()
600 // // exit() calls requestExit(), what exitPending() observes
601 // // exit() calls signal(), which is dropped since no waiters
602 // // context switch back from exit() to here
603 // mWaitWorkCV.wait(...);
604 // // now thread is hung
605 // }
606 AutoMutex lock(mLock);
607 requestExit();
608 mWaitWorkCV.broadcast();
609 }
610 // When Thread::requestExitAndWait is made virtual and this method is renamed to
611 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
612 requestExitAndWait();
613}
614
615status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
616{
Eric Laurent81784c32012-11-19 14:55:58 -0800617 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
618 Mutex::Autolock _l(mLock);
619
Eric Laurent10351942014-05-08 18:49:52 -0700620 return sendSetParameterConfigEvent_l(keyValuePairs);
621}
622
623// sendConfigEvent_l() must be called with ThreadBase::mLock held
624// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
625status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
626{
627 status_t status = NO_ERROR;
628
Eric Laurent72e3f392015-05-20 14:43:50 -0700629 if (event->mRequiresSystemReady && !mSystemReady) {
630 event->mWaitStatus = false;
631 mPendingConfigEvents.add(event);
632 return status;
633 }
Eric Laurent10351942014-05-08 18:49:52 -0700634 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700635 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800636 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700637 mLock.unlock();
638 {
639 Mutex::Autolock _l(event->mLock);
640 while (event->mWaitStatus) {
641 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
642 event->mStatus = TIMED_OUT;
643 event->mWaitStatus = false;
644 }
645 }
646 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800647 }
Eric Laurent10351942014-05-08 18:49:52 -0700648 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800649 return status;
650}
651
Mikhail Naganov88536df2021-07-26 17:30:29 -0700652void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700653 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800654{
655 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700656 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800657}
658
659// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov88536df2021-07-26 17:30:29 -0700660void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700661 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800662{
Andy Hungd0979812019-02-21 15:51:44 -0800663 // The audio statistics history is exponentially weighted to forget events
664 // about five or more seconds in the past. In order to have
665 // crisper statistics for mediametrics, we reset the statistics on
666 // an IoConfigEvent, to reflect different properties for a new device.
667 mIoJitterMs.reset();
668 mLatencyMs.reset();
669 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000670 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100671 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800672
Eric Laurent09f1ed22019-04-24 17:45:17 -0700673 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700674 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800675}
676
Mikhail Naganov83f04272017-02-07 10:45:09 -0800677void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700678{
679 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800680 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700681}
682
Eric Laurent81784c32012-11-19 14:55:58 -0800683// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800684void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
685 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800686{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800687 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700688 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800689}
690
Eric Laurent10351942014-05-08 18:49:52 -0700691// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
692status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800693{
Andy Hung2ddee192015-12-18 17:34:44 -0800694 sp<ConfigEvent> configEvent;
695 AudioParameter param(keyValuePair);
696 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700697 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800698 setMasterMono_l(value != 0);
699 if (param.size() == 1) {
700 return NO_ERROR; // should be a solo parameter - we don't pass down
701 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700702 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800703 configEvent = new SetParameterConfigEvent(param.toString());
704 } else {
705 configEvent = new SetParameterConfigEvent(keyValuePair);
706 }
Eric Laurent10351942014-05-08 18:49:52 -0700707 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700708}
709
Eric Laurent1c333e22014-05-20 10:48:17 -0700710status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
711 const struct audio_patch *patch,
712 audio_patch_handle_t *handle)
713{
714 Mutex::Autolock _l(mLock);
715 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
716 status_t status = sendConfigEvent_l(configEvent);
717 if (status == NO_ERROR) {
718 CreateAudioPatchConfigEventData *data =
719 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
720 *handle = data->mHandle;
721 }
722 return status;
723}
724
725status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
726 const audio_patch_handle_t handle)
727{
728 Mutex::Autolock _l(mLock);
729 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
730 return sendConfigEvent_l(configEvent);
731}
732
jiabinc52b1ff2019-10-31 17:20:42 -0700733status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
734 const DeviceDescriptorBaseVector& outDevices)
735{
736 if (type() != RECORD) {
737 // The update out device operation is only for record thread.
738 return INVALID_OPERATION;
739 }
740 Mutex::Autolock _l(mLock);
741 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
742 return sendConfigEvent_l(configEvent);
743}
744
Eric Laurentec376dc2021-04-08 20:41:22 +0200745void AudioFlinger::ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
746{
747 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
748 sp<ConfigEvent> configEvent =
749 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
750 sendConfigEvent_l(configEvent);
751}
Eric Laurent1c333e22014-05-20 10:48:17 -0700752
Eric Laurentb3f315a2021-07-13 15:09:05 +0200753void AudioFlinger::ThreadBase::sendCheckOutputStageEffectsEvent()
754{
755 Mutex::Autolock _l(mLock);
756 sendCheckOutputStageEffectsEvent_l();
757}
758
759void AudioFlinger::ThreadBase::sendCheckOutputStageEffectsEvent_l()
760{
761 sp<ConfigEvent> configEvent =
762 (ConfigEvent *)new CheckOutputStageEffectsEvent();
763 sendConfigEvent_l(configEvent);
764}
765
Eric Laurent6f9534f2022-05-03 18:15:04 +0200766void AudioFlinger::ThreadBase::sendHalLatencyModesChangedEvent_l()
767{
768 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
769 sendConfigEvent_l(configEvent);
770}
771
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700772// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700773void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700774{
Eric Laurent10351942014-05-08 18:49:52 -0700775 bool configChanged = false;
776
Eric Laurent81784c32012-11-19 14:55:58 -0800777 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700778 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700779 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800780 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700781 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700782 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700783 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
784 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800785 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700786 true /*asynchronous*/);
787 if (err != 0) {
788 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700789 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700790 }
791 } break;
792 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700793 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700794 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700795 } break;
796 case CFG_EVENT_SET_PARAMETER: {
797 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
798 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
799 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700800 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
801 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700802 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700803 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700804 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700805 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700806 CreateAudioPatchConfigEventData *data =
807 (CreateAudioPatchConfigEventData *)event->mData.get();
808 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700809 const DeviceTypeSet newDevices = getDeviceTypes();
810 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
811 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
812 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700813 } break;
814 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700815 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700816 ReleaseAudioPatchConfigEventData *data =
817 (ReleaseAudioPatchConfigEventData *)event->mData.get();
818 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700819 const DeviceTypeSet newDevices = getDeviceTypes();
820 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
821 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
822 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
823 } break;
824 case CFG_EVENT_UPDATE_OUT_DEVICE: {
825 UpdateOutDevicesConfigEventData *data =
826 (UpdateOutDevicesConfigEventData *)event->mData.get();
827 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700828 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200829 case CFG_EVENT_RESIZE_BUFFER: {
830 ResizeBufferConfigEventData *data =
831 (ResizeBufferConfigEventData *)event->mData.get();
832 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
833 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200834
835 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
836 setCheckOutputStageEffects();
837 } break;
838
Eric Laurent6f9534f2022-05-03 18:15:04 +0200839 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
840 onHalLatencyModesChanged_l();
841 } break;
842
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700843 default:
Eric Laurent10351942014-05-08 18:49:52 -0700844 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700845 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800846 }
Eric Laurent10351942014-05-08 18:49:52 -0700847 {
848 Mutex::Autolock _l(event->mLock);
849 if (event->mWaitStatus) {
850 event->mWaitStatus = false;
851 event->mCond.signal();
852 }
853 }
854 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
855 }
856
857 if (configChanged) {
858 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800859 }
Eric Laurent81784c32012-11-19 14:55:58 -0800860}
861
Marco Nelissenb2208842014-02-07 14:00:50 -0800862String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
863 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700864 const audio_channel_representation_t representation =
865 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700866
867 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800868 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700869 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
870 if (output) {
871 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
872 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
873 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700874 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700875 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
876 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
877 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
878 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
879 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
880 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
881 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
882 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
883 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
884 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
885 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
886 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700887 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
888 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
889 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
890 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
891 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
892 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
893 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700894 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700895 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
896 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700897 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
898 } else {
899 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
900 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
901 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
902 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
903 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
904 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
905 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
906 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
907 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
908 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
909 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
910 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700911 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
912 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
913 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700914 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700915 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
916 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700917 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
918 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
919 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
920 }
921 const int len = s.length();
922 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700923 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700924 s.unlockBuffer(len - 2); // remove trailing ", "
925 }
926 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800927 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700928 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
929 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
930 return s;
931 default:
932 s.appendFormat("unknown mask, representation:%d bits:%#x",
933 representation, audio_channel_mask_get_bits(mask));
934 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800935 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800936}
937
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700938void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800939{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800940 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
941 this, mThreadName, getTid(), type(), threadTypeToString(type()));
942
Eric Laurent81784c32012-11-19 14:55:58 -0800943 bool locked = AudioFlinger::dumpTryLock(mLock);
944 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800945 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800946 }
947
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700948 dumpBase_l(fd, args);
949 dumpInternals_l(fd, args);
950 dumpTracks_l(fd, args);
951 dumpEffectChains_l(fd, args);
952
953 if (locked) {
954 mLock.unlock();
955 }
956
957 dprintf(fd, " Local log:\n");
958 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -0700959
960 // --all does the statistics
961 bool dumpAll = false;
962 for (const auto &arg : args) {
963 if (arg == String16("--all")) {
964 dumpAll = true;
965 }
966 }
967 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -0700968 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -0700969 if (!sched.empty()) {
970 (void)write(fd, sched.c_str(), sched.size());
971 }
972 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700973}
974
975void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
976{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700977 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700978 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700979 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700980 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700981 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700982 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700983 dprintf(fd, " Channel count: %u\n", mChannelCount);
984 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800985 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700986 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700987 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700988 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800989 size_t numConfig = mConfigEvents.size();
990 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700991 const size_t SIZE = 256;
992 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800993 for (size_t i = 0; i < numConfig; i++) {
994 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700995 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800996 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700997 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800998 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700999 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001000 }
Andy Hung293558a2017-03-21 12:19:20 -07001001 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001002 dprintf(fd, " Output devices: %s (%s)\n",
1003 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
1004 dprintf(fd, " Input device: %#x (%s)\n",
1005 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001006 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001007
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001008 // Dump timestamp statistics for the Thread types that support it.
1009 if (mType == RECORD
1010 || mType == MIXER
1011 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001012 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001013 || mType == OFFLOAD
1014 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001015 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -07001016 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001017 }
1018
Andy Hung446f4df2019-02-21 12:26:41 -08001019 if (mLastIoBeginNs > 0) { // MMAP may not set this
1020 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1021 isOutput() ? "write" : "read",
1022 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1023 }
1024
1025 if (mProcessTimeMs.getN() > 0) {
1026 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1027 }
1028
1029 if (mIoJitterMs.getN() > 0) {
1030 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1031 isOutput() ? "write" : "read",
1032 mIoJitterMs.toString().c_str());
1033 }
1034
Andy Hunge6c37112019-02-26 17:38:10 -08001035 if (mLatencyMs.getN() > 0) {
1036 dprintf(fd, " Threadloop %s latency stats: %s\n",
1037 isOutput() ? "write" : "read",
1038 mLatencyMs.toString().c_str());
1039 }
Robert Wu06db0a32021-08-10 19:05:34 +00001040
1041 if (mMonopipePipeDepthStats.getN() > 0) {
1042 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1043 isOutput() ? "write" : "read",
1044 mMonopipePipeDepthStats.toString().c_str());
1045 }
Eric Laurent81784c32012-11-19 14:55:58 -08001046}
1047
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001048void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001049{
1050 const size_t SIZE = 256;
1051 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001052
Marco Nelissenb2208842014-02-07 14:00:50 -08001053 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001054 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001055 write(fd, buffer, strlen(buffer));
1056
Marco Nelissenb2208842014-02-07 14:00:50 -08001057 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -08001058 sp<EffectChain> chain = mEffectChains[i];
1059 if (chain != 0) {
1060 chain->dump(fd, args);
1061 }
1062 }
1063}
1064
Andy Hungdae27702016-10-31 14:01:16 -07001065void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001066{
1067 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07001068 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001069}
1070
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001071String16 AudioFlinger::ThreadBase::getWakeLockTag()
1072{
1073 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001074 case MIXER:
1075 return String16("AudioMix");
1076 case DIRECT:
1077 return String16("AudioDirectOut");
1078 case DUPLICATING:
1079 return String16("AudioDup");
1080 case RECORD:
1081 return String16("AudioIn");
1082 case OFFLOAD:
1083 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001084 case MMAP_PLAYBACK:
1085 return String16("MmapPlayback");
1086 case MMAP_CAPTURE:
1087 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001088 case SPATIALIZER:
1089 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001090 default:
1091 ALOG_ASSERT(false);
1092 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001093 }
1094}
1095
Andy Hungdae27702016-10-31 14:01:16 -07001096void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001097{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001098 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001099 if (mPowerManager != 0) {
1100 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001101 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001102 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1103 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001104 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001105 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001106 {} /* workSource */,
1107 {} /* historyTag */);
1108 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001109 mWakeLockToken = binder;
1110 }
Chris Ye6597d732020-02-28 22:38:25 -08001111 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001112 }
Wei Jia3f273d12015-11-24 09:06:49 -08001113
Andy Hung3f0c9022016-01-15 17:49:46 -08001114 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001115 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1116 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001117}
1118
1119void AudioFlinger::ThreadBase::releaseWakeLock()
1120{
1121 Mutex::Autolock _l(mLock);
1122 releaseWakeLock_l();
1123}
1124
1125void AudioFlinger::ThreadBase::releaseWakeLock_l()
1126{
Andy Hung3f0c9022016-01-15 17:49:46 -08001127 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001128 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001129 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001130 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001131 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001132 }
1133 mWakeLockToken.clear();
1134 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001135}
1136
1137void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001138 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001139 // use checkService() to avoid blocking if power service is not up yet
1140 sp<IBinder> binder =
1141 defaultServiceManager()->checkService(String16("power"));
1142 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001143 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001144 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001145 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001146 binder->linkToDeath(mDeathRecipient);
1147 }
1148 }
1149}
1150
Andy Hungd01b0f12016-11-07 16:10:30 -08001151void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001152 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001153
1154#if !LOG_NDEBUG
1155 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001156 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001157 s << uid << " ";
1158 }
1159 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1160#endif
1161
Andy Hung438e7572015-12-14 15:51:17 -08001162 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1163 if (mSystemReady) {
1164 ALOGE("no wake lock to update, but system ready!");
1165 } else {
1166 ALOGW("no wake lock to update, system not ready yet");
1167 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001168 return;
1169 }
1170 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001171 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001172 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1173 mWakeLockToken, uidsAsInt);
1174 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001175 }
1176}
1177
Eric Laurent81784c32012-11-19 14:55:58 -08001178void AudioFlinger::ThreadBase::clearPowerManager()
1179{
1180 Mutex::Autolock _l(mLock);
1181 releaseWakeLock_l();
1182 mPowerManager.clear();
1183}
1184
jiabinc52b1ff2019-10-31 17:20:42 -07001185void AudioFlinger::ThreadBase::updateOutDevices(
1186 const DeviceDescriptorBaseVector& outDevices __unused)
1187{
1188 ALOGE("%s should only be called in RecordThread", __func__);
1189}
1190
Eric Laurentec376dc2021-04-08 20:41:22 +02001191void AudioFlinger::ThreadBase::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs __unused)
1192{
1193 ALOGE("%s should only be called in RecordThread", __func__);
1194}
1195
Glenn Kasten0f11b512014-01-31 16:18:54 -08001196void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001197{
1198 sp<ThreadBase> thread = mThread.promote();
1199 if (thread != 0) {
1200 thread->clearPowerManager();
1201 }
1202 ALOGW("power manager service died !!!");
1203}
1204
Eric Laurent81784c32012-11-19 14:55:58 -08001205void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001206 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001207{
1208 sp<EffectChain> chain = getEffectChain_l(sessionId);
1209 if (chain != 0) {
1210 if (type != NULL) {
1211 chain->setEffectSuspended_l(type, suspend);
1212 } else {
1213 chain->setEffectSuspendedAll_l(suspend);
1214 }
1215 }
1216
1217 updateSuspendedSessions_l(type, suspend, sessionId);
1218}
1219
1220void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1221{
1222 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1223 if (index < 0) {
1224 return;
1225 }
1226
1227 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1228 mSuspendedSessions.valueAt(index);
1229
1230 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001231 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001232 for (int j = 0; j < desc->mRefCount; j++) {
1233 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1234 chain->setEffectSuspendedAll_l(true);
1235 } else {
1236 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1237 desc->mType.timeLow);
1238 chain->setEffectSuspended_l(&desc->mType, true);
1239 }
1240 }
1241 }
1242}
1243
1244void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1245 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001246 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001247{
1248 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1249
1250 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1251
1252 if (suspend) {
1253 if (index >= 0) {
1254 sessionEffects = mSuspendedSessions.valueAt(index);
1255 } else {
1256 mSuspendedSessions.add(sessionId, sessionEffects);
1257 }
1258 } else {
1259 if (index < 0) {
1260 return;
1261 }
1262 sessionEffects = mSuspendedSessions.valueAt(index);
1263 }
1264
1265
1266 int key = EffectChain::kKeyForSuspendAll;
1267 if (type != NULL) {
1268 key = type->timeLow;
1269 }
1270 index = sessionEffects.indexOfKey(key);
1271
1272 sp<SuspendedSessionDesc> desc;
1273 if (suspend) {
1274 if (index >= 0) {
1275 desc = sessionEffects.valueAt(index);
1276 } else {
1277 desc = new SuspendedSessionDesc();
1278 if (type != NULL) {
1279 desc->mType = *type;
1280 }
1281 sessionEffects.add(key, desc);
1282 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1283 }
1284 desc->mRefCount++;
1285 } else {
1286 if (index < 0) {
1287 return;
1288 }
1289 desc = sessionEffects.valueAt(index);
1290 if (--desc->mRefCount == 0) {
1291 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1292 sessionEffects.removeItemsAt(index);
1293 if (sessionEffects.isEmpty()) {
1294 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1295 sessionId);
1296 mSuspendedSessions.removeItem(sessionId);
1297 }
1298 }
1299 }
1300 if (!sessionEffects.isEmpty()) {
1301 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1302 }
1303}
1304
Eric Laurent6b446ce2019-12-13 10:56:31 -08001305void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1306 audio_session_t sessionId,
1307 bool threadLocked) {
1308 if (!threadLocked) {
1309 mLock.lock();
1310 }
Eric Laurent81784c32012-11-19 14:55:58 -08001311
Eric Laurent81784c32012-11-19 14:55:58 -08001312 if (mType != RECORD) {
1313 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1314 // another session. This gives the priority to well behaved effect control panels
1315 // and applications not using global effects.
1316 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1317 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001318 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001319 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1320 }
1321 }
1322
Eric Laurent6b446ce2019-12-13 10:56:31 -08001323 if (!threadLocked) {
1324 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001325 }
1326}
1327
Eric Laurent4c415062016-06-17 16:14:16 -07001328// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1329status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1330 const effect_descriptor_t *desc, audio_session_t sessionId)
1331{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001332 // No global output effect sessions on record threads
1333 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1334 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001335 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1336 desc->name, mThreadName);
1337 return BAD_VALUE;
1338 }
1339 // only pre processing effects on record thread
1340 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1341 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1342 desc->name, mThreadName);
1343 return BAD_VALUE;
1344 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001345
1346 // always allow effects without processing load or latency
1347 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1348 return NO_ERROR;
1349 }
1350
Eric Laurent4c415062016-06-17 16:14:16 -07001351 audio_input_flags_t flags = mInput->flags;
1352 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1353 if (flags & AUDIO_INPUT_FLAG_RAW) {
1354 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1355 desc->name, mThreadName);
1356 return BAD_VALUE;
1357 }
1358 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1359 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1360 desc->name, mThreadName);
1361 return BAD_VALUE;
1362 }
1363 }
jiabineb3bda02020-06-30 14:07:03 -07001364
1365 if (EffectModule::isHapticGenerator(&desc->type)) {
1366 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1367 return BAD_VALUE;
1368 }
Eric Laurent4c415062016-06-17 16:14:16 -07001369 return NO_ERROR;
1370}
1371
1372// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1373status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1374 const effect_descriptor_t *desc, audio_session_t sessionId)
1375{
1376 // no preprocessing on playback threads
1377 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001378 ALOGW("%s: pre processing effect %s created on playback"
1379 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001380 return BAD_VALUE;
1381 }
1382
Eric Laurent3e4de772017-07-16 16:55:08 -07001383 // always allow effects without processing load or latency
1384 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1385 return NO_ERROR;
1386 }
1387
jiabineb3bda02020-06-30 14:07:03 -07001388 if (EffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
1389 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1390 __func__);
1391 return BAD_VALUE;
1392 }
1393
Eric Laurentf690c462021-09-17 14:47:03 +02001394 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1395 && mType != SPATIALIZER) {
1396 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1397 __func__, mType);
1398 return BAD_VALUE;
1399 }
1400
Eric Laurent4c415062016-06-17 16:14:16 -07001401 switch (mType) {
1402 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001403#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001404 // Reject any effect on mixer multichannel sinks.
1405 // TODO: fix both format and multichannel issues with effects.
1406 if (mChannelCount != FCC_2) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001407 ALOGW("%s: effect %s for multichannel(%d) on MIXER thread %s",
1408 __func__, desc->name, mChannelCount, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001409 return BAD_VALUE;
1410 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001411#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001412 audio_output_flags_t flags = mOutput->flags;
1413 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1414 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1415 // global effects are applied only to non fast tracks if they are SW
1416 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1417 break;
1418 }
1419 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1420 // only post processing on output stage session
1421 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001422 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1423 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001424 return BAD_VALUE;
1425 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001426 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1427 // only post processing on output stage session
1428 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001429 ALOGW("%s: non post processing effect %s not allowed on device session",
1430 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001431 return BAD_VALUE;
1432 }
Eric Laurent4c415062016-06-17 16:14:16 -07001433 } else {
1434 // no restriction on effects applied on non fast tracks
1435 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1436 break;
1437 }
1438 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001439
Eric Laurent4c415062016-06-17 16:14:16 -07001440 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001441 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001442 return BAD_VALUE;
1443 }
1444 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001445 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1446 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001447 return BAD_VALUE;
1448 }
1449 }
1450 } break;
1451 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001452 // nothing actionable on offload threads, if the effect:
1453 // - is offloadable: the effect can be created
1454 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1455 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001456 break;
1457 case DIRECT:
1458 // Reject any effect on Direct output threads for now, since the format of
1459 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001460 ALOGW("%s: effect %s on DIRECT output thread %s",
1461 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001462 return BAD_VALUE;
1463 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001464#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001465 // Reject any effect on mixer multichannel sinks.
1466 // TODO: fix both format and multichannel issues with effects.
1467 if (mChannelCount != FCC_2) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001468 ALOGW("%s: effect %s for multichannel(%d) on DUPLICATING thread %s",
1469 __func__, desc->name, mChannelCount, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001470 return BAD_VALUE;
1471 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001472#endif
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001473 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001474 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1475 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001476 return BAD_VALUE;
1477 }
1478 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001479 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1480 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001481 return BAD_VALUE;
1482 }
1483 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001484 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1485 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001486 return BAD_VALUE;
1487 }
1488 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001489 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001490 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1491 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1492 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1493 // are supported and added after the spatializer.
1494 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1495 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1496 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001497 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001498 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1499 // only post processing , downmixer or spatializer effects on output stage session
1500 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1501 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1502 break;
1503 }
1504 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1505 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1506 __func__, desc->name);
1507 return BAD_VALUE;
1508 }
1509 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1510 // only post processing on output stage session
1511 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1512 ALOGW("%s: non post processing effect %s not allowed on device session",
1513 __func__, desc->name);
1514 return BAD_VALUE;
1515 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001516 }
1517 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001518 default:
1519 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1520 }
1521
1522 return NO_ERROR;
1523}
1524
Eric Laurent81784c32012-11-19 14:55:58 -08001525// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1526sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1527 const sp<AudioFlinger::Client>& client,
1528 const sp<IEffectClient>& effectClient,
1529 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001530 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001531 effect_descriptor_t *desc,
1532 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001533 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001534 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001535 bool probe,
1536 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001537{
1538 sp<EffectModule> effect;
1539 sp<EffectHandle> handle;
1540 status_t lStatus;
1541 sp<EffectChain> chain;
1542 bool chainCreated = false;
1543 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001544 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001545
1546 lStatus = initCheck();
1547 if (lStatus != NO_ERROR) {
1548 ALOGW("createEffect_l() Audio driver not initialized.");
1549 goto Exit;
1550 }
1551
Eric Laurent81784c32012-11-19 14:55:58 -08001552 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1553
1554 { // scope for mLock
1555 Mutex::Autolock _l(mLock);
1556
Eric Laurent4c415062016-06-17 16:14:16 -07001557 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001558 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001559 goto Exit;
1560 }
1561
Eric Laurent81784c32012-11-19 14:55:58 -08001562 // check for existing effect chain with the requested audio session
1563 chain = getEffectChain_l(sessionId);
1564 if (chain == 0) {
1565 // create a new chain for this session
1566 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1567 chain = new EffectChain(this, sessionId);
1568 addEffectChain_l(chain);
1569 chain->setStrategy(getStrategyForSession_l(sessionId));
1570 chainCreated = true;
1571 } else {
1572 effect = chain->getEffectFromDesc_l(desc);
1573 }
1574
1575 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1576
1577 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001578 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001579 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001580 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001581 if (lStatus != NO_ERROR) {
1582 goto Exit;
1583 }
1584 effectCreated = true;
1585
jiabinc52b1ff2019-10-31 17:20:42 -07001586 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001587 effect->setDevices(outDeviceTypeAddrs());
1588 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001589 effect->setMode(mAudioFlinger->getMode());
1590 effect->setAudioSource(mAudioSource);
1591 }
jiabin1319f5a2021-03-30 22:21:24 +00001592 if (effect->isHapticGenerator()) {
1593 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1594 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001595 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
1596 std::move(mAudioFlinger->getDefaultVibratorInfo_l());
1597 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001598 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001599 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001600 }
1601 }
Eric Laurent81784c32012-11-19 14:55:58 -08001602 // create effect handle and connect it to effect module
Eric Laurentde8caf42021-08-11 17:19:25 +02001603 handle = new EffectHandle(effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001604 lStatus = handle->initCheck();
1605 if (lStatus == OK) {
1606 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001607 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001608 }
Eric Laurent81784c32012-11-19 14:55:58 -08001609 if (enabled != NULL) {
1610 *enabled = (int)effect->isEnabled();
1611 }
1612 }
1613
1614Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001615 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001616 Mutex::Autolock _l(mLock);
1617 if (effectCreated) {
1618 chain->removeEffect_l(effect);
1619 }
Eric Laurent81784c32012-11-19 14:55:58 -08001620 if (chainCreated) {
1621 removeEffectChain_l(chain);
1622 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001623 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001624 }
1625
Glenn Kasten9156ef32013-08-06 15:39:08 -07001626 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001627 return handle;
1628}
1629
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001630void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1631 bool unpinIfLast)
1632{
1633 bool remove = false;
1634 sp<EffectModule> effect;
1635 {
1636 Mutex::Autolock _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001637 sp<EffectBase> effectBase = handle->effect().promote();
1638 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001639 return;
1640 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001641 effect = effectBase->asEffectModule();
1642 if (effect == nullptr) {
1643 return;
1644 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001645 // restore suspended effects if the disconnected handle was enabled and the last one.
1646 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1647 if (remove) {
1648 removeEffect_l(effect, true);
1649 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001650 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001651 }
1652 if (remove) {
1653 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001654 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001655 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001656 }
1657 }
1658}
1659
Eric Laurent6b446ce2019-12-13 10:56:31 -08001660void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001661 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001662 Mutex::Autolock _l(mLock);
1663 broadcast_l();
1664 }
1665 if (!effect->isOffloadable()) {
1666 if (mType == ThreadBase::OFFLOAD) {
1667 PlaybackThread *t = (PlaybackThread *)this;
1668 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1669 }
1670 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1671 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1672 }
1673 }
1674}
1675
1676void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001677 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001678 Mutex::Autolock _l(mLock);
1679 broadcast_l();
1680 }
1681}
1682
Glenn Kastend848eb42016-03-08 13:42:11 -08001683sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1684 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001685{
1686 Mutex::Autolock _l(mLock);
1687 return getEffect_l(sessionId, effectId);
1688}
1689
Glenn Kastend848eb42016-03-08 13:42:11 -08001690sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1691 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001692{
1693 sp<EffectChain> chain = getEffectChain_l(sessionId);
1694 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1695}
1696
Eric Laurent6c796322019-04-09 14:13:17 -07001697std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1698{
1699 sp<EffectChain> chain = getEffectChain_l(sessionId);
1700 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1701}
1702
Eric Laurent81784c32012-11-19 14:55:58 -08001703// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1704// PlaybackThread::mLock held
1705status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1706{
1707 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001708 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001709 sp<EffectChain> chain = getEffectChain_l(sessionId);
1710 bool chainCreated = false;
1711
Eric Laurent5baf2af2013-09-12 17:37:00 -07001712 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001713 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001714 this, effect->desc().name, effect->desc().flags);
1715
Eric Laurent81784c32012-11-19 14:55:58 -08001716 if (chain == 0) {
1717 // create a new chain for this session
1718 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1719 chain = new EffectChain(this, sessionId);
1720 addEffectChain_l(chain);
1721 chain->setStrategy(getStrategyForSession_l(sessionId));
1722 chainCreated = true;
1723 }
1724 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1725
1726 if (chain->getEffectFromId_l(effect->id()) != 0) {
1727 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1728 this, effect->desc().name, chain.get());
1729 return BAD_VALUE;
1730 }
1731
Eric Laurent5baf2af2013-09-12 17:37:00 -07001732 effect->setOffloaded(mType == OFFLOAD, mId);
1733
Eric Laurent81784c32012-11-19 14:55:58 -08001734 status_t status = chain->addEffect_l(effect);
1735 if (status != NO_ERROR) {
1736 if (chainCreated) {
1737 removeEffectChain_l(chain);
1738 }
1739 return status;
1740 }
1741
jiabin8f278ee2019-11-11 12:16:27 -08001742 effect->setDevices(outDeviceTypeAddrs());
1743 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001744 effect->setMode(mAudioFlinger->getMode());
1745 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001746
Eric Laurent81784c32012-11-19 14:55:58 -08001747 return NO_ERROR;
1748}
1749
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001750void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001751
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001752 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001753 effect_descriptor_t desc = effect->desc();
1754 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1755 detachAuxEffect_l(effect->id());
1756 }
1757
Andy Hungfda44002021-06-03 17:23:16 -07001758 sp<EffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001759 if (chain != 0) {
1760 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001761 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001762 removeEffectChain_l(chain);
1763 }
1764 } else {
1765 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1766 }
1767}
1768
1769void AudioFlinger::ThreadBase::lockEffectChains_l(
1770 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1771{
1772 effectChains = mEffectChains;
1773 for (size_t i = 0; i < mEffectChains.size(); i++) {
1774 mEffectChains[i]->lock();
1775 }
1776}
1777
1778void AudioFlinger::ThreadBase::unlockEffectChains(
1779 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1780{
1781 for (size_t i = 0; i < effectChains.size(); i++) {
1782 effectChains[i]->unlock();
1783 }
1784}
1785
Glenn Kastend848eb42016-03-08 13:42:11 -08001786sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001787{
1788 Mutex::Autolock _l(mLock);
1789 return getEffectChain_l(sessionId);
1790}
1791
Glenn Kastend848eb42016-03-08 13:42:11 -08001792sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1793 const
Eric Laurent81784c32012-11-19 14:55:58 -08001794{
1795 size_t size = mEffectChains.size();
1796 for (size_t i = 0; i < size; i++) {
1797 if (mEffectChains[i]->sessionId() == sessionId) {
1798 return mEffectChains[i];
1799 }
1800 }
1801 return 0;
1802}
1803
1804void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1805{
1806 Mutex::Autolock _l(mLock);
1807 size_t size = mEffectChains.size();
1808 for (size_t i = 0; i < size; i++) {
1809 mEffectChains[i]->setMode_l(mode);
1810 }
1811}
1812
Mikhail Naganovdc769682018-05-04 15:34:08 -07001813void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001814{
1815 config->type = AUDIO_PORT_TYPE_MIX;
1816 config->ext.mix.handle = mId;
1817 config->sample_rate = mSampleRate;
1818 config->format = mFormat;
1819 config->channel_mask = mChannelMask;
1820 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1821 AUDIO_PORT_CONFIG_FORMAT;
1822}
1823
Eric Laurent72e3f392015-05-20 14:43:50 -07001824void AudioFlinger::ThreadBase::systemReady()
1825{
1826 Mutex::Autolock _l(mLock);
1827 if (mSystemReady) {
1828 return;
1829 }
1830 mSystemReady = true;
1831
1832 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1833 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1834 }
1835 mPendingConfigEvents.clear();
1836}
1837
Andy Hungdae27702016-10-31 14:01:16 -07001838template <typename T>
1839ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1840 ssize_t index = mActiveTracks.indexOf(track);
1841 if (index >= 0) {
1842 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1843 return index;
1844 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001845 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001846 mActiveTracksGeneration++;
1847 mLatestActiveTrack = track;
1848 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001849 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001850 return mActiveTracks.add(track);
1851}
1852
1853template <typename T>
1854ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1855 ssize_t index = mActiveTracks.remove(track);
1856 if (index < 0) {
1857 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1858 return index;
1859 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001860 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001861 mActiveTracksGeneration++;
1862 --mBatteryCounter[track->uid()].second;
1863 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001864 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001865#ifdef TEE_SINK
1866 track->dumpTee(-1 /* fd */, "_REMOVE");
1867#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001868 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001869 return index;
1870}
1871
1872template <typename T>
1873void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1874 for (const sp<T> &track : mActiveTracks) {
1875 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001876 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001877 }
1878 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001879 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001880 mActiveTracks.clear();
1881 mLatestActiveTrack.clear();
1882 mBatteryCounter.clear();
1883}
1884
1885template <typename T>
1886void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1887 sp<ThreadBase> thread, bool force) {
1888 // Updates ActiveTracks client uids to the thread wakelock.
1889 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1890 thread->updateWakeLockUids_l(getWakeLockUids());
1891 mLastActiveTracksGeneration = mActiveTracksGeneration;
1892 }
1893
1894 // Updates BatteryNotifier uids
1895 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1896 const uid_t uid = it->first;
1897 ssize_t &previous = it->second.first;
1898 ssize_t &current = it->second.second;
1899 if (current > 0) {
1900 if (previous == 0) {
1901 BatteryNotifier::getInstance().noteStartAudio(uid);
1902 }
1903 previous = current;
1904 ++it;
1905 } else if (current == 0) {
1906 if (previous > 0) {
1907 BatteryNotifier::getInstance().noteStopAudio(uid);
1908 }
1909 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1910 } else /* (current < 0) */ {
1911 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1912 }
1913 }
1914}
Eric Laurent83b88082014-06-20 18:31:16 -07001915
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001916template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001917bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001918 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001919 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001920
1921 for (const sp<T> &track : mActiveTracks) {
1922 // Do not short-circuit as all hasChanged states must be reset
1923 // as all the metadata are going to be sent
1924 hasChanged |= track->readAndClearHasChanged();
1925 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001926 return hasChanged;
1927}
1928
1929template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001930void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1931 const char *funcName, const sp<T> &track) const {
1932 if (mLocalLog != nullptr) {
1933 String8 result;
1934 track->appendDump(result, false /* active */);
1935 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1936 }
1937}
1938
Eric Laurent6acd1d42017-01-04 14:23:29 -08001939void AudioFlinger::ThreadBase::broadcast_l()
1940{
1941 // Thread could be blocked waiting for async
1942 // so signal it to handle state changes immediately
1943 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1944 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1945 mSignalPending = true;
1946 mWaitWorkCV.broadcast();
1947}
1948
Andy Hungd0979812019-02-21 15:51:44 -08001949// Call only from threadLoop() or when it is idle.
1950// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1951void AudioFlinger::ThreadBase::sendStatistics(bool force)
1952{
1953 // Do not log if we have no stats.
1954 // We choose the timestamp verifier because it is the most likely item to be present.
1955 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1956 if (nstats == 0) {
1957 return;
1958 }
1959
1960 // Don't log more frequently than once per 12 hours.
1961 // We use BOOTTIME to include suspend time.
1962 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1963 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1964 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1965 return;
1966 }
1967
1968 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1969 mLastRecordedTimeNs = timeNs;
1970
Ray Essickf27e9872019-12-07 06:28:46 -08001971 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001972
1973#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1974
1975 // thread configuration
1976 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1977 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1978 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1979 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1980 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1981 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1982 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001983 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1984 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001985
1986 // thread statistics
1987 if (mIoJitterMs.getN() > 0) {
1988 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1989 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1990 }
1991 if (mProcessTimeMs.getN() > 0) {
1992 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1993 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1994 }
1995 const auto tsjitter = mTimestampVerifier.getJitterMs();
1996 if (tsjitter.getN() > 0) {
1997 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1998 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1999 }
2000 if (mLatencyMs.getN() > 0) {
2001 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2002 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2003 }
Robert Wu06db0a32021-08-10 19:05:34 +00002004 if (mMonopipePipeDepthStats.getN() > 0) {
2005 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2006 mMonopipePipeDepthStats.getMean());
2007 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2008 mMonopipePipeDepthStats.getStdDev());
2009 }
Andy Hungd0979812019-02-21 15:51:44 -08002010
2011 item->selfrecord();
2012}
2013
Eric Laurentd66d7a12021-07-13 13:35:32 +02002014product_strategy_t AudioFlinger::ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
2015{
2016 if (!mAudioFlinger->isAudioPolicyReady()) {
2017 return PRODUCT_STRATEGY_NONE;
2018 }
2019 return AudioSystem::getStrategyForStream(stream);
2020}
2021
Eric Laurent81784c32012-11-19 14:55:58 -08002022// ----------------------------------------------------------------------------
2023// Playback
2024// ----------------------------------------------------------------------------
2025
2026AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
2027 AudioStreamOut* output,
2028 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002029 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002030 bool systemReady,
2031 audio_config_base_t *mixerConfig)
Andy Hungcf10d742020-04-28 15:38:24 -07002032 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002033 mNormalFrameCount(0), mSinkBuffer(NULL),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002034 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002035 mMixerBuffer(NULL),
2036 mMixerBufferSize(0),
2037 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2038 mMixerBufferValid(false),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002039 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002040 mEffectBuffer(NULL),
2041 mEffectBufferSize(0),
2042 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2043 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002044 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002045 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002046 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002047 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002048 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002049 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002050 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002051 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002052 mMixerStatus(MIXER_IDLE),
2053 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002054 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002055 mBytesRemaining(0),
2056 mCurrentWriteLength(0),
2057 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002058 mWriteAckSequence(0),
2059 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08002060 mScreenState(AudioFlinger::mScreenState),
2061 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002062 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002063 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002064 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl9e661ad2022-07-27 18:01:07 +02002065 mDownStreamPatch{},
Eric Laurent01eb1642022-12-16 11:45:07 +01002066 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs),
2067 mBluetoothLatencyModesEnabled(true)
Eric Laurent81784c32012-11-19 14:55:58 -08002068{
Glenn Kastend7dca052015-03-05 16:05:54 -08002069 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
2070 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002071
2072 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2073 // it would be safer to explicitly pass initial masterVolume/masterMute as
2074 // parameter.
2075 //
2076 // If the HAL we are using has support for master volume or master mute,
2077 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2078 // and the mute set to false).
2079 mMasterVolume = audioFlinger->masterVolume_l();
2080 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002081 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002082 if (mOutput->audioHwDev->canSetMasterVolume()) {
2083 mMasterVolume = 1.0;
2084 }
2085
2086 if (mOutput->audioHwDev->canSetMasterMute()) {
2087 mMasterMute = false;
2088 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002089 mIsMsdDevice = strcmp(
2090 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002091 }
2092
Eric Laurentf1f22e72021-07-13 14:04:14 +02002093 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2094 mMixerChannelMask = mixerConfig->channel_mask;
2095 }
2096
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002097 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002098
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002099 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002100 && mMixerChannelMask != mChannelMask) {
2101 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2102 mChannelMask, mMixerChannelMask);
2103 }
2104
Andy Hungc8fddf32018-08-08 18:32:37 -07002105 // TODO: We may also match on address as well as device type for
2106 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002107 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002108 // TODO: This property should be ensure that only contains one single device type.
2109 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2110 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002111 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2112 : AUDIO_DEVICE_NONE));
2113 }
2114
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002115 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2116 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002117 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08002118 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
2119 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002120 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002121 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2122 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002123 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2124 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002125}
2126
2127AudioFlinger::PlaybackThread::~PlaybackThread()
2128{
Glenn Kasten9e58b552013-01-18 15:09:48 -08002129 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002130 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002131 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002132 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002133 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002134}
2135
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002136// Thread virtuals
2137
2138void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002139{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002140 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002141 ALOGE("The stream is not open yet"); // This should not happen.
2142 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002143 // Callbacks take strong or weak pointers as a parameter.
2144 // Since PlaybackThread passes itself as a callback handler, it can only
2145 // be done outside of the constructor. Creating weak and especially strong
2146 // pointers to a refcounted object in its own constructor is strongly
2147 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2148 // Even if a function takes a weak pointer, it is possible that it will
2149 // need to convert it to a strong pointer down the line.
2150 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2151 mOutput->stream->setCallback(this) == OK) {
2152 mUseAsyncWrite = true;
2153 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
2154 }
2155
jiabinf6eb4c32020-02-25 14:06:25 -08002156 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002157 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002158 }
2159 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002160 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002161 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002162}
2163
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002164// ThreadBase virtuals
2165void AudioFlinger::PlaybackThread::preExit()
2166{
2167 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002168 status_t result = mOutput->stream->exit();
2169 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002170}
2171
2172void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002173{
Eric Laurent81784c32012-11-19 14:55:58 -08002174 String8 result;
2175
Marco Nelissenb2208842014-02-07 14:00:50 -08002176 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002177 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2178 const stream_type_t *st = &mStreamTypes[i];
2179 if (i > 0) {
2180 result.appendFormat(", ");
2181 }
2182 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2183 if (st->mute) {
2184 result.append("M");
2185 }
2186 }
2187 result.append("\n");
2188 write(fd, result.string(), result.length());
2189 result.clear();
2190
Eric Laurent81784c32012-11-19 14:55:58 -08002191 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2192 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002193 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002194 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002195
2196 size_t numtracks = mTracks.size();
2197 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002198 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002199 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002200 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002201 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002202 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002203 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002204 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002205 for (size_t i = 0; i < numtracks; ++i) {
2206 sp<Track> track = mTracks[i];
2207 if (track != 0) {
2208 bool active = mActiveTracks.indexOf(track) >= 0;
2209 if (active) {
2210 numactiveseen++;
2211 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002212 result.append(prefix);
2213 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002214 }
2215 }
2216 } else {
2217 result.append("\n");
2218 }
2219 if (numactiveseen != numactive) {
2220 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002221 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002222 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002223 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002224 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002225 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002226 sp<Track> track = mActiveTracks[i];
2227 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002228 result.append(prefix);
2229 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002230 }
2231 }
2232 }
2233
2234 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002235}
2236
Andy Hung61589a42021-06-16 09:37:53 -07002237void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002238{
Andy Hung04cb8f72020-03-20 13:44:33 -07002239 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002240 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002241 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2242 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002243 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2244 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2245 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2246 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002247 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002248 dprintf(fd, " Total writes: %d\n", mNumWrites);
2249 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2250 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2251 dprintf(fd, " Suspend count: %d\n", mSuspended);
2252 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2253 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2254 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2255 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002256 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002257 AudioStreamOut *output = mOutput;
2258 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002259 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002260 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002261 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2262 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2263 if (mPipeSink.get() != nullptr) {
2264 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2265 }
2266 if (output != nullptr) {
2267 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002268 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002269 }
Eric Laurent81784c32012-11-19 14:55:58 -08002270}
2271
Eric Laurent81784c32012-11-19 14:55:58 -08002272// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2273sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2274 const sp<AudioFlinger::Client>& client,
2275 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002276 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002277 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002278 audio_format_t format,
2279 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002280 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002281 size_t *pNotificationFrameCount,
2282 uint32_t notificationsPerBuffer,
2283 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002284 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002285 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002286 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002287 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002288 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002289 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002290 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002291 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002292 const sp<media::IAudioTrackCallback>& callback,
2293 bool isSpatialized)
Eric Laurent81784c32012-11-19 14:55:58 -08002294{
Glenn Kasten74935e42013-12-19 08:56:45 -08002295 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002296 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002297 sp<Track> track;
2298 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002299 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002300 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002301 uint32_t sampleRate;
2302
2303 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2304 lStatus = BAD_VALUE;
2305 goto Exit;
2306 }
Eric Laurent21da6472017-11-09 16:29:26 -08002307
2308 if (*pSampleRate == 0) {
2309 *pSampleRate = mSampleRate;
2310 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002311 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002312
2313 // special case for FAST flag considered OK if fast mixer is present
2314 if (hasFastMixer()) {
2315 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2316 }
2317
2318 // Check if requested flags are compatible with output stream flags
2319 if ((*flags & outputFlags) != *flags) {
2320 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2321 *flags, outputFlags);
2322 *flags = (audio_output_flags_t)(*flags & outputFlags);
2323 }
Eric Laurent81784c32012-11-19 14:55:58 -08002324
Eric Laurent81784c32012-11-19 14:55:58 -08002325 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002326 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002327 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002328 // PCM data
2329 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002330 // TODO: extract as a data library function that checks that a computationally
2331 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002332 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002333 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2334 (channelMask == AUDIO_CHANNEL_OUT_MONO
2335 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002336 // hardware sample rate
2337 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002338 // normal mixer has an associated fast mixer
2339 hasFastMixer() &&
2340 // there are sufficient fast track slots available
2341 (mFastTrackAvailMask != 0)
2342 // FIXME test that MixerThread for this fast track has a capable output HAL
2343 // FIXME add a permission test also?
2344 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002345 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2346 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002347 // read the fast track multiplier property the first time it is needed
2348 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2349 if (ok != 0) {
2350 ALOGE("%s pthread_once failed: %d", __func__, ok);
2351 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002352 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002353 }
Eric Laurent4c415062016-06-17 16:14:16 -07002354
2355 // check compatibility with audio effects.
2356 { // scope for mLock
2357 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002358 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002359 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002360 AUDIO_SESSION_OUTPUT_STAGE,
2361 AUDIO_SESSION_OUTPUT_MIX,
2362 sessionId,
2363 }) {
2364 sp<EffectChain> chain = getEffectChain_l(session);
2365 if (chain.get() != nullptr) {
2366 audio_output_flags_t old = *flags;
2367 chain->checkOutputFlagCompatibility(flags);
2368 if (old != *flags) {
2369 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2370 (int)session, (int)old, (int)*flags);
2371 }
Eric Laurent4c415062016-06-17 16:14:16 -07002372 }
2373 }
2374 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002375 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002376 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2377 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002378 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002379 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002380 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002381 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002382 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002383 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002384 audio_is_linear_pcm(format), channelMask, sampleRate,
2385 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002386 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002387 }
2388 }
Eric Laurent21da6472017-11-09 16:29:26 -08002389
2390 if (!audio_has_proportional_frames(format)) {
2391 if (sharedBuffer != 0) {
2392 // Same comment as below about ignoring frameCount parameter for set()
2393 frameCount = sharedBuffer->size();
2394 } else if (frameCount == 0) {
2395 frameCount = mNormalFrameCount;
2396 }
2397 if (notificationFrameCount != frameCount) {
2398 notificationFrameCount = frameCount;
2399 }
2400 } else if (sharedBuffer != 0) {
2401 // FIXME: Ensure client side memory buffers need
2402 // not have additional alignment beyond sample
2403 // (e.g. 16 bit stereo accessed as 32 bit frame).
2404 size_t alignment = audio_bytes_per_sample(format);
2405 if (alignment & 1) {
2406 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2407 alignment = 1;
2408 }
2409 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2410 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2411 if (channelCount > 1) {
2412 // More than 2 channels does not require stronger alignment than stereo
2413 alignment <<= 1;
2414 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002415 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002416 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002417 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002418 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002419 goto Exit;
2420 }
Eric Laurent21da6472017-11-09 16:29:26 -08002421
2422 // When initializing a shared buffer AudioTrack via constructors,
2423 // there's no frameCount parameter.
2424 // But when initializing a shared buffer AudioTrack via set(),
2425 // there _is_ a frameCount parameter. We silently ignore it.
2426 frameCount = sharedBuffer->size() / frameSize;
2427 } else {
2428 size_t minFrameCount = 0;
2429 // For fast tracks we try to respect the application's request for notifications per buffer.
2430 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2431 if (notificationsPerBuffer > 0) {
2432 // Avoid possible arithmetic overflow during multiplication.
2433 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2434 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2435 notificationsPerBuffer, mFrameCount);
2436 } else {
2437 minFrameCount = mFrameCount * notificationsPerBuffer;
2438 }
2439 }
2440 } else {
2441 // For normal PCM streaming tracks, update minimum frame count.
2442 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2443 // cover audio hardware latency.
2444 // This is probably too conservative, but legacy application code may depend on it.
2445 // If you change this calculation, also review the start threshold which is related.
2446 uint32_t latencyMs = latency_l();
2447 if (latencyMs == 0) {
2448 ALOGE("Error when retrieving output stream latency");
2449 lStatus = UNKNOWN_ERROR;
2450 goto Exit;
2451 }
2452
2453 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2454 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2455
Eric Laurent81784c32012-11-19 14:55:58 -08002456 }
Eric Laurent21da6472017-11-09 16:29:26 -08002457 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002458 frameCount = minFrameCount;
2459 }
Eric Laurent81784c32012-11-19 14:55:58 -08002460 }
Eric Laurent21da6472017-11-09 16:29:26 -08002461
2462 // Make sure that application is notified with sufficient margin before underrun.
2463 // The client can divide the AudioTrack buffer into sub-buffers,
2464 // and expresses its desire to server as the notification frame count.
2465 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2466 size_t maxNotificationFrames;
2467 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2468 // notify every HAL buffer, regardless of the size of the track buffer
2469 maxNotificationFrames = mFrameCount;
2470 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002471 // Triple buffer the notification period for a triple buffered mixer period;
2472 // otherwise, double buffering for the notification period is fine.
2473 //
2474 // TODO: This should be moved to AudioTrack to modify the notification period
2475 // on AudioTrack::setBufferSizeInFrames() changes.
2476 const int nBuffering =
2477 (uint64_t{frameCount} * mSampleRate)
2478 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2479
Eric Laurent21da6472017-11-09 16:29:26 -08002480 maxNotificationFrames = frameCount / nBuffering;
2481 // If client requested a fast track but this was denied, then use the smaller maximum.
2482 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2483 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2484 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2485 maxNotificationFrames = maxNotificationFramesFastDenied;
2486 }
2487 }
2488 }
2489 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2490 if (notificationFrameCount == 0) {
2491 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2492 maxNotificationFrames, frameCount);
2493 } else {
2494 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2495 notificationFrameCount, maxNotificationFrames, frameCount);
2496 }
2497 notificationFrameCount = maxNotificationFrames;
2498 }
2499 }
2500
Glenn Kasten74935e42013-12-19 08:56:45 -08002501 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002502 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002503
Glenn Kastenc3df8382014-03-13 15:05:25 -07002504 switch (mType) {
2505
2506 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002507 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002508 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002509 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2510 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002511 sampleRate, format, channelMask, mOutput, mFormat);
2512 lStatus = BAD_VALUE;
2513 goto Exit;
2514 }
2515 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002516 break;
2517
2518 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002519 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002520 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2521 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002522 sampleRate, format, channelMask, mOutput, mFormat);
2523 lStatus = BAD_VALUE;
2524 goto Exit;
2525 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002526 break;
2527
2528 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002529 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002530 ALOGE("createTrack_l() Bad parameter: format %#x \""
2531 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002532 format, mOutput, mFormat);
2533 lStatus = BAD_VALUE;
2534 goto Exit;
2535 }
Andy Hungcd044842014-08-07 11:04:34 -07002536 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002537 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2538 lStatus = BAD_VALUE;
2539 goto Exit;
2540 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002541 break;
2542
Eric Laurent81784c32012-11-19 14:55:58 -08002543 }
2544
2545 lStatus = initCheck();
2546 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002547 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002548 goto Exit;
2549 }
2550
2551 { // scope for mLock
2552 Mutex::Autolock _l(mLock);
2553
2554 // all tracks in same audio session must share the same routing strategy otherwise
2555 // conflicts will happen when tracks are moved from one output to another by audio policy
2556 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002557 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002558 for (size_t i = 0; i < mTracks.size(); ++i) {
2559 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002560 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002561 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002562 if (sessionId == t->sessionId() && strategy != actual) {
2563 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2564 strategy, actual);
2565 lStatus = BAD_VALUE;
2566 goto Exit;
2567 }
2568 }
2569 }
2570
yucliuc9c49cd2020-07-13 16:25:21 -07002571 // Set DIRECT flag if current thread is DirectOutputThread. This can
2572 // happen when the playback is rerouted to direct output thread by
2573 // dynamic audio policy.
2574 // Do NOT report the flag changes back to client, since the client
2575 // doesn't explicitly request a direct flag.
2576 audio_output_flags_t trackFlags = *flags;
2577 if (mType == DIRECT) {
2578 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2579 }
2580
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002581 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002582 channelMask, frameCount,
2583 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002584 sessionId, creatorPid, attributionSource, trackFlags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002585 TrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
2586 speed, isSpatialized);
Glenn Kasten03003332013-08-06 15:40:54 -07002587
Glenn Kasten03003332013-08-06 15:40:54 -07002588 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2589 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002590 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002591 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002592 goto Exit;
2593 }
2594 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002595 {
2596 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2597 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002598 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002599 }
2600 }
Eric Laurent81784c32012-11-19 14:55:58 -08002601
2602 sp<EffectChain> chain = getEffectChain_l(sessionId);
2603 if (chain != 0) {
2604 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2605 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002606 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002607 chain->incTrackCnt();
2608 }
2609
Eric Laurent05067782016-06-01 18:27:28 -07002610 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002611 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2612 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2613 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002614 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002615 }
2616 }
2617
2618 lStatus = NO_ERROR;
2619
2620Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002621 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002622 return track;
2623}
2624
Andy Hung1bc088a2018-02-09 15:57:31 -08002625template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002626ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2627{
Andy Hungc0691382018-09-12 18:01:57 -07002628 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002629 const ssize_t index = mTracks.remove(track);
2630 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002631 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002632 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002633 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002634 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002635 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002636 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002637 }
2638 return index;
2639}
2640
Eric Laurent81784c32012-11-19 14:55:58 -08002641uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2642{
2643 return latency;
2644}
2645
2646uint32_t AudioFlinger::PlaybackThread::latency() const
2647{
2648 Mutex::Autolock _l(mLock);
2649 return latency_l();
2650}
2651uint32_t AudioFlinger::PlaybackThread::latency_l() const
2652{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002653 uint32_t latency;
2654 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2655 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002656 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002657 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002658}
2659
2660void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2661{
2662 Mutex::Autolock _l(mLock);
2663 // Don't apply master volume in SW if our HAL can do it for us.
2664 if (mOutput && mOutput->audioHwDev &&
2665 mOutput->audioHwDev->canSetMasterVolume()) {
2666 mMasterVolume = 1.0;
2667 } else {
2668 mMasterVolume = value;
2669 }
2670}
2671
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002672void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2673{
2674 mMasterBalance.store(balance);
2675}
2676
Eric Laurent81784c32012-11-19 14:55:58 -08002677void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2678{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002679 if (isDuplicating()) {
2680 return;
2681 }
Eric Laurent81784c32012-11-19 14:55:58 -08002682 Mutex::Autolock _l(mLock);
2683 // Don't apply master mute in SW if our HAL can do it for us.
2684 if (mOutput && mOutput->audioHwDev &&
2685 mOutput->audioHwDev->canSetMasterMute()) {
2686 mMasterMute = false;
2687 } else {
2688 mMasterMute = muted;
2689 }
2690}
2691
2692void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2693{
2694 Mutex::Autolock _l(mLock);
2695 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002696 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002697}
2698
2699void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2700{
2701 Mutex::Autolock _l(mLock);
2702 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002703 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002704}
2705
2706float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2707{
2708 Mutex::Autolock _l(mLock);
2709 return mStreamTypes[stream].volume;
2710}
2711
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002712void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2713{
2714 mOutput->stream->setVolume(left, right);
2715}
2716
Eric Laurent81784c32012-11-19 14:55:58 -08002717// addTrack_l() must be called with ThreadBase::mLock held
2718status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2719{
2720 status_t status = ALREADY_EXISTS;
2721
Eric Laurent81784c32012-11-19 14:55:58 -08002722 if (mActiveTracks.indexOf(track) < 0) {
2723 // the track is newly added, make sure it fills up all its
2724 // buffers before playing. This is to ensure the client will
2725 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002726 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002727 TrackBase::track_state state = track->mState;
2728 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002729 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002730 mLock.lock();
2731 // abort track was stopped/paused while we released the lock
2732 if (state != track->mState) {
2733 if (status == NO_ERROR) {
2734 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002735 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002736 mLock.lock();
2737 }
2738 return INVALID_OPERATION;
2739 }
2740 // abort if start is rejected by audio policy manager
2741 if (status != NO_ERROR) {
2742 return PERMISSION_DENIED;
2743 }
2744#ifdef ADD_BATTERY_DATA
2745 // to track the speaker usage
2746 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2747#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002748 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002749 }
2750
Eric Laurent51716182016-02-29 18:00:56 -08002751 // set retry count for buffer fill
2752 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002753 if (track->isStopping_1()) {
2754 track->mRetryCount = kMaxTrackStopRetriesOffload;
2755 } else {
2756 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2757 }
2758 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002759 } else {
2760 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002761 track->mFillingUpStatus =
2762 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002763 }
2764
jiabineb3bda02020-06-30 14:07:03 -07002765 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2766 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2767 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2768 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002769 // Unlock due to VibratorService will lock for this call and will
2770 // call Tracks.mute/unmute which also require thread's lock.
2771 mLock.unlock();
2772 const int intensity = AudioFlinger::onExternalVibrationStart(
2773 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002774 std::optional<media::AudioVibratorInfo> vibratorInfo;
2775 {
2776 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2777 // used to play this track.
2778 Mutex::Autolock _l(mAudioFlinger->mLock);
2779 vibratorInfo = std::move(mAudioFlinger->getDefaultVibratorInfo_l());
2780 }
jiabin57303cc2018-12-18 15:45:57 -08002781 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002782 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
Lais Andradebc3f37a2021-07-02 00:13:19 +01002783 if (vibratorInfo) {
2784 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2785 }
2786
jiabin57303cc2018-12-18 15:45:57 -08002787 // Haptic playback should be enabled by vibrator service.
2788 if (track->getHapticPlaybackEnabled()) {
2789 // Disable haptic playback of all active track to ensure only
2790 // one track playing haptic if current track should play haptic.
2791 for (const auto &t : mActiveTracks) {
2792 t->setHapticPlaybackEnabled(false);
2793 }
jiabin245cdd92018-12-07 17:55:15 -08002794 }
jiabine70bc7f2020-06-30 22:07:55 -07002795
2796 // Set haptic intensity for effect
2797 if (chain != nullptr) {
2798 chain->setHapticIntensity_l(track->id(), intensity);
2799 }
jiabin245cdd92018-12-07 17:55:15 -08002800 }
2801
Eric Laurent81784c32012-11-19 14:55:58 -08002802 track->mResetDone = false;
Andy Hung59de4262021-06-14 10:53:54 -07002803 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002804 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002805 if (chain != 0) {
2806 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2807 track->sessionId());
2808 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002809 }
2810
Andy Hungc2b11cb2020-04-22 09:04:01 -07002811 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002812 status = NO_ERROR;
2813 }
2814
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002815 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002816 return status;
2817}
2818
Eric Laurentbfb1b832013-01-07 09:53:42 -08002819bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002820{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002821 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002822 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002823 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2824 track->mState = TrackBase::STOPPED;
2825 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002826 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002827 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002828 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002829 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002830
2831 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002832}
2833
2834void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2835{
2836 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002837
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002838 String8 result;
2839 track->appendDump(result, false /* active */);
2840 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002841
Eric Laurent81784c32012-11-19 14:55:58 -08002842 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002843 {
2844 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2845 mAudioTrackCallbacks.erase(track);
2846 }
Eric Laurent81784c32012-11-19 14:55:58 -08002847 if (track->isFastTrack()) {
2848 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002849 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002850 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2851 mFastTrackAvailMask |= 1 << index;
2852 // redundant as track is about to be destroyed, for dumpsys only
2853 track->mFastIndex = -1;
2854 }
2855 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2856 if (chain != 0) {
2857 chain->decTrackCnt();
2858 }
2859}
2860
2861String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2862{
Eric Laurent81784c32012-11-19 14:55:58 -08002863 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002864 String8 out_s8;
2865 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2866 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002867 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002868 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002869}
2870
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002871status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2872 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002873 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002874 return NO_INIT;
2875 }
2876 return mOutput->stream->selectPresentation(presentationId, programId);
2877}
2878
Mikhail Naganov88536df2021-07-26 17:30:29 -07002879void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002880 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002881 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07002882 sp<AudioIoDescriptor> desc;
2883 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002884 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002885 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002886 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002887 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002888 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
2889 mSampleRate, mFormat, mChannelMask,
2890 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
2891 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08002892 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002893 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002894 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07002895 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002896 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002897 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002898 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08002899 break;
2900 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002901 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002902}
2903
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002904void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002905{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002906 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002907}
2908
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002909void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002910{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002911 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002912}
2913
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002914void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002915{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002916 mCallbackThread->setAsyncError();
2917}
2918
jiabinf6eb4c32020-02-25 14:06:25 -08002919void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2920 const std::basic_string<uint8_t>& metadataBs)
2921{
Kuowei Li9e2f6162022-11-23 16:25:26 +08002922 wp<AudioFlinger::PlaybackThread> weakPointerThis = this;
2923 std::thread([this, metadataBs, weakPointerThis]() {
2924 sp<AudioFlinger::PlaybackThread> playbackThread = weakPointerThis.promote();
2925 if (playbackThread == nullptr) {
2926 ALOGW("PlaybackThread was destroyed, skip codec format change event");
2927 return;
2928 }
2929
jiabinf6eb4c32020-02-25 14:06:25 -08002930 audio_utils::metadata::Data metadata =
2931 audio_utils::metadata::dataFromByteString(metadataBs);
2932 if (metadata.empty()) {
2933 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2934 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2935 (int)metadataBs.size());
2936 return;
2937 }
2938
2939 audio_utils::metadata::ByteString metaDataStr =
2940 audio_utils::metadata::byteStringFromData(metadata);
2941 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2942 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002943 for (const auto& callbackPair : mAudioTrackCallbacks) {
2944 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002945 }
2946 }).detach();
2947}
2948
Eric Laurent3b4529e2013-09-05 18:09:19 -07002949void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002950{
2951 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002952 // reject out of sequence requests
2953 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2954 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002955 mWaitWorkCV.signal();
2956 }
2957}
2958
Eric Laurent3b4529e2013-09-05 18:09:19 -07002959void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002960{
2961 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002962 // reject out of sequence requests
2963 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002964 // Register discontinuity when HW drain is completed because that can cause
2965 // the timestamp frame position to reset to 0 for direct and offload threads.
2966 // (Out of sequence requests are ignored, since the discontinuity would be handled
2967 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002968 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002969 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002970 mWaitWorkCV.signal();
2971 }
2972}
2973
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002974void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002975{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002976 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002977 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2978 mSampleRate = audioConfig.sample_rate;
2979 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002980 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002981 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002982 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002983 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07002984 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2985 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002986 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02002987
2988 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
2989 mMixerChannelMask = mChannelMask;
2990 }
2991
Andy Hunge5412692014-05-16 11:25:07 -07002992 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002993 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002994
Eric Laurentf1f22e72021-07-13 14:04:14 +02002995 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
2996
Phil Burkca5e6142015-07-14 09:42:29 -07002997 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002998 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002999 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003000 // Get format from the shim, which will be different than the HAL format
3001 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003002 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003003 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003004 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003005 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02003006 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003007 LOG_FATAL("HAL format %#x not supported for mixed output",
3008 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003009 }
Phil Burk062e67a2015-02-11 13:40:50 -08003010 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003011 result = mOutput->stream->getBufferSize(&mBufferSize);
3012 LOG_ALWAYS_FATAL_IF(result != OK,
3013 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003014 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003015 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003016 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003017 mFrameCount);
3018 }
3019
Eric Laurentd1f69b02014-12-15 14:33:13 -08003020 mHwSupportsPause = false;
3021 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003022 bool supportsPause = false, supportsResume = false;
3023 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3024 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003025 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003026 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003027 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003028 } else if (supportsResume) {
3029 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003030 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003031 }
3032 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003033 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3034 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3035 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003036
Andy Hungfbfc3952015-01-15 13:33:51 -08003037 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3038 // For best precision, we use float instead of the associated output
3039 // device format (typically PCM 16 bit).
3040
3041 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3042 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3043 mBufferSize = mFrameSize * mFrameCount;
3044
3045 // TODO: We currently use the associated output device channel mask and sample rate.
3046 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3047 // (if a valid mask) to avoid premature downmix.
3048 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3049 // instead of the output device sample rate to avoid loss of high frequency information.
3050 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3051 }
3052
Andy Hung09a50072014-02-27 14:30:47 -08003053 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003054 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003055 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003056 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3057 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003058 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3059 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003060
Eric Laurent81784c32012-11-19 14:55:58 -08003061 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3062 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3063 maxNormalFrameCount = maxNormalFrameCount & ~15;
3064 if (maxNormalFrameCount < minNormalFrameCount) {
3065 maxNormalFrameCount = minNormalFrameCount;
3066 }
3067 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3068 if (multiplier <= 1.0) {
3069 multiplier = 1.0;
3070 } else if (multiplier <= 2.0) {
3071 if (2 * mFrameCount <= maxNormalFrameCount) {
3072 multiplier = 2.0;
3073 } else {
3074 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3075 }
3076 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003077 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003078 }
3079 }
3080 mNormalFrameCount = multiplier * mFrameCount;
3081 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003082 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003083 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3084 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003085 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003086 mNormalFrameCount);
3087
Andy Hung08fb1742015-05-31 23:22:10 -07003088 // Check if we want to throttle the processing to no more than 2x normal rate
3089 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003090 mThreadThrottleTimeMs = 0;
3091 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003092 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3093
Andy Hung010a1a12014-03-13 13:57:33 -07003094 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3095 // Originally this was int16_t[] array, need to remove legacy implications.
3096 free(mSinkBuffer);
3097 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003098
Andy Hung5b10a202014-03-13 13:59:29 -07003099 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3100 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3101 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003102 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003103
Andy Hung69aed5f2014-02-25 17:24:40 -08003104 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3105 // drives the output.
3106 free(mMixerBuffer);
3107 mMixerBuffer = NULL;
3108 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003109 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003110 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003111 * audio_bytes_per_sample(mMixerBufferFormat);
3112 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3113 }
Andy Hung98ef9782014-03-04 14:46:50 -08003114 free(mEffectBuffer);
3115 mEffectBuffer = NULL;
3116 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07003117 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003118 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003119 * audio_bytes_per_sample(mEffectBufferFormat);
3120 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3121 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003122
Eric Laurentb62d0362021-10-26 17:40:18 +02003123 if (mType == SPATIALIZER) {
3124 free(mPostSpatializerBuffer);
3125 mPostSpatializerBuffer = nullptr;
3126 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3127 * audio_bytes_per_sample(mEffectBufferFormat);
3128 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3129 }
3130
Mikhail Naganov55773032020-10-01 15:08:13 -07003131 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3132 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003133 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3134 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003135 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003136
Eric Laurent81784c32012-11-19 14:55:58 -08003137 // force reconfiguration of effect chains and engines to take new buffer size and audio
3138 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003139 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003140 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3141 // matter.
3142 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
3143 Vector< sp<EffectChain> > effectChains = mEffectChains;
3144 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07003145 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
3146 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003147 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003148
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003149 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003150 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003151 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3152 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3153 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3154 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3155 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3156 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3157 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3158 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3159 (int32_t)mHapticChannelMask)
3160 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3161 (int32_t)mHapticChannelCount)
3162 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3163 formatToString(mHALFormat).c_str())
3164 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3165 (int32_t)mFrameCount) // sic - added HAL
3166 ;
3167 uint32_t latencyMs;
3168 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3169 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3170 }
3171 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003172}
3173
Kevin Rocard069c2712018-03-29 19:09:14 -07003174void AudioFlinger::PlaybackThread::updateMetadata_l()
3175{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003176 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Kevin Rocard12381092018-04-11 09:19:59 -07003177 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003178 }
3179 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003180 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07003181 for (const sp<Track> &track : mActiveTracks) {
3182 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003183 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003184 }
Kevin Rocard12381092018-04-11 09:19:59 -07003185 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00003186}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003187
Kevin Rocard12381092018-04-11 09:19:59 -07003188void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
3189 const StreamOutHalInterface::SourceMetadata& metadata)
3190{
3191 mOutput->stream->updateSourceMetadata(metadata);
3192};
3193
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003194status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08003195{
3196 if (halFrames == NULL || dspFrames == NULL) {
3197 return BAD_VALUE;
3198 }
3199 Mutex::Autolock _l(mLock);
3200 if (initCheck() != NO_ERROR) {
3201 return INVALID_OPERATION;
3202 }
Andy Hung818e7a32016-02-16 18:08:07 -08003203 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003204 *halFrames = framesWritten;
3205
3206 if (isSuspended()) {
3207 // return an estimation of rendered frames when the output is suspended
3208 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003209 *dspFrames = (uint32_t)
3210 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003211 return NO_ERROR;
3212 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003213 status_t status;
3214 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003215 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003216 *dspFrames = (size_t)frames;
3217 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003218 }
3219}
3220
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003221product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003222{
3223 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3224 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3225 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003226 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003227 }
3228 for (size_t i = 0; i < mTracks.size(); i++) {
3229 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003230 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003231 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003232 }
3233 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003234 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003235}
3236
3237
Phil Burk062e67a2015-02-11 13:40:50 -08003238AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003239{
3240 Mutex::Autolock _l(mLock);
3241 return mOutput;
3242}
3243
Phil Burk062e67a2015-02-11 13:40:50 -08003244AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003245{
3246 Mutex::Autolock _l(mLock);
3247 AudioStreamOut *output = mOutput;
3248 mOutput = NULL;
3249 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3250 // must push a NULL and wait for ack
3251 mOutputSink.clear();
3252 mPipeSink.clear();
3253 mNormalSink.clear();
3254 return output;
3255}
3256
3257// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003258sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003259{
3260 if (mOutput == NULL) {
3261 return NULL;
3262 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003263 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003264}
3265
3266uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3267{
3268 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3269}
3270
3271status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3272{
3273 if (!isValidSyncEvent(event)) {
3274 return BAD_VALUE;
3275 }
3276
3277 Mutex::Autolock _l(mLock);
3278
3279 for (size_t i = 0; i < mTracks.size(); ++i) {
3280 sp<Track> track = mTracks[i];
3281 if (event->triggerSession() == track->sessionId()) {
3282 (void) track->setSyncEvent(event);
3283 return NO_ERROR;
3284 }
3285 }
3286
3287 return NAME_NOT_FOUND;
3288}
3289
3290bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3291{
3292 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3293}
3294
3295void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
Jing Mike537412f2023-03-12 11:01:47 +08003296 [[maybe_unused]] const Vector< sp<Track> >& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003297{
Andy Hungfe726a62018-09-27 15:17:25 -07003298 // Miscellaneous track cleanup when removed from the active list,
3299 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003300#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003301 for (const auto& track : tracksToRemove) {
3302 if (track->isExternalTrack()) {
3303 // to track the speaker usage
3304 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003305 }
3306 }
Andy Hungfe726a62018-09-27 15:17:25 -07003307#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003308}
3309
3310void AudioFlinger::PlaybackThread::checkSilentMode_l()
3311{
3312 if (!mMasterMute) {
3313 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003314 if (mOutDeviceTypeAddrs.empty()) {
3315 ALOGD("ro.audio.silent is ignored since no output device is set");
3316 return;
3317 }
jiabinc52b1ff2019-10-31 17:20:42 -07003318 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003319 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3320 return;
3321 }
Eric Laurent81784c32012-11-19 14:55:58 -08003322 if (property_get("ro.audio.silent", value, "0") > 0) {
3323 char *endptr;
3324 unsigned long ul = strtoul(value, &endptr, 0);
3325 if (*endptr == '\0' && ul != 0) {
3326 ALOGD("Silence is golden");
3327 // The setprop command will not allow a property to be changed after
3328 // the first time it is set, so we don't have to worry about un-muting.
3329 setMasterMute_l(true);
3330 }
3331 }
3332 }
3333}
3334
3335// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003336ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003337{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003338 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003339 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003340 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003341 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003342
3343 // If an NBAIO sink is present, use it to write the normal mixer's submix
3344 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003345
Andy Hung010a1a12014-03-13 13:57:33 -07003346 const size_t count = mBytesRemaining / mFrameSize;
3347
Simon Wilson2d590962012-11-29 15:18:50 -08003348 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003349 // update the setpoint when AudioFlinger::mScreenState changes
3350 uint32_t screenState = AudioFlinger::mScreenState;
3351 if (screenState != mScreenState) {
3352 mScreenState = screenState;
3353 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3354 if (pipe != NULL) {
3355 pipe->setAvgFrames((mScreenState & 1) ?
3356 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3357 }
3358 }
Andy Hung010a1a12014-03-13 13:57:33 -07003359 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003360 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003361 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003362 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003363#ifdef TEE_SINK
3364 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3365#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003366 } else {
3367 bytesWritten = framesWritten;
3368 }
3369 // otherwise use the HAL / AudioStreamOut directly
3370 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003371 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003372
Eric Laurentbfb1b832013-01-07 09:53:42 -08003373 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003374 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3375 mWriteAckSequence += 2;
3376 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003377 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003378 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003379 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003380 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003381 // FIXME We should have an implementation of timestamps for direct output threads.
3382 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003383 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003384 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003385
Eric Laurentbfb1b832013-01-07 09:53:42 -08003386 if (mUseAsyncWrite &&
3387 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3388 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003389 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003390 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003391 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003392 }
Eric Laurent81784c32012-11-19 14:55:58 -08003393 }
3394
Eric Laurent81784c32012-11-19 14:55:58 -08003395 mNumWrites++;
3396 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003397 if (mStandby) {
3398 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003399 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003400 mStandby = false;
3401 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003402 return bytesWritten;
3403}
3404
3405void AudioFlinger::PlaybackThread::threadLoop_drain()
3406{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003407 bool supportsDrain = false;
3408 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003409 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3410 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003411 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3412 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003413 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003414 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003415 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003416 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003417 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003418 }
3419}
3420
3421void AudioFlinger::PlaybackThread::threadLoop_exit()
3422{
Eric Laurent275e8e92014-11-30 15:14:47 -08003423 {
3424 Mutex::Autolock _l(mLock);
3425 for (size_t i = 0; i < mTracks.size(); i++) {
3426 sp<Track> track = mTracks[i];
3427 track->invalidate();
3428 }
Andy Hungdae27702016-10-31 14:01:16 -07003429 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3430 // After we exit there are no more track changes sent to BatteryNotifier
3431 // because that requires an active threadLoop.
3432 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3433 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003434 }
Eric Laurent81784c32012-11-19 14:55:58 -08003435}
3436
3437/*
3438The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003439 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003440 - mActiveSleepTimeUs from activeSleepTimeUs()
3441 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003442 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3443 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003444 - maxPeriod from frame count and sample rate (MIXER only)
3445
3446The parameters that affect these derived values are:
3447 - frame count
3448 - frame size
3449 - sample rate
3450 - device type: A2DP or not
3451 - device latency
3452 - format: PCM or not
3453 - active sleep time
3454 - idle sleep time
3455*/
3456
3457void AudioFlinger::PlaybackThread::cacheParameters_l()
3458{
Andy Hung25c2dac2014-02-27 14:56:00 -08003459 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003460 mActiveSleepTimeUs = activeSleepTimeUs();
3461 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003462
3463 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3464 // truncating audio when going to standby.
3465 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003466 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003467 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3468 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3469 }
3470 }
Eric Laurent81784c32012-11-19 14:55:58 -08003471}
3472
Eric Laurent13084622016-05-17 10:51:49 -07003473bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003474{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003475 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003476 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003477 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003478 size_t size = mTracks.size();
3479 for (size_t i = 0; i < size; i++) {
3480 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003481 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003482 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003483 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003484 }
3485 }
Eric Laurent13084622016-05-17 10:51:49 -07003486 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003487}
3488
Haynes Mathew George05317d22016-05-03 16:34:26 -07003489void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3490{
3491 Mutex::Autolock _l(mLock);
3492 invalidateTracks_l(streamType);
3493}
3494
jiabinf042b9b2021-05-07 23:46:28 +00003495// getTrackById_l must be called with holding thread lock
3496AudioFlinger::PlaybackThread::Track* AudioFlinger::PlaybackThread::getTrackById_l(
3497 audio_port_handle_t trackPortId) {
3498 for (size_t i = 0; i < mTracks.size(); i++) {
3499 if (mTracks[i]->portId() == trackPortId) {
3500 return mTracks[i].get();
3501 }
3502 }
3503 return nullptr;
3504}
3505
Eric Laurent81784c32012-11-19 14:55:58 -08003506status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3507{
Glenn Kastend848eb42016-03-08 13:42:11 -08003508 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003509 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003510 effect_buffer_t *buffer = nullptr; // only used for non global sessions
3511
Andy Hungd3639922022-04-28 18:00:49 -07003512 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003513 if (!audio_is_global_session(session)) {
3514 // player sessions on a spatializer output will use a dedicated input buffer and
3515 // will either output multi channel to mEffectBuffer if the track is spatilaized
3516 // or stereo to mPostSpatializerBuffer if not spatialized.
3517 uint32_t channelMask;
3518 bool isSessionSpatialized =
3519 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3520 if (isSessionSpatialized) {
3521 channelMask = mMixerChannelMask;
3522 } else {
3523 channelMask = mChannelMask;
3524 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003525 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003526 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003527 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003528 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003529 &halInBuffer);
3530 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003531
3532 result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3533 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3534 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3535 &halOutBuffer);
3536 if (result != OK) return result;
3537
rago94a1ee82017-07-21 15:11:02 -07003538#ifdef FLOAT_EFFECT_CHAIN
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003539 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
rago94a1ee82017-07-21 15:11:02 -07003540#else
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003541 buffer = halInBuffer ? halInBuffer->audioBuffer()->s16 : buffer;
rago94a1ee82017-07-21 15:11:02 -07003542#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003543 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3544 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003545 } else {
3546 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3547 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3548 // mPostSpatializerBuffer as output buffer
3549 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
3550 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3551 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3552 if (result != OK) return result;
3553 result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3554 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3555 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003556
Eric Laurentb62d0362021-10-26 17:40:18 +02003557 if (session == AUDIO_SESSION_DEVICE) {
3558 halInBuffer = halOutBuffer;
3559 }
3560 }
3561 } else {
3562 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3563 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3564 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3565 &halInBuffer);
3566 if (result != OK) return result;
3567 halOutBuffer = halInBuffer;
3568 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3569 if (!audio_is_global_session(session)) {
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003570 buffer = halInBuffer ? reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData())
3571 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003572 // Only one effect chain can be present in direct output thread and it uses
3573 // the sink buffer as input
3574 if (mType != DIRECT) {
3575 size_t numSamples = mNormalFrameCount
3576 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3577 + mHapticChannelCount);
3578 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
3579 numSamples * sizeof(effect_buffer_t),
3580 &halInBuffer);
3581 if (result != OK) return result;
3582#ifdef FLOAT_EFFECT_CHAIN
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003583 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003584#else
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003585 buffer = halInBuffer ? halInBuffer->audioBuffer()->s16 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003586#endif
3587 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3588 buffer, session);
3589 }
3590 }
3591 }
3592
3593 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003594 // Attach all tracks with same session ID to this chain.
3595 for (size_t i = 0; i < mTracks.size(); ++i) {
3596 sp<Track> track = mTracks[i];
3597 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003598 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3599 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003600 track->setMainBuffer(buffer);
3601 chain->incTrackCnt();
3602 }
3603 }
3604
3605 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003606 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003607 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003608 ALOGV("addEffectChain_l() activating track %p on session %d",
3609 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003610 chain->incActiveTrackCnt();
3611 }
3612 }
3613 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003614
Eric Laurentaaa44472014-09-12 17:41:50 -07003615 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003616 chain->setInBuffer(halInBuffer);
3617 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003618 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3619 // chains list in order to be processed last as it contains output device effects.
3620 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3621 // processing effects specific to an output stream before effects applied to all streams
3622 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003623 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3624 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003625 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003626 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003627 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003628 // Effect chain for other sessions are inserted at beginning of effect
3629 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003630 // sessions is not important.
3631 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003632 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3633 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003634 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003635 size_t size = mEffectChains.size();
3636 size_t i = 0;
3637 for (i = 0; i < size; i++) {
3638 if (mEffectChains[i]->sessionId() < session) {
3639 break;
3640 }
3641 }
3642 mEffectChains.insertAt(chain, i);
3643 checkSuspendOnAddEffectChain_l(chain);
3644
3645 return NO_ERROR;
3646}
3647
3648size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3649{
Glenn Kastend848eb42016-03-08 13:42:11 -08003650 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003651
3652 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3653
3654 for (size_t i = 0; i < mEffectChains.size(); i++) {
3655 if (chain == mEffectChains[i]) {
3656 mEffectChains.removeAt(i);
3657 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003658 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003659 if (session == track->sessionId()) {
3660 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3661 chain.get(), session);
3662 chain->decActiveTrackCnt();
3663 }
3664 }
3665
3666 // detach all tracks with same session ID from this chain
3667 for (size_t i = 0; i < mTracks.size(); ++i) {
3668 sp<Track> track = mTracks[i];
3669 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003670 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003671 chain->decTrackCnt();
3672 }
3673 }
3674 break;
3675 }
3676 }
3677 return mEffectChains.size();
3678}
3679
3680status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003681 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003682{
3683 Mutex::Autolock _l(mLock);
3684 return attachAuxEffect_l(track, EffectId);
3685}
3686
3687status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003688 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003689{
3690 status_t status = NO_ERROR;
3691
3692 if (EffectId == 0) {
3693 track->setAuxBuffer(0, NULL);
3694 } else {
3695 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3696 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3697 if (effect != 0) {
3698 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3699 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3700 } else {
3701 status = INVALID_OPERATION;
3702 }
3703 } else {
3704 status = BAD_VALUE;
3705 }
3706 }
3707 return status;
3708}
3709
3710void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3711{
3712 for (size_t i = 0; i < mTracks.size(); ++i) {
3713 sp<Track> track = mTracks[i];
3714 if (track->auxEffectId() == effectId) {
3715 attachAuxEffect_l(track, 0);
3716 }
3717 }
3718}
3719
3720bool AudioFlinger::PlaybackThread::threadLoop()
3721{
Glenn Kasten388d5712017-04-07 14:38:41 -07003722 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003723
Eric Laurent81784c32012-11-19 14:55:58 -08003724 Vector< sp<Track> > tracksToRemove;
3725
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003726 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003727 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003728
3729 // MIXER
3730 nsecs_t lastWarning = 0;
3731
3732 // DUPLICATING
3733 // FIXME could this be made local to while loop?
3734 writeFrames = 0;
3735
3736 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003737 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003738
Andy Hungd3639922022-04-28 18:00:49 -07003739 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003740 sleepTimeShift = 0;
3741 }
3742
3743 CpuStats cpuStats;
3744 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3745
3746 acquireWakeLock();
3747
Glenn Kasteneef598c2017-04-03 14:41:13 -07003748 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3749 // thread associated with this PlaybackThread.
3750 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3751 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003752 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3753 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003754 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003755 const char *logString = NULL;
3756
rago1bb90822017-05-02 18:31:48 -07003757 // Estimated time for next buffer to be written to hal. This is used only on
3758 // suspended mode (for now) to help schedule the wait time until next iteration.
3759 nsecs_t timeLoopNextNs = 0;
3760
Eric Laurent664539d2013-09-23 18:24:31 -07003761 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003762
Andy Hung2dbffc22018-08-08 18:50:41 -07003763 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003764
Eric Laurentb3f315a2021-07-13 15:09:05 +02003765 sendCheckOutputStageEffectsEvent();
3766
Andy Hung446f4df2019-02-21 12:26:41 -08003767 // loopCount is used for statistics and diagnostics.
3768 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003769 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003770 // Log merge requests are performed during AudioFlinger binder transactions, but
3771 // that does not cover audio playback. It's requested here for that reason.
3772 mAudioFlinger->requestLogMerge();
3773
Eric Laurent81784c32012-11-19 14:55:58 -08003774 cpuStats.sample(myName);
3775
3776 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003777 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003778 bool isHapticSessionSpatialized = false;
Andy Hungc1646382019-04-30 16:12:10 -07003779 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003780
Andy Hung2dbffc22018-08-08 18:50:41 -07003781 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3782 //
jiabinc52b1ff2019-10-31 17:20:42 -07003783 // Note: we access outDeviceTypes() outside of mLock.
3784 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003785 // Here, we try for the AF lock, but do not block on it as the latency
3786 // is more informational.
3787 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3788 std::vector<PatchPanel::SoftwarePatch> swPatches;
3789 double latencyMs;
3790 status_t status = INVALID_OPERATION;
3791 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3792 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3793 && swPatches.size() > 0) {
3794 status = swPatches[0].getLatencyMs_l(&latencyMs);
3795 downstreamPatchHandle = swPatches[0].getPatchHandle();
3796 }
3797 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003798 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003799 lastDownstreamPatchHandle = downstreamPatchHandle;
3800 }
3801 if (status == OK) {
3802 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003803 // latency of 5 seconds).
3804 const double minLatency = 0., maxLatency = 5000.;
3805 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003806 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003807 } else {
3808 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003809 if (latencyMs < minLatency) latencyMs = minLatency;
3810 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003811 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003812 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003813 }
3814 mAudioFlinger->mLock.unlock();
3815 }
3816 } else {
3817 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3818 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003819 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003820 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3821 }
3822 }
3823
Eric Laurentb3f315a2021-07-13 15:09:05 +02003824 if (mCheckOutputStageEffects.exchange(false)) {
3825 checkOutputStageEffects();
3826 }
3827
Eric Laurent81784c32012-11-19 14:55:58 -08003828 { // scope for mLock
3829
3830 Mutex::Autolock _l(mLock);
3831
Eric Laurent021cf962014-05-13 10:18:14 -07003832 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003833 if (mCheckOutputStageEffects.load()) {
3834 continue;
3835 }
Eric Laurent10351942014-05-08 18:49:52 -07003836
Glenn Kasteneef598c2017-04-03 14:41:13 -07003837 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003838 if (logString != NULL) {
3839 mNBLogWriter->logTimestamp();
3840 mNBLogWriter->log(logString);
3841 logString = NULL;
3842 }
3843
Dean Wheatley12473e92021-03-18 23:00:55 +11003844 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003845
Eric Laurent81784c32012-11-19 14:55:58 -08003846 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003847 if (mSignalPending) {
3848 // A signal was raised while we were unlocked
3849 mSignalPending = false;
3850 } else if (waitingAsyncCallback_l()) {
3851 if (exitPending()) {
3852 break;
3853 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003854 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003855 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003856 releaseWakeLock_l();
3857 released = true;
3858 }
Andy Hung10cbff12017-02-21 17:30:14 -08003859
3860 const int64_t waitNs = computeWaitTimeNs_l();
3861 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3862 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3863 if (status == TIMED_OUT) {
3864 mSignalPending = true; // if timeout recheck everything
3865 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003866 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003867 if (released) {
3868 acquireWakeLock_l();
3869 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003870 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3871 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003872
3873 continue;
3874 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003875 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003876 isSuspended()) {
3877 // put audio hardware into standby after short delay
3878 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003879
3880 threadLoop_standby();
3881
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003882 // This is where we go into standby
3883 if (!mStandby) {
3884 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003885 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003886 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07003887 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003888 }
Andy Hungd0979812019-02-21 15:51:44 -08003889 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003890 }
3891
Eric Tan39ec8d62018-07-24 09:49:29 -07003892 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003893 // we're about to wait, flush the binder command buffer
3894 IPCThreadState::self()->flushCommands();
3895
3896 clearOutputTracks();
3897
3898 if (exitPending()) {
3899 break;
3900 }
3901
3902 releaseWakeLock_l();
3903 // wait until we have something to do...
3904 ALOGV("%s going to sleep", myName.string());
3905 mWaitWorkCV.wait(mLock);
3906 ALOGV("%s waking up", myName.string());
3907 acquireWakeLock_l();
3908
3909 mMixerStatus = MIXER_IDLE;
3910 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3911 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003912 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003913 checkSilentMode_l();
3914
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003915 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3916 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07003917 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003918 sleepTimeShift = 0;
3919 }
3920
3921 continue;
3922 }
3923 }
Eric Laurent81784c32012-11-19 14:55:58 -08003924 // mMixerStatusIgnoringFastTracks is also updated internally
3925 mMixerStatus = prepareTracks_l(&tracksToRemove);
3926
Andy Hungdae27702016-10-31 14:01:16 -07003927 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003928
Kevin Rocard069c2712018-03-29 19:09:14 -07003929 updateMetadata_l();
3930
Eric Laurent81784c32012-11-19 14:55:58 -08003931 // prevent any changes in effect chain list and in each effect chain
3932 // during mixing and effect process as the audio buffers could be deleted
3933 // or modified if an effect is created or deleted
3934 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003935
3936 // Determine which session to pick up haptic data.
3937 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003938 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003939 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02003940 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07003941 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003942 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02003943 if (effectChain != nullptr
3944 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07003945 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02003946 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02003947 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07003948 break;
3949 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003950 if (activeHapticSessionId == AUDIO_SESSION_NONE
3951 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07003952 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02003953 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02003954 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07003955 }
3956 }
3957 }
3958
Andy Hungc1646382019-04-30 16:12:10 -07003959 // Acquire a local copy of active tracks with lock (release w/o lock).
3960 //
3961 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3962 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3963 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3964 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent6f9534f2022-05-03 18:15:04 +02003965
3966 setHalLatencyMode_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003967 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003968
Eric Laurentbfb1b832013-01-07 09:53:42 -08003969 if (mBytesRemaining == 0) {
3970 mCurrentWriteLength = 0;
3971 if (mMixerStatus == MIXER_TRACKS_READY) {
3972 // threadLoop_mix() sets mCurrentWriteLength
3973 threadLoop_mix();
3974 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3975 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003976 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003977 // must be written to HAL
3978 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003979 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003980 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003981
3982 // Tally underrun frames as we are inserting 0s here.
3983 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003984 if (track->mFillingUpStatus == Track::FS_ACTIVE
3985 && !track->isStopped()
3986 && !track->isPaused()
3987 && !track->isTerminated()) {
3988 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3989 __func__, track->id(), track->getTrackStateAsString(),
3990 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003991 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3992 }
3993 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003994 }
3995 }
Andy Hung98ef9782014-03-04 14:46:50 -08003996 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003997 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003998 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3999 // or mSinkBuffer (if there are no effects).
4000 //
4001 // This is done pre-effects computation; if effects change to
4002 // support higher precision, this needs to move.
4003 //
4004 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004005 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004006 uint32_t mixerChannelCount = mEffectBufferValid ?
4007 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
Andy Hung98ef9782014-03-04 14:46:50 -08004008 if (mMixerBufferValid) {
4009 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4010 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4011
David Li88ee0902022-06-22 10:01:21 +08004012 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4013 // do these processes after effects are applied.
4014 if (!mEffectBufferValid) {
4015 // mono blend occurs for mixer threads only (not direct or offloaded)
4016 // and is handled here if we're going directly to the sink.
4017 if (requireMonoBlend()) {
4018 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4019 mNormalFrameCount, true /*limit*/);
4020 }
Andy Hung2ddee192015-12-18 17:34:44 -08004021
David Li88ee0902022-06-22 10:01:21 +08004022 if (!hasFastMixer()) {
4023 // Balance must take effect after mono conversion.
4024 // We do it here if there is no FastMixer.
4025 // mBalance detects zero balance within the class for speed
4026 // (not needed here).
4027 mBalance.setBalance(mMasterBalance.load());
4028 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4029 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004030 }
4031
Andy Hung98ef9782014-03-04 14:46:50 -08004032 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004033 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004034
4035 // If we're going directly to the sink and there are haptic channels,
4036 // we should adjust channels as the sample data is partially interleaved
4037 // in this case.
4038 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4039 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4040 mChannelCount + mHapticChannelCount,
4041 audio_bytes_per_sample(format),
4042 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4043 }
Andy Hung98ef9782014-03-04 14:46:50 -08004044 }
4045
Eric Laurentbfb1b832013-01-07 09:53:42 -08004046 mBytesRemaining = mCurrentWriteLength;
4047 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004048 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4049 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4050 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4051 mBytesWritten += mBytesRemaining;
4052 mFramesWritten += framesRemaining;
4053 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004054 mBytesRemaining = 0;
4055 }
Eric Laurent81784c32012-11-19 14:55:58 -08004056
Eric Laurentbfb1b832013-01-07 09:53:42 -08004057 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004058 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004059 for (size_t i = 0; i < effectChains.size(); i ++) {
4060 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004061 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004062 if (activeHapticSessionId != AUDIO_SESSION_NONE
4063 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004064 // Haptic data is active in this case, copy it directly from
4065 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004066 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4067 audio_channel_count_from_out_mask(mMixerChannelMask) :
4068 mChannelCount;
4069 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4070 hapticSessionChannelCount = mChannelCount;
4071 }
4072
jiabin47affe52019-04-04 18:02:07 -07004073 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004074 * audio_bytes_per_frame(hapticSessionChannelCount,
4075 EFFECT_BUFFER_FORMAT);
jiabin47affe52019-04-04 18:02:07 -07004076 memcpy_by_audio_format(
4077 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
4078 EFFECT_BUFFER_FORMAT,
4079 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
4080 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
4081 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004082 }
Eric Laurent81784c32012-11-19 14:55:58 -08004083 }
4084 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004085 // Process effect chains for offloaded thread even if no audio
4086 // was read from audio track: process only updates effect state
4087 // and thus does have to be synchronized with audio writes but may have
4088 // to be called while waiting for async write callback
4089 if (mType == OFFLOAD) {
4090 for (size_t i = 0; i < effectChains.size(); i ++) {
4091 effectChains[i]->process_l();
4092 }
4093 }
Eric Laurent81784c32012-11-19 14:55:58 -08004094
Andy Hung98ef9782014-03-04 14:46:50 -08004095 // Only if the Effects buffer is enabled and there is data in the
4096 // Effects buffer (buffer valid), we need to
4097 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004098 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08004099 if (mEffectBufferValid) {
4100 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004101 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004102 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004103 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004104 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004105 }
4106
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004107 if (!hasFastMixer()) {
4108 // Balance must take effect after mono conversion.
4109 // We do it here if there is no FastMixer.
4110 // mBalance detects zero balance within the class for speed (not needed here).
4111 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004112 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004113 }
4114
Eric Laurentb62d0362021-10-26 17:40:18 +02004115 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4116 // mPostSpatializerBuffer if the haptics track is spatialized.
4117 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4118 // For other thread types, the haptics channels are already in mEffectBuffer.
4119 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4120 const size_t srcBufferSize = mNormalFrameCount *
4121 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4122 mEffectBufferFormat);
4123 const size_t dstBufferSize = mNormalFrameCount
4124 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4125
4126 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4127 mEffectBufferFormat,
4128 (uint8_t*)mEffectBuffer + srcBufferSize,
4129 mEffectBufferFormat,
4130 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004131 }
Atneya Nair68436cf2022-09-19 17:51:37 -07004132 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4133 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4134 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4135 // Clamp PCM float values more than this distance from 0 to insulate
4136 // a HAL which doesn't handle NaN correctly.
4137 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4138 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4139 static_cast<const float*>(effectBuffer),
4140 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4141 } else {
4142 memcpy_by_audio_format(mSinkBuffer, mFormat,
4143 effectBuffer, mEffectBufferFormat, framesToCopy);
4144 }
jiabin245cdd92018-12-07 17:55:15 -08004145 // The sample data is partially interleaved when haptic channels exist,
4146 // we need to adjust channels here.
4147 if (mHapticChannelCount > 0) {
4148 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4149 mChannelCount + mHapticChannelCount,
4150 audio_bytes_per_sample(mFormat),
4151 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4152 }
Andy Hung98ef9782014-03-04 14:46:50 -08004153 }
4154
Eric Laurent81784c32012-11-19 14:55:58 -08004155 // enable changes in effect chain
4156 unlockEffectChains(effectChains);
4157
Eric Laurentbfb1b832013-01-07 09:53:42 -08004158 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004159 // mSleepTimeUs == 0 means we must write to audio hardware
4160 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004161 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004162 // writePeriodNs is updated >= 0 when ret > 0.
4163 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004164 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004165 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004166 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004167 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004168 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004169 if (ret < 0) {
4170 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004171 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004172 mBytesWritten += ret;
4173 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004174 const int64_t frames = ret / mFrameSize;
4175 mFramesWritten += frames;
4176
4177 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4178 // process information relating to write time.
4179 if (audio_has_proportional_frames(mFormat)) {
4180 // we are in a continuous mixing cycle
4181 if (mMixerStatus == MIXER_TRACKS_READY &&
4182 loopCount == lastLoopCountWritten + 1) {
4183
4184 const double jitterMs =
4185 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4186 {frames, writePeriodNs},
4187 {0, 0} /* lastTimestamp */, mSampleRate);
4188 const double processMs =
4189 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4190
4191 Mutex::Autolock _l(mLock);
4192 mIoJitterMs.add(jitterMs);
4193 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004194
4195 if (mPipeSink.get() != nullptr) {
4196 // Using the Monopipe availableToWrite, we estimate the current
4197 // buffer size.
4198 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4199 const ssize_t
4200 availableToWrite = mPipeSink->availableToWrite();
4201 const size_t pipeFrames = monoPipe->maxFrames();
4202 const size_t
4203 remainingFrames = pipeFrames - max(availableToWrite, 0);
4204 mMonopipePipeDepthStats.add(remainingFrames);
4205 }
Andy Hung446f4df2019-02-21 12:26:41 -08004206 }
4207
4208 // write blocked detection
4209 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004210 if ((mType == MIXER || mType == SPATIALIZER)
4211 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004212 mNumDelayedWrites++;
4213 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4214 ATRACE_NAME("underrun");
4215 ALOGW("write blocked for %lld msecs, "
4216 "%d delayed writes, thread %d",
4217 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4218 mNumDelayedWrites, mId);
4219 lastWarning = lastIoEndNs;
4220 }
4221 }
4222 }
4223 // update timing info.
4224 mLastIoBeginNs = lastIoBeginNs;
4225 mLastIoEndNs = lastIoEndNs;
4226 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004227 }
4228 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4229 (mMixerStatus == MIXER_DRAIN_ALL)) {
4230 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004231 }
Andy Hungd3639922022-04-28 18:00:49 -07004232 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004233
4234 if (mThreadThrottle
4235 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004236 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004237 // Limit MixerThread data processing to no more than twice the
4238 // expected processing rate.
4239 //
4240 // This helps prevent underruns with NuPlayer and other applications
4241 // which may set up buffers that are close to the minimum size, or use
4242 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4243 //
4244 // The throttle smooths out sudden large data drains from the device,
4245 // e.g. when it comes out of standby, which often causes problems with
4246 // (1) mixer threads without a fast mixer (which has its own warm-up)
4247 // (2) minimum buffer sized tracks (even if the track is full,
4248 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004249 //
4250 // Total time spent in last processing cycle equals time spent in
4251 // 1. threadLoop_write, as well as time spent in
4252 // 2. threadLoop_mix (significant for heavy mixing, especially
4253 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004254
Andy Hung446f4df2019-02-21 12:26:41 -08004255 // it's OK if deltaMs is an overestimate.
4256
4257 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004258
Ivan Lozanoea04d392017-11-07 14:37:07 -08004259 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004260 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004261 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004262
Andy Hung08fb1742015-05-31 23:22:10 -07004263 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004264 // notify of throttle start on verbose log
4265 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4266 "mixer(%p) throttle begin:"
4267 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004268 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004269 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004270 // Throttle must be attributed to the previous mixer loop's write time
4271 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004272 // This also ensures proper timing statistics.
4273 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004274 } else {
4275 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4276 if (diff > 0) {
4277 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004278 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004279 ALOGD_IF(!isSingleDeviceType(
4280 outDeviceTypes(), audio_is_a2dp_out_device) &&
4281 !isSingleDeviceType(
4282 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004283 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004284 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4285 }
Andy Hung08fb1742015-05-31 23:22:10 -07004286 }
4287 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004288 }
Eric Laurent81784c32012-11-19 14:55:58 -08004289
Eric Laurentbfb1b832013-01-07 09:53:42 -08004290 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004291 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004292 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004293 // suspended requires accurate metering of sleep time.
4294 if (isSuspended()) {
4295 // advance by expected sleepTime
4296 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4297 const nsecs_t nowNs = systemTime();
4298
4299 // compute expected next time vs current time.
4300 // (negative deltas are treated as delays).
4301 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4302 if (deltaNs < -kMaxNextBufferDelayNs) {
4303 // Delays longer than the max allowed trigger a reset.
4304 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4305 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4306 timeLoopNextNs = nowNs + deltaNs;
4307 } else if (deltaNs < 0) {
4308 // Delays within the max delay allowed: zero the delta/sleepTime
4309 // to help the system catch up in the next iteration(s)
4310 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4311 deltaNs = 0;
4312 }
4313 // update sleep time (which is >= 0)
4314 mSleepTimeUs = deltaNs / 1000;
4315 }
Eric Laurente93cc032016-05-05 10:15:10 -07004316 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4317 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004318 }
Glenn Kastene7754022014-10-31 12:11:26 -07004319 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004320 }
Eric Laurent81784c32012-11-19 14:55:58 -08004321 }
4322
4323 // Finally let go of removed track(s), without the lock held
4324 // since we can't guarantee the destructors won't acquire that
4325 // same lock. This will also mutate and push a new fast mixer state.
4326 threadLoop_removeTracks(tracksToRemove);
4327 tracksToRemove.clear();
4328
4329 // FIXME I don't understand the need for this here;
4330 // it was in the original code but maybe the
4331 // assignment in saveOutputTracks() makes this unnecessary?
4332 clearOutputTracks();
4333
4334 // Effect chains will be actually deleted here if they were removed from
4335 // mEffectChains list during mixing or effects processing
4336 effectChains.clear();
4337
4338 // FIXME Note that the above .clear() is no longer necessary since effectChains
4339 // is now local to this block, but will keep it for now (at least until merge done).
4340 }
4341
Eric Laurentbfb1b832013-01-07 09:53:42 -08004342 threadLoop_exit();
4343
Eric Laurentcf817a22014-08-04 20:36:31 -07004344 if (!mStandby) {
4345 threadLoop_standby();
4346 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004347 }
4348
4349 releaseWakeLock();
4350
4351 ALOGV("Thread %p type %d exiting", this, mType);
4352 return false;
4353}
4354
Dean Wheatley12473e92021-03-18 23:00:55 +11004355void AudioFlinger::PlaybackThread::collectTimestamps_l()
4356{
Dean Wheatley12473e92021-03-18 23:00:55 +11004357 if (mStandby) {
4358 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4359 return;
4360 } else if (mHwPaused) {
4361 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4362 return;
4363 }
4364
4365 // Gather the framesReleased counters for all active tracks,
4366 // and associate with the sink frames written out. We need
4367 // this to convert the sink timestamp to the track timestamp.
4368 bool kernelLocationUpdate = false;
4369 ExtendedTimestamp timestamp; // use private copy to fetch
4370
4371 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4372 // HAL may be draining some small duration buffered data for fade out.
4373 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4374 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4375 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4376 mSampleRate);
4377
4378 if (isTimestampCorrectionEnabled()) {
4379 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4380 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4381 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4382 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4383 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4384 = correctedTimestamp.mFrames;
4385 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4386 = correctedTimestamp.mTimeNs;
4387 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4388 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4389 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4390
4391 // Note: Downstream latency only added if timestamp correction enabled.
4392 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4393 const int64_t newPosition =
4394 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4395 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4396 // prevent retrograde
4397 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4398 newPosition,
4399 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4400 - mSuspendedFrames));
4401 }
4402 }
4403
4404 // We always fetch the timestamp here because often the downstream
4405 // sink will block while writing.
4406
4407 // We keep track of the last valid kernel position in case we are in underrun
4408 // and the normal mixer period is the same as the fast mixer period, or there
4409 // is some error from the HAL.
4410 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4411 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4412 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4413 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4414 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4415
4416 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4417 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4418 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4419 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4420 }
4421
4422 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4423 kernelLocationUpdate = true;
4424 } else {
4425 ALOGVV("getTimestamp error - no valid kernel position");
4426 }
4427
4428 // copy over kernel info
4429 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4430 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4431 + mSuspendedFrames; // add frames discarded when suspended
4432 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4433 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4434 } else {
4435 mTimestampVerifier.error();
4436 }
4437
4438 // mFramesWritten for non-offloaded tracks are contiguous
4439 // even after standby() is called. This is useful for the track frame
4440 // to sink frame mapping.
4441 bool serverLocationUpdate = false;
4442 if (mFramesWritten != mLastFramesWritten) {
4443 serverLocationUpdate = true;
4444 mLastFramesWritten = mFramesWritten;
4445 }
4446 // Only update timestamps if there is a meaningful change.
4447 // Either the kernel timestamp must be valid or we have written something.
4448 if (kernelLocationUpdate || serverLocationUpdate) {
4449 if (serverLocationUpdate) {
4450 // use the time before we called the HAL write - it is a bit more accurate
4451 // to when the server last read data than the current time here.
4452 //
4453 // If we haven't written anything, mLastIoBeginNs will be -1
4454 // and we use systemTime().
4455 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4456 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4457 ? systemTime() : mLastIoBeginNs;
4458 }
4459
4460 for (const sp<Track> &t : mActiveTracks) {
4461 if (!t->isFastTrack()) {
4462 t->updateTrackFrameInfo(
4463 t->mAudioTrackServerProxy->framesReleased(),
4464 mFramesWritten,
4465 mSampleRate,
4466 mTimestamp);
4467 }
4468 }
4469 }
4470
4471 if (audio_has_proportional_frames(mFormat)) {
4472 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4473 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4474 mLatencyMs.add(latencyMs);
4475 }
4476 }
4477#if 0
4478 // logFormat example
4479 if (z % 100 == 0) {
4480 timespec ts;
4481 clock_gettime(CLOCK_MONOTONIC, &ts);
4482 LOGT("This is an integer %d, this is a float %f, this is my "
4483 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4484 LOGT("A deceptive null-terminated string %\0");
4485 }
4486 ++z;
4487#endif
4488}
4489
Eric Laurentbfb1b832013-01-07 09:53:42 -08004490// removeTracks_l() must be called with ThreadBase::mLock held
4491void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4492{
Andy Hungfe726a62018-09-27 15:17:25 -07004493 for (const auto& track : tracksToRemove) {
4494 mActiveTracks.remove(track);
4495 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4496 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4497 if (chain != 0) {
4498 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4499 __func__, track->id(), chain.get(), track->sessionId());
4500 chain->decActiveTrackCnt();
4501 }
4502 // If an external client track, inform APM we're no longer active, and remove if needed.
4503 // We do this under lock so that the state is consistent if the Track is destroyed.
4504 if (track->isExternalTrack()) {
4505 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004506 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004507 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004508 }
4509 }
Andy Hungfe726a62018-09-27 15:17:25 -07004510 if (track->isTerminated()) {
4511 // remove from our tracks vector
4512 removeTrack_l(track);
4513 }
jiabineb3bda02020-06-30 14:07:03 -07004514 if (mHapticChannelCount > 0 &&
4515 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4516 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004517 mLock.unlock();
4518 // Unlock due to VibratorService will lock for this call and will
4519 // call Tracks.mute/unmute which also require thread's lock.
4520 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4521 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004522
4523 // When the track is stop, set the haptic intensity as MUTE
4524 // for the HapticGenerator effect.
4525 if (chain != nullptr) {
4526 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4527 }
jiabin245cdd92018-12-07 17:55:15 -08004528 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004529 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004530}
Eric Laurent81784c32012-11-19 14:55:58 -08004531
Eric Laurentaccc1472013-09-20 09:36:34 -07004532status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4533{
4534 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004535 ExtendedTimestamp ets;
4536 status_t status = mNormalSink->getTimestamp(ets);
4537 if (status == NO_ERROR) {
4538 status = ets.getBestTimestamp(&timestamp);
4539 }
4540 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004541 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004542 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004543 collectTimestamps_l();
4544 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4545 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004546 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004547 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4548 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4549 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4550 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4551 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004552 }
4553 return INVALID_OPERATION;
4554}
Eric Laurent1c333e22014-05-20 10:48:17 -07004555
Eric Laurenteab90452019-06-24 15:17:46 -07004556// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4557// still applied by the mixer.
4558// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4559// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4560// if more than one track are active
4561status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4562{
4563 status_t result = NO_ERROR;
4564 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4565 if (*volume != mLeftVolFloat) {
4566 result = mOutput->stream->setVolume(*volume, *volume);
4567 ALOGE_IF(result != OK,
4568 "Error when setting output stream volume: %d", result);
4569 if (result == NO_ERROR) {
4570 mLeftVolFloat = *volume;
4571 }
4572 }
4573 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4574 // remove stream volume contribution from software volume.
4575 if (mLeftVolFloat == *volume) {
4576 *volume = 1.0f;
4577 }
4578 }
4579 return result;
4580}
4581
Eric Laurent054d9d32015-04-24 08:48:48 -07004582status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4583 audio_patch_handle_t *handle)
4584{
Andy Hungf60abce2016-08-26 11:37:54 -07004585 status_t status;
4586 if (property_get_bool("af.patch_park", false /* default_value */)) {
4587 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4588 // or if HAL does not properly lock against access.
4589 AutoPark<FastMixer> park(mFastMixer);
4590 status = PlaybackThread::createAudioPatch_l(patch, handle);
4591 } else {
4592 status = PlaybackThread::createAudioPatch_l(patch, handle);
4593 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004594 return status;
4595}
4596
Eric Laurent1c333e22014-05-20 10:48:17 -07004597status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4598 audio_patch_handle_t *handle)
4599{
4600 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004601
4602 // store new device and send to effects
4603 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004604 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004605 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004606 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4607 && !mOutput->audioHwDev->supportsAudioPatches(),
4608 "Enumerated device type(%#x) must not be used "
4609 "as it does not support audio patches",
4610 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004611 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07004612 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4613 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004614 }
4615
François Gaffie0c280aa2018-07-25 10:02:15 +02004616 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004617#ifdef ADD_BATTERY_DATA
4618 // when changing the audio output device, call addBatteryData to notify
4619 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004620 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004621 uint32_t params = 0;
4622 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004623 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004624 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004625 }
4626
Eric Laurent054d9d32015-04-24 08:48:48 -07004627 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004628 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004629 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4630 }
4631
4632 if (params != 0) {
4633 addBatteryData(params);
4634 }
4635 }
4636#endif
4637
4638 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004639 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004640 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004641
jiabinc52b1ff2019-10-31 17:20:42 -07004642 // mPatch.num_sinks is not set when the thread is created so that
4643 // the first patch creation triggers an ioConfigChanged callback
4644 bool configChanged = (mPatch.num_sinks == 0) ||
4645 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004646 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004647 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004648 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004649
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004650 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004651 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4652 status = hwDevice->createAudioPatch(patch->num_sources,
4653 patch->sources,
4654 patch->num_sinks,
4655 patch->sinks,
4656 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004657 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004658 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004659 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004660 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004661 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004662
4663 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004664 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004665 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004666 // also dispatch to active AudioTracks for MediaMetrics
4667 for (const auto &track : mActiveTracks) {
4668 track->logEndInterval();
4669 track->logBeginInterval(patchSinksAsString);
4670 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004671
Eric Laurente8726fe2015-06-26 09:39:24 -07004672 if (configChanged) {
4673 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4674 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004675 return status;
4676}
4677
Eric Laurent054d9d32015-04-24 08:48:48 -07004678status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4679{
Andy Hungf60abce2016-08-26 11:37:54 -07004680 status_t status;
4681 if (property_get_bool("af.patch_park", false /* default_value */)) {
4682 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4683 // or if HAL does not properly lock against access.
4684 AutoPark<FastMixer> park(mFastMixer);
4685 status = PlaybackThread::releaseAudioPatch_l(handle);
4686 } else {
4687 status = PlaybackThread::releaseAudioPatch_l(handle);
4688 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004689 return status;
4690}
4691
Eric Laurent1c333e22014-05-20 10:48:17 -07004692status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4693{
4694 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004695
jiabinc52b1ff2019-10-31 17:20:42 -07004696 mPatch = audio_patch{};
4697 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004698
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004699 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004700 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4701 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004702 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004703 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004704 }
4705 return status;
4706}
4707
Eric Laurent83b88082014-06-20 18:31:16 -07004708void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4709{
4710 Mutex::Autolock _l(mLock);
4711 mTracks.add(track);
4712}
4713
4714void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4715{
4716 Mutex::Autolock _l(mLock);
4717 destroyTrack_l(track);
4718}
4719
Mikhail Naganovdc769682018-05-04 15:34:08 -07004720void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004721{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004722 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004723 config->role = AUDIO_PORT_ROLE_SOURCE;
4724 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4725 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004726 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4727 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4728 config->flags.output = mOutput->flags;
4729 }
Eric Laurent83b88082014-06-20 18:31:16 -07004730}
4731
Eric Laurent81784c32012-11-19 14:55:58 -08004732// ----------------------------------------------------------------------------
4733
4734AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004735 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
4736 : PlaybackThread(audioFlinger, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004737 // mAudioMixer below
4738 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004739 mFastMixerFutex(0),
4740 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004741 // mOutputSink below
4742 // mPipeSink below
4743 // mNormalSink below
4744{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004745 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004746 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004747 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004748 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004749 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4750 mNormalFrameCount);
4751 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4752
Andy Hungfbfc3952015-01-15 13:33:51 -08004753 if (type == DUPLICATING) {
4754 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4755 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4756 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4757 return;
4758 }
Eric Laurent81784c32012-11-19 14:55:58 -08004759 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004760 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004761 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004762 const NBAIO_Format offers[1] = {Format_from_SR_C(
4763 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004764#if !LOG_NDEBUG
4765 ssize_t index =
4766#else
4767 (void)
4768#endif
4769 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004770 ALOG_ASSERT(index == 0);
4771
4772 // initialize fast mixer depending on configuration
4773 bool initFastMixer;
Eric Laurentb62d0362021-10-26 17:40:18 +02004774 if (mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004775 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004776 } else {
4777 switch (kUseFastMixer) {
4778 case FastMixer_Never:
4779 initFastMixer = false;
4780 break;
4781 case FastMixer_Always:
4782 initFastMixer = true;
4783 break;
4784 case FastMixer_Static:
4785 case FastMixer_Dynamic:
4786 initFastMixer = mFrameCount < mNormalFrameCount;
4787 break;
4788 }
4789 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4790 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4791 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004792 }
4793 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004794 audio_format_t fastMixerFormat;
4795 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4796 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4797 } else {
4798 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4799 }
4800 if (mFormat != fastMixerFormat) {
4801 // change our Sink format to accept our intermediate precision
4802 mFormat = fastMixerFormat;
4803 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004804 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004805 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4806 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4807 }
Eric Laurent81784c32012-11-19 14:55:58 -08004808
4809 // create a MonoPipe to connect our submix to FastMixer
4810 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004811
Andy Hung1258c1a2014-05-23 21:22:17 -07004812 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004813 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004814 format.mFormat = fastMixerFormat;
4815 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4816
Eric Laurent81784c32012-11-19 14:55:58 -08004817 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4818 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4819 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4820 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4821 const NBAIO_Format offers[1] = {format};
4822 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004823#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004824 ssize_t index =
4825#else
4826 (void)
4827#endif
4828 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004829 ALOG_ASSERT(index == 0);
4830 monoPipe->setAvgFrames((mScreenState & 1) ?
4831 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4832 mPipeSink = monoPipe;
4833
Eric Laurent81784c32012-11-19 14:55:58 -08004834 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004835 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004836 FastMixerStateQueue *sq = mFastMixer->sq();
4837#ifdef STATE_QUEUE_DUMP
4838 sq->setObserverDump(&mStateQueueObserverDump);
4839 sq->setMutatorDump(&mStateQueueMutatorDump);
4840#endif
4841 FastMixerState *state = sq->begin();
4842 FastTrack *fastTrack = &state->mFastTracks[0];
4843 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4844 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4845 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004846 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4847 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4848 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004849 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004850 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004851 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01004852 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08004853 fastTrack->mGeneration++;
4854 state->mFastTracksGen++;
4855 state->mTrackMask = 1;
4856 // fast mixer will use the HAL output sink
4857 state->mOutputSink = mOutputSink.get();
4858 state->mOutputSinkGen++;
4859 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004860 // specify sink channel mask when haptic channel mask present as it can not
4861 // be calculated directly from channel count
4862 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004863 ? AUDIO_CHANNEL_NONE
4864 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004865 state->mCommand = FastMixerState::COLD_IDLE;
4866 // already done in constructor initialization list
4867 //mFastMixerFutex = 0;
4868 state->mColdFutexAddr = &mFastMixerFutex;
4869 state->mColdGen++;
4870 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004871 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4872 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004873 sq->end();
4874 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4875
Eric Tan0513b5d2018-09-17 10:32:48 -07004876 NBLog::thread_info_t info;
4877 info.id = mId;
4878 info.type = NBLog::FASTMIXER;
4879 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4880
Eric Laurent81784c32012-11-19 14:55:58 -08004881 // start the fast mixer
4882 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4883 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004884 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004885 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004886
4887#ifdef AUDIO_WATCHDOG
4888 // create and start the watchdog
4889 mAudioWatchdog = new AudioWatchdog();
4890 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4891 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4892 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004893 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004894#endif
Andy Hung8946a282018-04-19 20:04:56 -07004895 } else {
4896#ifdef TEE_SINK
4897 // Only use the MixerThread tee if there is no FastMixer.
4898 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4899 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4900#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004901 }
4902
4903 switch (kUseFastMixer) {
4904 case FastMixer_Never:
4905 case FastMixer_Dynamic:
4906 mNormalSink = mOutputSink;
4907 break;
4908 case FastMixer_Always:
4909 mNormalSink = mPipeSink;
4910 break;
4911 case FastMixer_Static:
4912 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4913 break;
4914 }
4915}
4916
4917AudioFlinger::MixerThread::~MixerThread()
4918{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004919 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004920 FastMixerStateQueue *sq = mFastMixer->sq();
4921 FastMixerState *state = sq->begin();
4922 if (state->mCommand == FastMixerState::COLD_IDLE) {
4923 int32_t old = android_atomic_inc(&mFastMixerFutex);
4924 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004925 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004926 }
4927 }
4928 state->mCommand = FastMixerState::EXIT;
4929 sq->end();
4930 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4931 mFastMixer->join();
4932 // Though the fast mixer thread has exited, it's state queue is still valid.
4933 // We'll use that extract the final state which contains one remaining fast track
4934 // corresponding to our sub-mix.
4935 state = sq->begin();
4936 ALOG_ASSERT(state->mTrackMask == 1);
4937 FastTrack *fastTrack = &state->mFastTracks[0];
4938 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4939 delete fastTrack->mBufferProvider;
4940 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004941 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004942#ifdef AUDIO_WATCHDOG
4943 if (mAudioWatchdog != 0) {
4944 mAudioWatchdog->requestExit();
4945 mAudioWatchdog->requestExitAndWait();
4946 mAudioWatchdog.clear();
4947 }
4948#endif
4949 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004950 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004951 delete mAudioMixer;
4952}
4953
4954
4955uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4956{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004957 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004958 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4959 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4960 }
4961 return latency;
4962}
4963
Eric Laurentbfb1b832013-01-07 09:53:42 -08004964ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004965{
4966 // FIXME we should only do one push per cycle; confirm this is true
4967 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004968 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004969 FastMixerStateQueue *sq = mFastMixer->sq();
4970 FastMixerState *state = sq->begin();
4971 if (state->mCommand != FastMixerState::MIX_WRITE &&
4972 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4973 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004974
4975 // FIXME workaround for first HAL write being CPU bound on some devices
4976 ATRACE_BEGIN("write");
4977 mOutput->write((char *)mSinkBuffer, 0);
4978 ATRACE_END();
4979
Eric Laurent81784c32012-11-19 14:55:58 -08004980 int32_t old = android_atomic_inc(&mFastMixerFutex);
4981 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004982 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004983 }
4984#ifdef AUDIO_WATCHDOG
4985 if (mAudioWatchdog != 0) {
4986 mAudioWatchdog->resume();
4987 }
4988#endif
4989 }
4990 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004991#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004992 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004993 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004994#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004995 sq->end();
4996 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4997 if (kUseFastMixer == FastMixer_Dynamic) {
4998 mNormalSink = mPipeSink;
4999 }
5000 } else {
5001 sq->end(false /*didModify*/);
5002 }
5003 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005004 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005005}
5006
5007void AudioFlinger::MixerThread::threadLoop_standby()
5008{
5009 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005010 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005011 FastMixerStateQueue *sq = mFastMixer->sq();
5012 FastMixerState *state = sq->begin();
5013 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005014 // Report any frames trapped in the Monopipe
5015 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5016 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5017 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5018 "monoPipeWritten:%lld monoPipeLeft:%lld",
5019 (long long)mFramesWritten, (long long)mSuspendedFrames,
5020 (long long)mPipeSink->framesWritten(), pipeFrames);
5021 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5022
Eric Laurent81784c32012-11-19 14:55:58 -08005023 state->mCommand = FastMixerState::COLD_IDLE;
5024 state->mColdFutexAddr = &mFastMixerFutex;
5025 state->mColdGen++;
5026 mFastMixerFutex = 0;
5027 sq->end();
5028 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5029 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5030 if (kUseFastMixer == FastMixer_Dynamic) {
5031 mNormalSink = mOutputSink;
5032 }
5033#ifdef AUDIO_WATCHDOG
5034 if (mAudioWatchdog != 0) {
5035 mAudioWatchdog->pause();
5036 }
5037#endif
5038 } else {
5039 sq->end(false /*didModify*/);
5040 }
5041 }
5042 PlaybackThread::threadLoop_standby();
5043}
5044
Eric Laurentbfb1b832013-01-07 09:53:42 -08005045bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
5046{
5047 return false;
5048}
5049
5050bool AudioFlinger::PlaybackThread::shouldStandby_l()
5051{
5052 return !mStandby;
5053}
5054
5055bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
5056{
5057 Mutex::Autolock _l(mLock);
5058 return waitingAsyncCallback_l();
5059}
5060
Eric Laurent81784c32012-11-19 14:55:58 -08005061// shared by MIXER and DIRECT, overridden by DUPLICATING
5062void AudioFlinger::PlaybackThread::threadLoop_standby()
5063{
5064 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005065 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005066 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005067 // discard any pending drain or write ack by incrementing sequence
5068 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5069 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005070 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005071 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5072 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005073 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005074 mHwPaused = false;
Eric Laurent6f9534f2022-05-03 18:15:04 +02005075 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005076}
5077
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005078void AudioFlinger::PlaybackThread::onAddNewTrack_l()
5079{
5080 ALOGV("signal playback thread");
5081 broadcast_l();
5082}
5083
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005084void AudioFlinger::PlaybackThread::onAsyncError()
5085{
5086 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5087 invalidateTracks((audio_stream_type_t)i);
5088 }
5089}
5090
Eric Laurent81784c32012-11-19 14:55:58 -08005091void AudioFlinger::MixerThread::threadLoop_mix()
5092{
Eric Laurent81784c32012-11-19 14:55:58 -08005093 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005094 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005095 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005096 // increase sleep time progressively when application underrun condition clears.
5097 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5098 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5099 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005100 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005101 sleepTimeShift--;
5102 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005103 mSleepTimeUs = 0;
5104 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005105 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005106
Eric Laurent81784c32012-11-19 14:55:58 -08005107}
5108
5109void AudioFlinger::MixerThread::threadLoop_sleepTime()
5110{
5111 // If no tracks are ready, sleep once for the duration of an output
5112 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005113 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005114 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005115 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5116 // Using the Monopipe availableToWrite, we estimate the
5117 // sleep time to retry for more data (before we underrun).
5118 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5119 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5120 const size_t pipeFrames = monoPipe->maxFrames();
5121 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5122 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5123 const size_t framesDelay = std::min(
5124 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5125 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5126 pipeFrames, framesLeft, framesDelay);
5127 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5128 } else {
5129 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5130 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5131 mSleepTimeUs = kMinThreadSleepTimeUs;
5132 }
5133 // reduce sleep time in case of consecutive application underruns to avoid
5134 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5135 // duration we would end up writing less data than needed by the audio HAL if
5136 // the condition persists.
5137 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5138 sleepTimeShift++;
5139 }
Eric Laurent81784c32012-11-19 14:55:58 -08005140 }
5141 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005142 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005143 }
5144 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005145 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5146 // before effects processing or output.
5147 if (mMixerBufferValid) {
5148 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005149 if (mType == SPATIALIZER) {
5150 memset(mSinkBuffer, 0, mSinkBufferSize);
5151 }
Andy Hung98ef9782014-03-04 14:46:50 -08005152 } else {
5153 memset(mSinkBuffer, 0, mSinkBufferSize);
5154 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005155 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005156 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5157 "anticipated start");
5158 }
5159 // TODO add standby time extension fct of effect tail
5160}
5161
5162// prepareTracks_l() must be called with ThreadBase::mLock held
5163AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
5164 Vector< sp<Track> > *tracksToRemove)
5165{
Andy Hungc0691382018-09-12 18:01:57 -07005166 // clean up deleted track ids in AudioMixer before allocating new tracks
5167 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5168 // for each trackId, destroy it in the AudioMixer
5169 if (mAudioMixer->exists(trackId)) {
5170 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005171 }
5172 });
Andy Hungc0691382018-09-12 18:01:57 -07005173 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005174
5175 mixer_state mixerStatus = MIXER_IDLE;
5176 // find out which tracks need to be processed
5177 size_t count = mActiveTracks.size();
5178 size_t mixedTracks = 0;
5179 size_t tracksWithEffect = 0;
5180 // counts only _active_ fast tracks
5181 size_t fastTracks = 0;
5182 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5183
5184 float masterVolume = mMasterVolume;
5185 bool masterMute = mMasterMute;
5186
5187 if (masterMute) {
5188 masterVolume = 0;
5189 }
5190 // Delegate master volume control to effect in output mix effect chain if needed
5191 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
5192 if (chain != 0) {
5193 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5194 chain->setVolume_l(&v, &v);
5195 masterVolume = (float)((v + (1 << 23)) >> 24);
5196 chain.clear();
5197 }
5198
5199 // prepare a new state to push
5200 FastMixerStateQueue *sq = NULL;
5201 FastMixerState *state = NULL;
5202 bool didModify = false;
5203 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005204 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005205 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005206 sq = mFastMixer->sq();
5207 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005208 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005209 }
5210
Andy Hung69aed5f2014-02-25 17:24:40 -08005211 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005212 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005213
Andy Hungbd3b2b02018-05-21 10:53:11 -07005214 // DeferredOperations handles statistics after setting mixerStatus.
5215 class DeferredOperations {
5216 public:
Andy Hungea840382020-05-05 21:50:17 -07005217 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5218 : mMixerStatus(mixerStatus)
5219 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005220
5221 // when leaving scope, tally frames properly.
5222 ~DeferredOperations() {
5223 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5224 // because that is when the underrun occurs.
5225 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005226 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005227 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005228 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005229 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005230 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005231 }
5232 }
Andy Hungea840382020-05-05 21:50:17 -07005233 // send the max underrun frames for this mixer period
5234 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005235 }
5236
5237 // tallyUnderrunFrames() is called to update the track counters
5238 // with the number of underrun frames for a particular mixer period.
5239 // We defer tallying until we know the final mixer status.
5240 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
5241 mUnderrunFrames.emplace_back(track, underrunFrames);
5242 }
5243
5244 private:
5245 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005246 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07005247 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005248 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005249 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005250
jiabin245cdd92018-12-07 17:55:15 -08005251 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005252 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07005253 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005254
5255 // this const just means the local variable doesn't change
5256 Track* const track = t.get();
5257
5258 // process fast tracks
5259 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005260 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5261 "%s(%d): FastTrack(%d) present without FastMixer",
5262 __func__, id(), track->id());
5263
jiabin245cdd92018-12-07 17:55:15 -08005264 if (track->getHapticPlaybackEnabled()) {
5265 noFastHapticTrack = false;
5266 }
Eric Laurent81784c32012-11-19 14:55:58 -08005267
5268 // It's theoretically possible (though unlikely) for a fast track to be created
5269 // and then removed within the same normal mix cycle. This is not a problem, as
5270 // the track never becomes active so it's fast mixer slot is never touched.
5271 // The converse, of removing an (active) track and then creating a new track
5272 // at the identical fast mixer slot within the same normal mix cycle,
5273 // is impossible because the slot isn't marked available until the end of each cycle.
5274 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005275 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005276 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5277 FastTrack *fastTrack = &state->mFastTracks[j];
5278
5279 // Determine whether the track is currently in underrun condition,
5280 // and whether it had a recent underrun.
5281 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5282 FastTrackUnderruns underruns = ftDump->mUnderruns;
5283 uint32_t recentFull = (underruns.mBitFields.mFull -
5284 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
5285 uint32_t recentPartial = (underruns.mBitFields.mPartial -
5286 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
5287 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
5288 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
5289 uint32_t recentUnderruns = recentPartial + recentEmpty;
5290 track->mObservedUnderruns = underruns;
5291 // don't count underruns that occur while stopping or pausing
5292 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005293 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005294 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5295 recentUnderruns > 0) {
5296 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005297 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005298 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005299 // Immediately account for FastTrack underruns.
5300 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005301
5302 // This is similar to the state machine for normal tracks,
5303 // with a few modifications for fast tracks.
5304 bool isActive = true;
5305 switch (track->mState) {
5306 case TrackBase::STOPPING_1:
5307 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005308 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005309 track->mState = TrackBase::STOPPING_2;
5310 }
5311 break;
5312 case TrackBase::PAUSING:
5313 // ramp down is not yet implemented
5314 track->setPaused();
5315 break;
5316 case TrackBase::RESUMING:
5317 // ramp up is not yet implemented
5318 track->mState = TrackBase::ACTIVE;
5319 break;
5320 case TrackBase::ACTIVE:
5321 if (recentFull > 0 || recentPartial > 0) {
5322 // track has provided at least some frames recently: reset retry count
5323 track->mRetryCount = kMaxTrackRetries;
5324 }
5325 if (recentUnderruns == 0) {
5326 // no recent underruns: stay active
5327 break;
5328 }
5329 // there has recently been an underrun of some kind
5330 if (track->sharedBuffer() == 0) {
5331 // were any of the recent underruns "empty" (no frames available)?
5332 if (recentEmpty == 0) {
5333 // no, then ignore the partial underruns as they are allowed indefinitely
5334 break;
5335 }
5336 // there has recently been an "empty" underrun: decrement the retry counter
5337 if (--(track->mRetryCount) > 0) {
5338 break;
5339 }
5340 // indicate to client process that the track was disabled because of underrun;
5341 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005342 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005343 // remove from active list, but state remains ACTIVE [confusing but true]
5344 isActive = false;
5345 break;
5346 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005347 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005348 case TrackBase::STOPPING_2:
5349 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005350 case TrackBase::STOPPED:
5351 case TrackBase::FLUSHED: // flush() while active
5352 // Check for presentation complete if track is inactive
5353 // We have consumed all the buffers of this track.
5354 // This would be incomplete if we auto-paused on underrun
5355 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005356 uint32_t latency = 0;
5357 status_t result = mOutput->stream->getLatency(&latency);
5358 ALOGE_IF(result != OK,
5359 "Error when retrieving output stream latency: %d", result);
5360 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005361 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005362 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5363 // track stays in active list until presentation is complete
5364 break;
5365 }
5366 }
5367 if (track->isStopping_2()) {
5368 track->mState = TrackBase::STOPPED;
5369 }
5370 if (track->isStopped()) {
5371 // Can't reset directly, as fast mixer is still polling this track
5372 // track->reset();
5373 // So instead mark this track as needing to be reset after push with ack
5374 resetMask |= 1 << i;
5375 }
5376 isActive = false;
5377 break;
5378 case TrackBase::IDLE:
5379 default:
Andy Hung959b5b82021-09-24 10:46:20 -07005380 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005381 }
5382
5383 if (isActive) {
5384 // was it previously inactive?
5385 if (!(state->mTrackMask & (1 << j))) {
5386 ExtendedAudioBufferProvider *eabp = track;
5387 VolumeProvider *vp = track;
5388 fastTrack->mBufferProvider = eabp;
5389 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005390 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005391 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005392 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005393 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005394 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005395 fastTrack->mGeneration++;
5396 state->mTrackMask |= 1 << j;
5397 didModify = true;
5398 // no acknowledgement required for newly active tracks
5399 }
Kevin Rocard12381092018-04-11 09:19:59 -07005400 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005401 float volume;
5402 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5403 volume = 0.f;
5404 } else {
5405 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5406 }
5407
5408 handleVoipVolume_l(&volume);
5409
Eric Laurent81784c32012-11-19 14:55:58 -08005410 // cache the combined master volume and stream type volume for fast mixer; this
5411 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005412 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005413 proxy->framesReleased()).first;
5414 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005415 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005416 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5417 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5418 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005419
Kevin Rocard12381092018-04-11 09:19:59 -07005420 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005421 ++fastTracks;
5422 } else {
5423 // was it previously active?
5424 if (state->mTrackMask & (1 << j)) {
5425 fastTrack->mBufferProvider = NULL;
5426 fastTrack->mGeneration++;
5427 state->mTrackMask &= ~(1 << j);
5428 didModify = true;
5429 // If any fast tracks were removed, we must wait for acknowledgement
5430 // because we're about to decrement the last sp<> on those tracks.
5431 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5432 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005433 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5434 // AudioTrack may start (which may not be with a start() but with a write()
5435 // after underrun) and immediately paused or released. In that case the
5436 // FastTrack state hasn't had time to update.
5437 // TODO Remove the ALOGW when this theory is confirmed.
5438 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005439 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung959b5b82021-09-24 10:46:20 -07005440 j, (int)track->mState, state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005441 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005442 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005443 }
5444 tracksToRemove->add(track);
5445 // Avoids a misleading display in dumpsys
5446 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5447 }
jiabin245cdd92018-12-07 17:55:15 -08005448 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5449 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5450 didModify = true;
5451 }
Eric Laurent81784c32012-11-19 14:55:58 -08005452 continue;
5453 }
5454
5455 { // local variable scope to avoid goto warning
5456
5457 audio_track_cblk_t* cblk = track->cblk();
5458
5459 // The first time a track is added we wait
5460 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005461 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005462
5463 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005464 // use the trackId as the AudioMixer name.
5465 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005466 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005467 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005468 track->mChannelMask,
5469 track->mFormat,
5470 track->mSessionId);
5471 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005472 ALOGW("%s(): AudioMixer cannot create track(%d)"
5473 " mask %#x, format %#x, sessionId %d",
5474 __func__, trackId,
5475 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005476 tracksToRemove->add(track);
5477 track->invalidate(); // consider it dead.
5478 continue;
5479 }
5480 }
5481
Eric Laurent81784c32012-11-19 14:55:58 -08005482 // make sure that we have enough frames to mix one full buffer.
5483 // enforce this condition only once to enable draining the buffer in case the client
5484 // app does not call stop() and relies on underrun to stop:
5485 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5486 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005487 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005488 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005489 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005490
5491 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005492 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005493 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5494 // add frames already consumed but not yet released by the resampler
5495 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005496 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005497
Eric Laurent81784c32012-11-19 14:55:58 -08005498 uint32_t minFrames = 1;
5499 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5500 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005501 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005502 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005503
5504 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005505 if (ATRACE_ENABLED()) {
5506 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005507 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005508 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005509 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005510 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005511 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005512 !track->isPaused() && !track->isTerminated())
5513 {
Andy Hungc0691382018-09-12 18:01:57 -07005514 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005515
5516 mixedTracks++;
5517
Andy Hung69aed5f2014-02-25 17:24:40 -08005518 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5519 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005520 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005521 if (track->mainBuffer() != mSinkBuffer &&
5522 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005523 if (mEffectBufferEnabled) {
5524 mEffectBufferValid = true; // Later can set directly.
5525 }
Eric Laurent81784c32012-11-19 14:55:58 -08005526 chain = getEffectChain_l(track->sessionId());
5527 // Delegate volume control to effect in track effect chain if needed
5528 if (chain != 0) {
5529 tracksWithEffect++;
5530 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005531 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005532 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005533 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005534 }
5535 }
5536
5537
5538 int param = AudioMixer::VOLUME;
5539 if (track->mFillingUpStatus == Track::FS_FILLED) {
5540 // no ramp for the first volume setting
5541 track->mFillingUpStatus = Track::FS_ACTIVE;
5542 if (track->mState == TrackBase::RESUMING) {
5543 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005544 // If a new track is paused immediately after start, do not ramp on resume.
5545 if (cblk->mServer != 0) {
5546 param = AudioMixer::RAMP_VOLUME;
5547 }
Eric Laurent81784c32012-11-19 14:55:58 -08005548 }
Andy Hungc0691382018-09-12 18:01:57 -07005549 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005550 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005551 // FIXME should not make a decision based on mServer
5552 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005553 // If the track is stopped before the first frame was mixed,
5554 // do not apply ramp
5555 param = AudioMixer::RAMP_VOLUME;
5556 }
5557
5558 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005559 uint32_t vl, vr; // in U8.24 integer format
5560 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005561 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005562 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005563 // Always fetch volumeshaper volume to ensure state is updated.
5564 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5565 const float vh = track->getVolumeHandler()->getVolume(
5566 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005567
Eric Laurenteab90452019-06-24 15:17:46 -07005568 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5569 v = 0;
5570 }
5571
5572 handleVoipVolume_l(&v);
5573
5574 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005575 vl = vr = 0;
5576 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005577 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005578 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005579 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005580 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5581 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005582 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005583 if (vlf > GAIN_FLOAT_UNITY) {
5584 ALOGV("Track left volume out of range: %.3g", vlf);
5585 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005586 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005587 if (vrf > GAIN_FLOAT_UNITY) {
5588 ALOGV("Track right volume out of range: %.3g", vrf);
5589 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005590 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005591 // now apply the master volume and stream type volume and shaper volume
5592 vlf *= v * vh;
5593 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005594 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005595 // then derive vl and vr as U8.24 versions for the effect chain
5596 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5597 vl = (uint32_t) (scaleto8_24 * vlf);
5598 vr = (uint32_t) (scaleto8_24 * vrf);
5599 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005600 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005601 // send level comes from shared memory and so may be corrupt
5602 if (sendLevel > MAX_GAIN_INT) {
5603 ALOGV("Track send level out of range: %04X", sendLevel);
5604 sendLevel = MAX_GAIN_INT;
5605 }
Andy Hung6be49402014-05-30 10:42:03 -07005606 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5607 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005608 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005609
Kevin Rocard12381092018-04-11 09:19:59 -07005610 track->setFinalVolume((vrf + vlf) / 2.f);
5611
Eric Laurent81784c32012-11-19 14:55:58 -08005612 // Delegate volume control to effect in track effect chain if needed
5613 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5614 // Do not ramp volume if volume is controlled by effect
5615 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005616 // Update remaining floating point volume levels
5617 vlf = (float)vl / (1 << 24);
5618 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005619 track->mHasVolumeController = true;
5620 } else {
5621 // force no volume ramp when volume controller was just disabled or removed
5622 // from effect chain to avoid volume spike
5623 if (track->mHasVolumeController) {
5624 param = AudioMixer::VOLUME;
5625 }
5626 track->mHasVolumeController = false;
5627 }
5628
Eric Laurent81784c32012-11-19 14:55:58 -08005629 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005630 mAudioMixer->setBufferProvider(trackId, track);
5631 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005632
Andy Hungc0691382018-09-12 18:01:57 -07005633 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5634 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5635 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005636 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005637 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005638 AudioMixer::TRACK,
5639 AudioMixer::FORMAT, (void *)track->format());
5640 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005641 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005642 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005643 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005644
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005645 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005646 mAudioMixer->setParameter(
5647 trackId,
5648 AudioMixer::TRACK,
5649 AudioMixer::MIXER_CHANNEL_MASK,
5650 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5651 } else {
5652 mAudioMixer->setParameter(
5653 trackId,
5654 AudioMixer::TRACK,
5655 AudioMixer::MIXER_CHANNEL_MASK,
5656 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5657 }
5658
Glenn Kastene3aa6592012-12-04 12:22:46 -08005659 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005660 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005661 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005662 if (reqSampleRate == 0) {
5663 reqSampleRate = mSampleRate;
5664 } else if (reqSampleRate > maxSampleRate) {
5665 reqSampleRate = maxSampleRate;
5666 }
Eric Laurent81784c32012-11-19 14:55:58 -08005667 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005668 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005669 AudioMixer::RESAMPLE,
5670 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005671 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005672
Andy Hung333ab962019-05-28 20:23:35 -07005673 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005674 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005675 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005676 AudioMixer::TIMESTRETCH,
5677 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005678 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005679
Andy Hung69aed5f2014-02-25 17:24:40 -08005680 /*
5681 * Select the appropriate output buffer for the track.
5682 *
Andy Hung98ef9782014-03-04 14:46:50 -08005683 * Tracks with effects go into their own effects chain buffer
5684 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005685 *
5686 * Other tracks can use mMixerBuffer for higher precision
5687 * channel accumulation. If this buffer is enabled
5688 * (mMixerBufferEnabled true), then selected tracks will accumulate
5689 * into it.
5690 *
5691 */
5692 if (mMixerBufferEnabled
5693 && (track->mainBuffer() == mSinkBuffer
5694 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005695 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005696 mAudioMixer->setParameter(
5697 trackId,
5698 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005699 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005700 mAudioMixer->setParameter(
5701 trackId,
5702 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005703 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005704 } else {
5705 mAudioMixer->setParameter(
5706 trackId,
5707 AudioMixer::TRACK,
5708 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5709 mAudioMixer->setParameter(
5710 trackId,
5711 AudioMixer::TRACK,
5712 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5713 // TODO: override track->mainBuffer()?
5714 mMixerBufferValid = true;
5715 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005716 } else {
5717 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005718 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005719 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005720 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005721 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005722 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005723 AudioMixer::TRACK,
5724 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5725 }
Eric Laurent81784c32012-11-19 14:55:58 -08005726 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005727 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005728 AudioMixer::TRACK,
5729 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005730 mAudioMixer->setParameter(
5731 trackId,
5732 AudioMixer::TRACK,
5733 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005734 mAudioMixer->setParameter(
5735 trackId,
5736 AudioMixer::TRACK,
5737 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Lais Andradebc3f37a2021-07-02 00:13:19 +01005738 mAudioMixer->setParameter(
5739 trackId,
5740 AudioMixer::TRACK,
5741 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)(&(track->mHapticMaxAmplitude)));
Eric Laurent81784c32012-11-19 14:55:58 -08005742
5743 // reset retry count
5744 track->mRetryCount = kMaxTrackRetries;
5745
5746 // If one track is ready, set the mixer ready if:
5747 // - the mixer was not ready during previous round OR
5748 // - no other track is not ready
5749 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5750 mixerStatus != MIXER_TRACKS_ENABLED) {
5751 mixerStatus = MIXER_TRACKS_READY;
5752 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005753
5754 // Enable the next few lines to instrument a test for underrun log handling.
5755 // TODO: Remove when we have a better way of testing the underrun log.
5756#if 0
5757 static int i;
5758 if ((++i & 0xf) == 0) {
5759 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5760 }
5761#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005762 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005763 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005764 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005765 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5766 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005767 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005768 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005769 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005770
Eric Laurent81784c32012-11-19 14:55:58 -08005771 // clear effect chain input buffer if an active track underruns to avoid sending
5772 // previous audio buffer again to effects
5773 chain = getEffectChain_l(track->sessionId());
5774 if (chain != 0) {
5775 chain->clearInputBuffer();
5776 }
5777
Andy Hungc0691382018-09-12 18:01:57 -07005778 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005779 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5780 track->isStopped() || track->isPaused()) {
5781 // We have consumed all the buffers of this track.
5782 // Remove it from the list of active tracks.
5783 // TODO: use actual buffer filling status instead of latency when available from
5784 // audio HAL
5785 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005786 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005787 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5788 if (track->isStopped()) {
5789 track->reset();
5790 }
5791 tracksToRemove->add(track);
5792 }
5793 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005794 // No buffers for this track. Give it a few chances to
5795 // fill a buffer, then remove it from active list.
5796 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005797 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5798 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005799 tracksToRemove->add(track);
5800 // indicate to client process that the track was disabled because of underrun;
5801 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005802 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005803 // If one track is not ready, mark the mixer also not ready if:
5804 // - the mixer was ready during previous round OR
5805 // - no other track is ready
5806 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5807 mixerStatus != MIXER_TRACKS_READY) {
5808 mixerStatus = MIXER_TRACKS_ENABLED;
5809 }
5810 }
Andy Hungc0691382018-09-12 18:01:57 -07005811 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005812 }
5813
5814 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005815
5816 }
5817
jiabin245cdd92018-12-07 17:55:15 -08005818 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5819 // When there is no fast track playing haptic and FastMixer exists,
5820 // enabling the first FastTrack, which provides mixed data from normal
5821 // tracks, to play haptic data.
5822 FastTrack *fastTrack = &state->mFastTracks[0];
5823 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5824 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5825 didModify = true;
5826 }
5827 }
5828
Eric Laurent81784c32012-11-19 14:55:58 -08005829 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08005830 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005831 if (didModify) {
5832 state->mFastTracksGen++;
5833 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5834 if (kUseFastMixer == FastMixer_Dynamic &&
5835 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5836 state->mCommand = FastMixerState::COLD_IDLE;
5837 state->mColdFutexAddr = &mFastMixerFutex;
5838 state->mColdGen++;
5839 mFastMixerFutex = 0;
5840 if (kUseFastMixer == FastMixer_Dynamic) {
5841 mNormalSink = mOutputSink;
5842 }
5843 // If we go into cold idle, need to wait for acknowledgement
5844 // so that fast mixer stops doing I/O.
5845 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5846 pauseAudioWatchdog = true;
5847 }
Eric Laurent81784c32012-11-19 14:55:58 -08005848 }
5849 if (sq != NULL) {
5850 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005851 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5852 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5853 // when bringing the output sink into standby.)
5854 //
5855 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5856 //
5857 // This occurs with BT suspend when we idle the FastMixer with
5858 // active tracks, which may be added or removed.
5859 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005860 }
5861#ifdef AUDIO_WATCHDOG
5862 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5863 mAudioWatchdog->pause();
5864 }
5865#endif
5866
5867 // Now perform the deferred reset on fast tracks that have stopped
5868 while (resetMask != 0) {
5869 size_t i = __builtin_ctz(resetMask);
5870 ALOG_ASSERT(i < count);
5871 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005872 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005873 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5874 track->reset();
5875 }
5876
Andy Hung80d03d22018-04-10 10:32:11 -07005877 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5878 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5879 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5880 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5881 // See also the implementation of destroyTrack_l().
5882 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005883 const int trackId = track->id();
5884 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5885 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005886 }
5887 }
5888
Eric Laurent81784c32012-11-19 14:55:58 -08005889 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005890 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005891
Eric Laurentb3f315a2021-07-13 15:09:05 +02005892 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
5893 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07005894 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005895 }
5896
5897 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005898 // as long as there are effects we should clear the effects buffer, to avoid
5899 // passing a non-clean buffer to the effect chain
5900 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02005901 if (mType == SPATIALIZER) {
5902 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
5903 }
Eric Laurent97d547d2014-09-02 14:45:53 -07005904 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005905 // sink or mix buffer must be cleared if all tracks are connected to an
5906 // effect chain as in this case the mixer will not write to the sink or mix buffer
5907 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02005908 // always clear sink buffer for spatializer output as the output of the spatializer
5909 // effect will be accumulated into it
5910 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5911 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005912 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005913 if (mMixerBufferValid) {
5914 memset(mMixerBuffer, 0, mMixerBufferSize);
5915 // TODO: In testing, mSinkBuffer below need not be cleared because
5916 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5917 // after mixing.
5918 //
5919 // To enforce this guarantee:
5920 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5921 // (mixedTracks == 0 && fastTracks > 0))
5922 // must imply MIXER_TRACKS_READY.
5923 // Later, we may clear buffers regardless, and skip much of this logic.
5924 }
Andy Hung98ef9782014-03-04 14:46:50 -08005925 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005926 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005927 }
5928
5929 // if any fast tracks, then status is ready
5930 mMixerStatusIgnoringFastTracks = mixerStatus;
5931 if (fastTracks > 0) {
5932 mixerStatus = MIXER_TRACKS_READY;
5933 }
5934 return mixerStatus;
5935}
5936
Eric Laurentad7dd962016-09-22 12:38:37 -07005937// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005938uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005939{
5940 uint32_t trackCount = 0;
5941 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005942 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005943 trackCount++;
5944 }
5945 }
5946 return trackCount;
5947}
5948
Brian Lindahl9e661ad2022-07-27 18:01:07 +02005949bool AudioFlinger::PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut * output)
ziyangch8f194f12021-12-01 13:48:04 -08005950{
Brian Lindahl9e661ad2022-07-27 18:01:07 +02005951 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
5952 // could falsely detect that the frame position has stalled due to underrun because we haven't
5953 // given the Audio HAL enough time to update.
5954 const nsecs_t nowNs = systemTime();
5955 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
5956 return mLatchedValue;
5957 }
5958 mPreviousNs = nowNs;
5959 mLatchedValue = false;
5960 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08005961 uint64_t position = 0;
5962 struct timespec unused;
Brian Lindahl9e661ad2022-07-27 18:01:07 +02005963 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08005964 if (ret == NO_ERROR) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02005965 if (position != mPreviousPosition) {
5966 mPreviousPosition = position;
5967 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08005968 }
5969 }
Brian Lindahl9e661ad2022-07-27 18:01:07 +02005970 return mLatchedValue;
5971}
5972
5973void AudioFlinger::PlaybackThread::IsTimestampAdvancing::clear()
5974{
5975 mLatchedValue = true;
5976 mPreviousPosition = 0;
5977 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08005978}
5979
Andy Hung1bc088a2018-02-09 15:57:31 -08005980// isTrackAllowed_l() must be called with ThreadBase::mLock held
5981bool AudioFlinger::MixerThread::isTrackAllowed_l(
5982 audio_channel_mask_t channelMask, audio_format_t format,
5983 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005984{
Andy Hung1bc088a2018-02-09 15:57:31 -08005985 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5986 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005987 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005988 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005989 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005990 ALOGW("%s: invalid format: %#x", __func__, format);
5991 return false;
5992 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005993 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005994 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5995 return false;
5996 }
5997 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005998}
5999
Eric Laurent10351942014-05-08 18:49:52 -07006000// checkForNewParameter_l() must be called with ThreadBase::mLock held
6001bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
6002 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006003{
Eric Laurent81784c32012-11-19 14:55:58 -08006004 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006005 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006006
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006007 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006008
Eric Laurent10351942014-05-08 18:49:52 -07006009 AudioParameter param = AudioParameter(keyValuePair);
6010 int value;
6011 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6012 reconfig = true;
6013 }
6014 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07006015 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006016 status = BAD_VALUE;
6017 } else {
6018 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006019 reconfig = true;
6020 }
Eric Laurent10351942014-05-08 18:49:52 -07006021 }
6022 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07006023 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006024 status = BAD_VALUE;
6025 } else {
6026 // no need to save value, since it's constant
6027 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006028 }
Eric Laurent10351942014-05-08 18:49:52 -07006029 }
6030 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6031 // do not accept frame count changes if tracks are open as the track buffer
6032 // size depends on frame count and correct behavior would not be guaranteed
6033 // if frame count is changed after track creation
6034 if (!mTracks.isEmpty()) {
6035 status = INVALID_OPERATION;
6036 } else {
6037 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006038 }
Eric Laurent10351942014-05-08 18:49:52 -07006039 }
6040 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006041 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006042 }
Eric Laurent81784c32012-11-19 14:55:58 -08006043
Eric Laurent10351942014-05-08 18:49:52 -07006044 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006045 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006046 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006047 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006048 if (!mStandby) {
6049 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006050 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07006051 mStandby = true;
6052 }
Eric Laurent10351942014-05-08 18:49:52 -07006053 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006054 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006055 }
Eric Laurent10351942014-05-08 18:49:52 -07006056 if (status == NO_ERROR && reconfig) {
6057 readOutputParameters_l();
6058 delete mAudioMixer;
6059 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006060 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006061 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08006062 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006063 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08006064 track->mChannelMask,
6065 track->mFormat,
6066 track->mSessionId);
6067 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006068 "%s(): AudioMixer cannot create track(%d)"
6069 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006070 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07006071 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07006072 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006073 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006074 }
Eric Laurent81784c32012-11-19 14:55:58 -08006075 }
6076
Dean Wheatley68918102021-03-19 22:09:19 +11006077 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006078}
6079
6080
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006081void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006082{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006083 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006084 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006085 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006086 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006087 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6088 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6089 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006090 if (hasFastMixer()) {
6091 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6092
6093 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6094 // while we are dumping it. It may be inconsistent, but it won't mutate!
6095 // This is a large object so we place it on the heap.
6096 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006097 const std::unique_ptr<FastMixerDumpState> copy =
6098 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006099 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006100
6101#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006102 // Similar for state queue
6103 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6104 observerCopy.dump(fd);
6105 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6106 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006107#endif
6108
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006109#ifdef AUDIO_WATCHDOG
6110 if (mAudioWatchdog != 0) {
6111 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6112 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6113 wdCopy.dump(fd);
6114 }
6115#endif
6116
6117 } else {
6118 dprintf(fd, " No FastMixer\n");
6119 }
Eric Laurent81784c32012-11-19 14:55:58 -08006120}
6121
6122uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
6123{
6124 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6125}
6126
6127uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
6128{
6129 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6130}
6131
6132void AudioFlinger::MixerThread::cacheParameters_l()
6133{
6134 PlaybackThread::cacheParameters_l();
6135
6136 // FIXME: Relaxed timing because of a certain device that can't meet latency
6137 // Should be reduced to 2x after the vendor fixes the driver issue
6138 // increase threshold again due to low power audio mode. The way this warning
6139 // threshold is calculated and its usefulness should be reconsidered anyway.
6140 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6141}
6142
6143// ----------------------------------------------------------------------------
6144
6145AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Gareth Fenn56576722022-10-05 13:42:36 -07006146 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6147 const audio_offload_info_t& offloadInfo)
jiabinc52b1ff2019-10-31 17:20:42 -07006148 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Gareth Fenn56576722022-10-05 13:42:36 -07006149 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006150{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006151 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006152}
6153
Eric Laurent81784c32012-11-19 14:55:58 -08006154AudioFlinger::DirectOutputThread::~DirectOutputThread()
6155{
6156}
6157
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006158void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006159{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006160 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006161 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6162 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6163}
6164
6165void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
6166{
6167 Mutex::Autolock _l(mLock);
6168 if (mMasterBalance != balance) {
6169 mMasterBalance.store(balance);
6170 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6171 broadcast_l();
6172 }
6173}
6174
Eric Laurent5850c4c2016-11-10 13:04:31 -08006175void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006176{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006177 float left, right;
6178
Andy Hung333ab962019-05-28 20:23:35 -07006179 // Ensure volumeshaper state always advances even when muted.
6180 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
6181 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
6182 proxy->framesReleased());
6183 mVolumeShaperActive = shaperActive;
6184
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006185 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006186 left = right = 0;
6187 } else {
6188 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006189 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006190
Glenn Kastenc56f3422014-03-21 17:53:17 -07006191 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6192 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6193 if (left > GAIN_FLOAT_UNITY) {
6194 left = GAIN_FLOAT_UNITY;
6195 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006196 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07006197 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6198 if (right > GAIN_FLOAT_UNITY) {
6199 right = GAIN_FLOAT_UNITY;
6200 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006201 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006202 }
6203
6204 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07006205 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006206 if (left != mLeftVolFloat || right != mRightVolFloat) {
6207 mLeftVolFloat = left;
6208 mRightVolFloat = right;
6209
Eric Laurentbfb1b832013-01-07 09:53:42 -08006210 // Delegate volume control to effect in track effect chain if needed
6211 // only one effect chain can be present on DirectOutputThread, so if
6212 // there is one, the track is connected to it
6213 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006214 // if effect chain exists, volume is handled by it.
6215 // Convert volumes from float to 8.24
6216 uint32_t vl = (uint32_t)(left * (1 << 24));
6217 uint32_t vr = (uint32_t)(right * (1 << 24));
6218 // Direct/Offload effect chains set output volume in setVolume_l().
6219 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6220 } else {
6221 // otherwise we directly set the volume.
6222 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006223 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006224 }
6225 }
6226}
6227
Phil Burk43b4dcc2015-06-09 16:53:44 -07006228void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
6229{
6230 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07006231 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006232
Eric Laurent0f0631e2015-07-06 18:01:25 -07006233 if (previousTrack != 0 && latestTrack != 0) {
6234 if (mType == DIRECT) {
6235 if (previousTrack.get() != latestTrack.get()) {
6236 mFlushPending = true;
6237 }
6238 } else /* mType == OFFLOAD */ {
6239 if (previousTrack->sessionId() != latestTrack->sessionId()) {
6240 mFlushPending = true;
6241 }
6242 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006243 } else if (previousTrack == 0) {
6244 // there could be an old track added back during track transition for direct
6245 // output, so always issues flush to flush data of the previous track if it
6246 // was already destroyed with HAL paused, then flush can resume the playback
6247 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006248 }
6249 PlaybackThread::onAddNewTrack_l();
6250}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006251
Eric Laurent81784c32012-11-19 14:55:58 -08006252AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
6253 Vector< sp<Track> > *tracksToRemove
6254)
6255{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006256 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006257 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006258 bool doHwPause = false;
6259 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006260
6261 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006262 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006263 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006264 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006265 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006266 continue;
6267 }
6268
Eric Laurent5850c4c2016-11-10 13:04:31 -08006269 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006270#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006271 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006272#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006273 // Only consider last track started for volume and mixer state control.
6274 // In theory an older track could underrun and restart after the new one starts
6275 // but as we only care about the transition phase between two tracks on a
6276 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006277 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006278 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006279
Kuowei Li23666472021-01-20 10:23:25 +08006280 if (track->isPausePending()) {
6281 track->pauseAck();
6282 // It is possible a track might have been flushed or stopped.
6283 // Other operations such as flush pending might occur on the next prepare.
6284 if (track->isPausing()) {
6285 track->setPaused();
6286 }
6287 // Always perform pause, as an immediate flush will change
6288 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006289 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006290 doHwPause = true;
6291 mHwPaused = true;
6292 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006293 } else if (track->isFlushPending()) {
6294 track->flushAck();
6295 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006296 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006297 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006298 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006299 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006300 if (last) {
6301 mLeftVolFloat = mRightVolFloat = -1.0;
6302 if (mHwPaused) {
6303 doHwResume = true;
6304 mHwPaused = false;
6305 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006306 }
6307 }
6308
Eric Laurent81784c32012-11-19 14:55:58 -08006309 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006310 // for all its buffers to be filled before processing it.
6311 // Allow draining the buffer in case the client
6312 // app does not call stop() and relies on underrun to stop:
6313 // hence the test on (track->mRetryCount > 1).
Andy Hung455982f2021-04-27 17:46:12 -07006314 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
6315 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6316 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006317 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006318
6319 // target retry count that we will use is based on the time we wait for retries.
6320 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6321 // the retry threshold is when we accept any size for PCM data. This is slightly
6322 // smaller than the retry count so we can push small bits of data without a glitch.
6323 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006324 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006325 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung455982f2021-04-27 17:46:12 -07006326 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006327 minFrames = mNormalFrameCount;
6328 } else {
6329 minFrames = 1;
6330 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006331
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006332 const size_t framesReady = track->framesReady();
6333 const int trackId = track->id();
6334 if (ATRACE_ENABLED()) {
6335 std::string traceName("nRdy");
6336 traceName += std::to_string(trackId);
6337 ATRACE_INT(traceName.c_str(), framesReady);
6338 }
6339 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006340 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006341 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006342 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006343
6344 if (track->mFillingUpStatus == Track::FS_FILLED) {
6345 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006346 if (last) {
6347 // make sure processVolume_l() will apply new volume even if 0
6348 mLeftVolFloat = mRightVolFloat = -1.0;
6349 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006350 if (!mHwSupportsPause) {
6351 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006352 }
6353 }
6354
6355 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006356 processVolume_l(track, last);
6357 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006358 sp<Track> previousTrack = mPreviousTrack.promote();
6359 if (previousTrack != 0) {
6360 if (track != previousTrack.get()) {
6361 // Flush any data still being written from last track
6362 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006363 // Invalidate previous track to force a seek when resuming.
6364 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006365 }
6366 }
6367 mPreviousTrack = track;
6368
Eric Laurentd595b7c2013-04-03 17:27:56 -07006369 // reset retry count
Andy Hung455982f2021-04-27 17:46:12 -07006370 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006371 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006372 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006373 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006374 doHwResume = true;
6375 mHwPaused = false;
6376 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006377 }
Eric Laurent81784c32012-11-19 14:55:58 -08006378 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006379 // clear effect chain input buffer if the last active track started underruns
6380 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006381 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006382 mEffectChains[0]->clearInputBuffer();
6383 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006384 if (track->isStopping_1()) {
6385 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07006386 if (last && mHwPaused) {
6387 doHwResume = true;
6388 mHwPaused = false;
6389 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006390 }
6391 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6392 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006393 // We have consumed all the buffers of this track.
6394 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006395 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006396 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006397 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006398 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006399 if (presComplete) {
6400 mOutput->presentationComplete();
6401 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006402 if (track->isStopping_2()) {
6403 track->mState = TrackBase::STOPPED;
6404 }
Eric Laurent81784c32012-11-19 14:55:58 -08006405 if (track->isStopped()) {
6406 track->reset();
6407 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006408 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006409 }
6410 } else {
6411 // No buffers for this track. Give it a few chances to
6412 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006413 // Only consider last track started for mixer state control
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006414 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07006415 if (!isTunerStream() // tuner streams remain active in underrun
6416 && --(track->mRetryCount) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006417 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
ziyangch8f194f12021-12-01 13:48:04 -08006418 track->mRetryCount = kMaxTrackRetriesOffload;
6419 } else {
6420 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6421 tracksToRemove->add(track);
6422 // indicate to client process that the track was disabled because of
6423 // underrun; it will then automatically call start() when data is available
6424 track->disable();
6425 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6426 // unlike mixerthread, HAL can be paused for direct output
6427 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6428 "minFrames = %u, mFormat = %#x",
6429 framesReady, minFrames, mFormat);
6430 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6431 doHwPause = true;
6432 mHwPaused = true;
6433 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006434 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006435 } else if (last) {
6436 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006437 }
6438 }
6439 }
6440 }
6441
Eric Laurentd1f69b02014-12-15 14:33:13 -08006442 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006443 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006444 for (size_t i = 0; i < mTracks.size(); i++) {
6445 if (mTracks[i]->isFlushPending()) {
6446 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006447 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006448 }
6449 }
6450 }
6451
6452 // make sure the pause/flush/resume sequence is executed in the right order.
6453 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6454 // before flush and then resume HW. This can happen in case of pause/flush/resume
6455 // if resume is received before pause is executed.
6456 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006457 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006458 status_t result = mOutput->stream->pause();
6459 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006460 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006461 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006462 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006463 flushHw_l();
6464 }
6465 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006466 status_t result = mOutput->stream->resume();
6467 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006468 }
Eric Laurent81784c32012-11-19 14:55:58 -08006469 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006470 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006471
6472 return mixerStatus;
6473}
6474
6475void AudioFlinger::DirectOutputThread::threadLoop_mix()
6476{
Eric Laurent81784c32012-11-19 14:55:58 -08006477 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006478 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006479 // output audio to hardware
6480 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006481 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006482 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006483 status_t status = mActiveTrack->getNextBuffer(&buffer);
6484 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006485 // no need to pad with 0 for compressed audio
6486 if (audio_has_proportional_frames(mFormat)) {
6487 memset(curBuf, 0, frameCount * mFrameSize);
6488 }
Eric Laurent81784c32012-11-19 14:55:58 -08006489 break;
6490 }
6491 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6492 frameCount -= buffer.frameCount;
6493 curBuf += buffer.frameCount * mFrameSize;
6494 mActiveTrack->releaseBuffer(&buffer);
6495 }
Andy Hung2098f272014-02-27 14:00:06 -08006496 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006497 mSleepTimeUs = 0;
6498 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006499 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006500}
6501
6502void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6503{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006504 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006505 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006506 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006507 return;
6508 }
Andy Hung85ba3332021-04-27 17:40:26 -07006509 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6510 mSleepTimeUs = mActiveSleepTimeUs;
6511 } else {
6512 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006513 }
Andy Hung85ba3332021-04-27 17:40:26 -07006514 // Note: In S or later, we do not write zeroes for
6515 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006516}
6517
Eric Laurentd1f69b02014-12-15 14:33:13 -08006518void AudioFlinger::DirectOutputThread::threadLoop_exit()
6519{
6520 {
6521 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006522 for (size_t i = 0; i < mTracks.size(); i++) {
6523 if (mTracks[i]->isFlushPending()) {
6524 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006525 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006526 }
6527 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006528 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006529 flushHw_l();
6530 }
6531 }
6532 PlaybackThread::threadLoop_exit();
6533}
6534
6535// must be called with thread mutex locked
6536bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6537{
6538 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006539 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006540
6541 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6542 // after a timeout and we will enter standby then.
6543 if (mTracks.size() > 0) {
6544 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006545 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6546 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006547 }
6548
Eric Laurent5cff4032015-05-26 13:49:58 -07006549 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006550}
6551
Eric Laurent10351942014-05-08 18:49:52 -07006552// checkForNewParameter_l() must be called with ThreadBase::mLock held
6553bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6554 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006555{
6556 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006557 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006558
Eric Laurent10351942014-05-08 18:49:52 -07006559 AudioParameter param = AudioParameter(keyValuePair);
6560 int value;
6561 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006562 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006563 }
Eric Laurent10351942014-05-08 18:49:52 -07006564 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6565 // do not accept frame count changes if tracks are open as the track buffer
6566 // size depends on frame count and correct behavior would not be garantied
6567 // if frame count is changed after track creation
6568 if (!mTracks.isEmpty()) {
6569 status = INVALID_OPERATION;
6570 } else {
6571 reconfig = true;
6572 }
6573 }
6574 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006575 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006576 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006577 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006578 if (!mStandby) {
6579 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006580 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07006581 mStandby = true;
6582 }
Eric Laurent10351942014-05-08 18:49:52 -07006583 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006584 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006585 }
6586 if (status == NO_ERROR && reconfig) {
6587 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006588 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006589 }
6590 }
6591
Dean Wheatley68918102021-03-19 22:09:19 +11006592 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006593}
6594
6595uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6596{
6597 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006598 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006599 time = PlaybackThread::activeSleepTimeUs();
6600 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006601 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006602 }
6603 return time;
6604}
6605
6606uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6607{
6608 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006609 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006610 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6611 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006612 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006613 }
6614 return time;
6615}
6616
6617uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6618{
6619 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006620 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006621 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6622 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006623 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006624 }
6625 return time;
6626}
6627
6628void AudioFlinger::DirectOutputThread::cacheParameters_l()
6629{
6630 PlaybackThread::cacheParameters_l();
6631
6632 // use shorter standby delay as on normal output to release
6633 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006634 // no delay on outputs with HW A/V sync
6635 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006636 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006637 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006638 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006639 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006640 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006641 }
Eric Laurent81784c32012-11-19 14:55:58 -08006642}
6643
Eric Laurente659ef42014-09-29 13:06:46 -07006644void AudioFlinger::DirectOutputThread::flushHw_l()
6645{
ziyangch8f194f12021-12-01 13:48:04 -08006646 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08006647 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006648 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006649 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006650 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006651 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006652}
6653
Andy Hung10cbff12017-02-21 17:30:14 -08006654int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6655 // If a VolumeShaper is active, we must wake up periodically to update volume.
6656 const int64_t NS_PER_MS = 1000000;
6657 return mVolumeShaperActive ?
6658 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6659}
6660
Eric Laurent81784c32012-11-19 14:55:58 -08006661// ----------------------------------------------------------------------------
6662
Eric Laurentbfb1b832013-01-07 09:53:42 -08006663AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006664 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006665 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006666 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006667 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006668 mDrainSequence(0),
6669 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006670{
6671}
6672
6673AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6674{
6675}
6676
6677void AudioFlinger::AsyncCallbackThread::onFirstRef()
6678{
6679 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6680}
6681
6682bool AudioFlinger::AsyncCallbackThread::threadLoop()
6683{
6684 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006685 uint32_t writeAckSequence;
6686 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006687 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006688
6689 {
6690 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006691 while (!((mWriteAckSequence & 1) ||
6692 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006693 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006694 exitPending())) {
6695 mWaitWorkCV.wait(mLock);
6696 }
6697
Eric Laurentbfb1b832013-01-07 09:53:42 -08006698 if (exitPending()) {
6699 break;
6700 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006701 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6702 mWriteAckSequence, mDrainSequence);
6703 writeAckSequence = mWriteAckSequence;
6704 mWriteAckSequence &= ~1;
6705 drainSequence = mDrainSequence;
6706 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006707 asyncError = mAsyncError;
6708 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006709 }
6710 {
Eric Laurent4de95592013-09-26 15:28:21 -07006711 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6712 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006713 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006714 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006715 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006716 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006717 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006718 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006719 if (asyncError) {
6720 playbackThread->onAsyncError();
6721 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006722 }
6723 }
6724 }
6725 return false;
6726}
6727
6728void AudioFlinger::AsyncCallbackThread::exit()
6729{
6730 ALOGV("AsyncCallbackThread::exit");
6731 Mutex::Autolock _l(mLock);
6732 requestExit();
6733 mWaitWorkCV.broadcast();
6734}
6735
Eric Laurent3b4529e2013-09-05 18:09:19 -07006736void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006737{
6738 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006739 // bit 0 is cleared
6740 mWriteAckSequence = sequence << 1;
6741}
6742
6743void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6744{
6745 Mutex::Autolock _l(mLock);
6746 // ignore unexpected callbacks
6747 if (mWriteAckSequence & 2) {
6748 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006749 mWaitWorkCV.signal();
6750 }
6751}
6752
Eric Laurent3b4529e2013-09-05 18:09:19 -07006753void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006754{
6755 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006756 // bit 0 is cleared
6757 mDrainSequence = sequence << 1;
6758}
6759
6760void AudioFlinger::AsyncCallbackThread::resetDraining()
6761{
6762 Mutex::Autolock _l(mLock);
6763 // ignore unexpected callbacks
6764 if (mDrainSequence & 2) {
6765 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006766 mWaitWorkCV.signal();
6767 }
6768}
6769
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006770void AudioFlinger::AsyncCallbackThread::setAsyncError()
6771{
6772 Mutex::Autolock _l(mLock);
6773 mAsyncError = true;
6774 mWaitWorkCV.signal();
6775}
6776
Eric Laurentbfb1b832013-01-07 09:53:42 -08006777
6778// ----------------------------------------------------------------------------
6779AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Gareth Fenn56576722022-10-05 13:42:36 -07006780 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6781 const audio_offload_info_t& offloadInfo)
6782 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08006783 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006784{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006785 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006786 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006787 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006788}
6789
Eric Laurentbfb1b832013-01-07 09:53:42 -08006790void AudioFlinger::OffloadThread::threadLoop_exit()
6791{
6792 if (mFlushPending || mHwPaused) {
6793 // If a flush is pending or track was paused, just discard buffered data
6794 flushHw_l();
6795 } else {
6796 mMixerStatus = MIXER_DRAIN_ALL;
6797 threadLoop_drain();
6798 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006799 if (mUseAsyncWrite) {
6800 ALOG_ASSERT(mCallbackThread != 0);
6801 mCallbackThread->exit();
6802 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006803 PlaybackThread::threadLoop_exit();
6804}
6805
6806AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6807 Vector< sp<Track> > *tracksToRemove
6808)
6809{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006810 size_t count = mActiveTracks.size();
6811
6812 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006813 bool doHwPause = false;
6814 bool doHwResume = false;
6815
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006816 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006817
Eric Laurentbfb1b832013-01-07 09:53:42 -08006818 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006819 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006820 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006821#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006822 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006823#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006824 // Only consider last track started for volume and mixer state control.
6825 // In theory an older track could underrun and restart after the new one starts
6826 // but as we only care about the transition phase between two tracks on a
6827 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006828 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006829 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006830
Haynes Mathew George7844f672014-01-15 12:32:55 -08006831 if (track->isInvalid()) {
6832 ALOGW("An invalidated track shouldn't be in active list");
6833 tracksToRemove->add(track);
6834 continue;
6835 }
6836
6837 if (track->mState == TrackBase::IDLE) {
6838 ALOGW("An idle track shouldn't be in active list");
6839 continue;
6840 }
6841
Kuowei Li23666472021-01-20 10:23:25 +08006842 if (track->isPausePending()) {
6843 track->pauseAck();
6844 // It is possible a track might have been flushed or stopped.
6845 // Other operations such as flush pending might occur on the next prepare.
6846 if (track->isPausing()) {
6847 track->setPaused();
6848 }
6849 // Always perform pause if last, as an immediate flush will change
6850 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006851 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006852 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006853 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006854 mHwPaused = true;
6855 }
6856 // If we were part way through writing the mixbuffer to
6857 // the HAL we must save this until we resume
6858 // BUG - this will be wrong if a different track is made active,
6859 // in that case we want to discard the pending data in the
6860 // mixbuffer and tell the client to present it again when the
6861 // track is resumed
6862 mPausedWriteLength = mCurrentWriteLength;
6863 mPausedBytesRemaining = mBytesRemaining;
6864 mBytesRemaining = 0; // stop writing
6865 }
6866 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006867 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006868 if (track->isStopping_1()) {
6869 track->mRetryCount = kMaxTrackStopRetriesOffload;
6870 } else {
6871 track->mRetryCount = kMaxTrackRetriesOffload;
6872 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006873 track->flushAck();
6874 if (last) {
6875 mFlushPending = true;
6876 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006877 } else if (track->isResumePending()){
6878 track->resumeAck();
6879 if (last) {
6880 if (mPausedBytesRemaining) {
6881 // Need to continue write that was interrupted
6882 mCurrentWriteLength = mPausedWriteLength;
6883 mBytesRemaining = mPausedBytesRemaining;
6884 mPausedBytesRemaining = 0;
6885 }
6886 if (mHwPaused) {
6887 doHwResume = true;
6888 mHwPaused = false;
6889 // threadLoop_mix() will handle the case that we need to
6890 // resume an interrupted write
6891 }
6892 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006893 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006894
Eric Laurent3df841a2016-07-15 15:15:40 -07006895 mLeftVolFloat = mRightVolFloat = -1.0;
6896
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006897 // Do not handle new data in this iteration even if track->framesReady()
6898 mixerStatus = MIXER_TRACKS_ENABLED;
6899 }
6900 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006901 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006902 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006903 if (track->mFillingUpStatus == Track::FS_FILLED) {
6904 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006905 if (last) {
6906 // make sure processVolume_l() will apply new volume even if 0
6907 mLeftVolFloat = mRightVolFloat = -1.0;
6908 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006909 }
6910
6911 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006912 sp<Track> previousTrack = mPreviousTrack.promote();
6913 if (previousTrack != 0) {
6914 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006915 // Flush any data still being written from last track
6916 mBytesRemaining = 0;
6917 if (mPausedBytesRemaining) {
6918 // Last track was paused so we also need to flush saved
6919 // mixbuffer state and invalidate track so that it will
6920 // re-submit that unwritten data when it is next resumed
6921 mPausedBytesRemaining = 0;
6922 // Invalidate is a bit drastic - would be more efficient
6923 // to have a flag to tell client that some of the
6924 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006925 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006926 }
6927 // flush data already sent to the DSP if changing audio session as audio
6928 // comes from a different source. Also invalidate previous track to force a
6929 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006930 if (previousTrack->sessionId() != track->sessionId()) {
6931 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006932 }
6933 }
6934 }
6935 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006936 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006937 if (track->isStopping_1()) {
6938 track->mRetryCount = kMaxTrackStopRetriesOffload;
6939 } else {
6940 track->mRetryCount = kMaxTrackRetriesOffload;
6941 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006942 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006943 mixerStatus = MIXER_TRACKS_READY;
6944 }
6945 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006946 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006947 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006948 if (--(track->mRetryCount) <= 0) {
6949 // Hardware buffer can hold a large amount of audio so we must
6950 // wait for all current track's data to drain before we say
6951 // that the track is stopped.
6952 if (mBytesRemaining == 0) {
6953 // Only start draining when all data in mixbuffer
6954 // has been written
6955 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6956 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6957 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6958 if (last && !mStandby) {
6959 // do not modify drain sequence if we are already draining. This happens
6960 // when resuming from pause after drain.
6961 if ((mDrainSequence & 1) == 0) {
6962 mSleepTimeUs = 0;
6963 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6964 mixerStatus = MIXER_DRAIN_TRACK;
6965 mDrainSequence += 2;
6966 }
6967 if (mHwPaused) {
6968 // It is possible to move from PAUSED to STOPPING_1 without
6969 // a resume so we must ensure hardware is running
6970 doHwResume = true;
6971 mHwPaused = false;
6972 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006973 }
6974 }
Eric Laurente93cc032016-05-05 10:15:10 -07006975 } else if (last) {
6976 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6977 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006978 }
6979 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006980 // Drain has completed or we are in standby, signal presentation complete
6981 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006982 track->mState = TrackBase::STOPPED;
Atneya Nair0cae0432022-05-10 18:12:12 -04006983 mOutput->presentationComplete();
6984 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08006985 track->reset();
6986 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006987 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006988 if (!mUseAsyncWrite) {
6989 // If we don't get explicit drain notification we must
6990 // register discontinuity regardless of whether this is
6991 // the previous (!last) or the upcoming (last) track
6992 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006993 mTimestampVerifier.discontinuity(
6994 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006995 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006996 }
6997 } else {
6998 // No buffers for this track. Give it a few chances to
6999 // fill a buffer, then remove it from active list.
Brian Lindahl9e661ad2022-07-27 18:01:07 +02007000 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07007001 if (!isTunerStream() // tuner streams remain active in underrun
7002 && --(track->mRetryCount) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02007003 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hungf8044752016-07-27 14:58:11 -07007004 track->mRetryCount = kMaxTrackRetriesOffload;
7005 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007006 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7007 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007008 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007009 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007010 // it will then automatically call start() when data is available
7011 track->disable();
7012 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007013 } else if (last){
7014 mixerStatus = MIXER_TRACKS_ENABLED;
7015 }
7016 }
7017 }
7018 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007019 if (track->isReady()) { // check ready to prevent premature start.
7020 processVolume_l(track, last);
7021 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007022 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007023
Eric Laurentea0fade2013-10-04 16:23:48 -07007024 // make sure the pause/flush/resume sequence is executed in the right order.
7025 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7026 // before flush and then resume HW. This can happen in case of pause/flush/resume
7027 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007028 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007029 status_t result = mOutput->stream->pause();
7030 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007031 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007032 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007033 if (mFlushPending) {
7034 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007035 }
Eric Laurentfd477972013-10-25 18:10:40 -07007036 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007037 status_t result = mOutput->stream->resume();
7038 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007039 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007040
Eric Laurentbfb1b832013-01-07 09:53:42 -08007041 // remove all the tracks that need to be...
7042 removeTracks_l(*tracksToRemove);
7043
7044 return mixerStatus;
7045}
7046
Eric Laurentbfb1b832013-01-07 09:53:42 -08007047// must be called with thread mutex locked
7048bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
7049{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007050 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7051 mWriteAckSequence, mDrainSequence);
7052 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007053 return true;
7054 }
7055 return false;
7056}
7057
Eric Laurentbfb1b832013-01-07 09:53:42 -08007058bool AudioFlinger::OffloadThread::waitingAsyncCallback()
7059{
7060 Mutex::Autolock _l(mLock);
7061 return waitingAsyncCallback_l();
7062}
7063
7064void AudioFlinger::OffloadThread::flushHw_l()
7065{
Eric Laurente659ef42014-09-29 13:06:46 -07007066 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007067 // Flush anything still waiting in the mixbuffer
7068 mCurrentWriteLength = 0;
7069 mBytesRemaining = 0;
7070 mPausedWriteLength = 0;
7071 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007072 // reset bytes written count to reflect that DSP buffers are empty after flush.
7073 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007074
Eric Laurentbfb1b832013-01-07 09:53:42 -08007075 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007076 // discard any pending drain or write ack by incrementing sequence
7077 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7078 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007079 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007080 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7081 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007082 }
7083}
7084
Haynes Mathew George05317d22016-05-03 16:34:26 -07007085void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
7086{
7087 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007088 if (PlaybackThread::invalidateTracks_l(streamType)) {
7089 mFlushPending = true;
7090 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007091}
7092
Eric Laurentbfb1b832013-01-07 09:53:42 -08007093// ----------------------------------------------------------------------------
7094
Eric Laurent81784c32012-11-19 14:55:58 -08007095AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07007096 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07007097 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007098 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007099 mWaitTimeMs(UINT_MAX)
7100{
7101 addOutputTrack(mainThread);
7102}
7103
7104AudioFlinger::DuplicatingThread::~DuplicatingThread()
7105{
7106 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7107 mOutputTracks[i]->destroy();
7108 }
7109}
7110
7111void AudioFlinger::DuplicatingThread::threadLoop_mix()
7112{
7113 // mix buffers...
7114 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007115 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007116 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007117 if (mMixerBufferValid) {
7118 memset(mMixerBuffer, 0, mMixerBufferSize);
7119 } else {
7120 memset(mSinkBuffer, 0, mSinkBufferSize);
7121 }
Eric Laurent81784c32012-11-19 14:55:58 -08007122 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007123 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007124 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007125 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007126 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007127}
7128
7129void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
7130{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007131 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007132 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007133 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007134 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007135 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007136 }
7137 } else if (mBytesWritten != 0) {
7138 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7139 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007140 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007141 } else {
7142 // flush remaining overflow buffers in output tracks
7143 writeFrames = 0;
7144 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007145 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007146 }
7147}
7148
Eric Laurentbfb1b832013-01-07 09:53:42 -08007149ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007150{
7151 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007152 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7153
7154 // Consider the first OutputTrack for timestamp and frame counting.
7155
7156 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7157 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7158 // we always claim success.
7159 if (i == 0) {
7160 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7161 ALOGD_IF(correction != 0 && writeFrames != 0,
7162 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7163 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7164 mFramesWritten -= correction;
7165 }
7166
7167 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007168 }
Andy Hungcf10d742020-04-28 15:38:24 -07007169 if (mStandby) {
7170 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007171 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007172 mStandby = false;
7173 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007174 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007175}
7176
7177void AudioFlinger::DuplicatingThread::threadLoop_standby()
7178{
7179 // DuplicatingThread implements standby by stopping all tracks
7180 for (size_t i = 0; i < outputTracks.size(); i++) {
7181 outputTracks[i]->stop();
7182 }
7183}
7184
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007185void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08007186{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007187 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007188
7189 std::stringstream ss;
7190 const size_t numTracks = mOutputTracks.size();
7191 ss << " " << numTracks << " OutputTracks";
7192 if (numTracks > 0) {
7193 ss << ":";
7194 for (const auto &track : mOutputTracks) {
7195 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007196 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007197 if (thread.get() != nullptr) {
7198 ss << thread.get() << ", " << thread->id();
7199 } else {
7200 ss << "null";
7201 }
7202 ss << ")";
7203 }
7204 }
7205 ss << "\n";
7206 std::string result = ss.str();
7207 write(fd, result.c_str(), result.size());
7208}
7209
Eric Laurent81784c32012-11-19 14:55:58 -08007210void AudioFlinger::DuplicatingThread::saveOutputTracks()
7211{
7212 outputTracks = mOutputTracks;
7213}
7214
7215void AudioFlinger::DuplicatingThread::clearOutputTracks()
7216{
7217 outputTracks.clear();
7218}
7219
7220void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
7221{
7222 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007223 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7224 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7225 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7226 const size_t frameCount =
7227 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7228 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7229 // from different OutputTracks and their associated MixerThreads (e.g. one may
7230 // nearly empty and the other may be dropping data).
7231
Svet Ganov33761132021-05-13 22:51:08 +00007232 // TODO b/182392769: use attribution source util, move to server edge
7233 AttributionSourceState attributionSource = AttributionSourceState();
7234 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007235 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007236 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007237 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007238 attributionSource.token = sp<BBinder>::make();
Andy Hungc25b84a2015-01-14 19:04:10 -08007239 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007240 this,
7241 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007242 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007243 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007244 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007245 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007246 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7247 if (status != NO_ERROR) {
7248 ALOGE("addOutputTrack() initCheck failed %d", status);
7249 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007250 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007251 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7252 mOutputTracks.add(outputTrack);
7253 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7254 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007255}
7256
7257void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
7258{
7259 Mutex::Autolock _l(mLock);
7260 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7261 if (mOutputTracks[i]->thread() == thread) {
7262 mOutputTracks[i]->destroy();
7263 mOutputTracks.removeAt(i);
7264 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007265 if (thread->getOutput() == mOutput) {
7266 mOutput = NULL;
7267 }
Eric Laurent81784c32012-11-19 14:55:58 -08007268 return;
7269 }
7270 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007271 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007272}
7273
7274// caller must hold mLock
7275void AudioFlinger::DuplicatingThread::updateWaitTime_l()
7276{
7277 mWaitTimeMs = UINT_MAX;
7278 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7279 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
7280 if (strong != 0) {
7281 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7282 if (waitTimeMs < mWaitTimeMs) {
7283 mWaitTimeMs = waitTimeMs;
7284 }
7285 }
7286 }
7287}
7288
7289
7290bool AudioFlinger::DuplicatingThread::outputsReady(
7291 const SortedVector< sp<OutputTrack> > &outputTracks)
7292{
7293 for (size_t i = 0; i < outputTracks.size(); i++) {
7294 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
7295 if (thread == 0) {
7296 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7297 outputTracks[i].get());
7298 return false;
7299 }
7300 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
7301 // see note at standby() declaration
7302 if (playbackThread->standby() && !playbackThread->isSuspended()) {
7303 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7304 thread.get());
7305 return false;
7306 }
7307 }
7308 return true;
7309}
7310
Kevin Rocard12381092018-04-11 09:19:59 -07007311void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
7312 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007313{
Kevin Rocard12381092018-04-11 09:19:59 -07007314 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7315 outputTrack->setMetadatas(metadata.tracks);
7316 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007317}
7318
Eric Laurent81784c32012-11-19 14:55:58 -08007319uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
7320{
7321 return (mWaitTimeMs * 1000) / 2;
7322}
7323
7324void AudioFlinger::DuplicatingThread::cacheParameters_l()
7325{
7326 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7327 updateWaitTime_l();
7328
7329 MixerThread::cacheParameters_l();
7330}
7331
Eric Laurentb3f315a2021-07-13 15:09:05 +02007332// ----------------------------------------------------------------------------
7333
Eric Laurentfa0f6742021-08-17 18:39:44 +02007334AudioFlinger::SpatializerThread::SpatializerThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007335 AudioStreamOut* output,
7336 audio_io_handle_t id,
7337 bool systemReady,
7338 audio_config_base_t *mixerConfig)
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007339 : MixerThread(audioFlinger, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007340{
7341}
7342
Eric Laurent6f9534f2022-05-03 18:15:04 +02007343void AudioFlinger::SpatializerThread::onFirstRef() {
7344 PlaybackThread::onFirstRef();
7345
7346 Mutex::Autolock _l(mLock);
7347 status_t status = mOutput->stream->setLatencyModeCallback(this);
7348 if (status != INVALID_OPERATION) {
7349 updateHalSupportedLatencyModes_l();
7350 }
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007351
Andy Hung41ccf7f2022-12-14 14:25:49 -08007352 const pid_t tid = getTid();
7353 if (tid == -1) {
7354 // Unusual: PlaybackThread::onFirstRef() should set the threadLoop running.
7355 ALOGW("%s: Cannot update Spatializer mixer thread priority, not running", __func__);
7356 } else {
7357 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
7358 if (priorityBoost > 0) {
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007359 stream()->setHalThreadPriority(priorityBoost);
7360 }
7361 }
Eric Laurent6f9534f2022-05-03 18:15:04 +02007362}
7363
7364status_t AudioFlinger::SpatializerThread::createAudioPatch_l(const struct audio_patch *patch,
7365 audio_patch_handle_t *handle)
7366{
7367 status_t status = MixerThread::createAudioPatch_l(patch, handle);
7368 updateHalSupportedLatencyModes_l();
7369 return status;
7370}
7371
7372void AudioFlinger::SpatializerThread::updateHalSupportedLatencyModes_l() {
7373 std::vector<audio_latency_mode_t> latencyModes;
Andy Hung4bd53e72022-11-17 17:21:45 -08007374 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
7375 if (status != NO_ERROR) {
Eric Laurent6f9534f2022-05-03 18:15:04 +02007376 latencyModes.clear();
7377 }
7378 if (latencyModes != mSupportedLatencyModes) {
Andy Hung4bd53e72022-11-17 17:21:45 -08007379 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
7380 __func__, mId, status, toString(latencyModes).c_str());
Eric Laurent6f9534f2022-05-03 18:15:04 +02007381 mSupportedLatencyModes.swap(latencyModes);
7382 sendHalLatencyModesChangedEvent_l();
7383 }
7384}
7385
7386void AudioFlinger::SpatializerThread::onHalLatencyModesChanged_l() {
7387 mAudioFlinger->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
7388}
7389
7390void AudioFlinger::SpatializerThread::setHalLatencyMode_l() {
7391 // if mSupportedLatencyModes is empty, the HAL stream does not support
7392 // latency mode control and we can exit.
7393 if (mSupportedLatencyModes.empty()) {
7394 return;
7395 }
7396 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7397 if (mSupportedLatencyModes.size() == 1) {
7398 // If the HAL only support one latency mode currently, confirm the choice
7399 latencyMode = mSupportedLatencyModes[0];
7400 } else if (mSupportedLatencyModes.size() > 1) {
7401 // Request low latency if:
7402 // - The low latency mode is requested by the spatializer controller
7403 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7404 // AND
7405 // - At least one active track is spatialized
7406 bool hasSpatializedActiveTrack = false;
7407 for (const auto& track : mActiveTracks) {
7408 if (track->isSpatialized()) {
7409 hasSpatializedActiveTrack = true;
7410 break;
7411 }
7412 }
7413 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7414 latencyMode = AUDIO_LATENCY_MODE_LOW;
7415 }
7416 }
7417
7418 if (latencyMode != mSetLatencyMode) {
7419 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007420 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7421 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent6f9534f2022-05-03 18:15:04 +02007422 if (status == NO_ERROR) {
7423 mSetLatencyMode = latencyMode;
7424 }
7425 }
7426}
7427
7428status_t AudioFlinger::SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
7429 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7430 return BAD_VALUE;
7431 }
7432 Mutex::Autolock _l(mLock);
7433 mRequestedLatencyMode = mode;
7434 return NO_ERROR;
7435}
7436
7437status_t AudioFlinger::SpatializerThread::getSupportedLatencyModes(
7438 std::vector<audio_latency_mode_t>* modes) {
7439 if (modes == nullptr) {
7440 return BAD_VALUE;
7441 }
7442 Mutex::Autolock _l(mLock);
7443 *modes = mSupportedLatencyModes;
7444 return NO_ERROR;
7445}
7446
Eric Laurent49879b72022-12-20 20:20:23 +01007447status_t AudioFlinger::PlaybackThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurent01eb1642022-12-16 11:45:07 +01007448 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
Eric Laurent49879b72022-12-20 20:20:23 +01007449 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
Eric Laurent01eb1642022-12-16 11:45:07 +01007450 return INVALID_OPERATION;
7451 }
7452 mBluetoothLatencyModesEnabled.store(enabled);
7453 return NO_ERROR;
7454}
7455
Eric Laurentfa0f6742021-08-17 18:39:44 +02007456void AudioFlinger::SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007457{
7458 bool hasVirtualizer = false;
7459 bool hasDownMixer = false;
7460 sp<EffectHandle> finalDownMixer;
7461 {
7462 Mutex::Autolock _l(mLock);
7463 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
7464 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007465 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007466 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7467 }
7468
7469 finalDownMixer = mFinalDownMixer;
7470 mFinalDownMixer.clear();
7471 }
7472
7473 if (hasVirtualizer) {
7474 if (finalDownMixer != nullptr) {
7475 int32_t ret;
7476 finalDownMixer->disable(&ret);
7477 }
7478 finalDownMixer.clear();
7479 } else if (!hasDownMixer) {
7480 std::vector<effect_descriptor_t> descriptors;
7481 status_t status = mAudioFlinger->mEffectsFactoryHal->getDescriptors(
7482 EFFECT_UIID_DOWNMIX, &descriptors);
7483 if (status != NO_ERROR) {
7484 return;
7485 }
7486 ALOG_ASSERT(!descriptors.empty(),
7487 "%s getDescriptors() returned no error but empty list", __func__);
7488
7489 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7490 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007491 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007492
7493 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7494 ALOGW("%s error creating downmixer %d", __func__, status);
7495 finalDownMixer.clear();
7496 } else {
7497 int32_t ret;
7498 finalDownMixer->enable(&ret);
7499 }
7500 }
7501
7502 {
7503 Mutex::Autolock _l(mLock);
7504 mFinalDownMixer = finalDownMixer;
7505 }
7506}
7507
Eric Laurent6f9534f2022-05-03 18:15:04 +02007508void AudioFlinger::SpatializerThread::onRecommendedLatencyModeChanged(
7509 std::vector<audio_latency_mode_t> modes) {
7510 Mutex::Autolock _l(mLock);
7511 if (modes != mSupportedLatencyModes) {
Andy Hungb5ecdb82022-11-18 19:40:00 -08007512 ALOGD("%s: thread(%d) supported latency modes: %s",
7513 __func__, mId, toString(modes).c_str());
Eric Laurent6f9534f2022-05-03 18:15:04 +02007514 mSupportedLatencyModes.swap(modes);
7515 sendHalLatencyModesChangedEvent_l();
7516 }
7517}
Eric Laurent6acd1d42017-01-04 14:23:29 -08007518
Eric Laurent81784c32012-11-19 14:55:58 -08007519// ----------------------------------------------------------------------------
7520// Record
7521// ----------------------------------------------------------------------------
7522
7523AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
7524 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007525 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007526 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007527 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07007528 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007529 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007530 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007531 mActiveTracks(&this->mLocalLog),
7532 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007533 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007534 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007535 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7536 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007537 // mFastCapture below
7538 , mFastCaptureFutex(0)
7539 // mInputSource
7540 // mPipeSink
7541 // mPipeSource
7542 , mPipeFramesP2(0)
7543 // mPipeMemory
7544 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007545 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007546 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007547{
Glenn Kastend7dca052015-03-05 16:05:54 -08007548 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7549 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007550
George Burgess IVa8f90c12020-05-14 11:27:19 -07007551 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007552 mIsMsdDevice = strcmp(
7553 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7554 }
7555
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007556 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007557
Andy Hungc8fddf32018-08-08 18:32:37 -07007558 // TODO: We may also match on address as well as device type for
7559 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007560 // TODO: This property should be ensure that only contains one single device type.
7561 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7562 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007563 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7564 : AUDIO_DEVICE_NONE));
7565
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007566 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007567 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007568 size_t numCounterOffers = 0;
7569 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007570#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007571 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007572#else
7573 (void)
7574#endif
7575 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007576 ALOG_ASSERT(index == 0);
7577
7578 // initialize fast capture depending on configuration
7579 bool initFastCapture;
7580 switch (kUseFastCapture) {
7581 case FastCapture_Never:
7582 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007583 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007584 break;
7585 case FastCapture_Always:
7586 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007587 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007588 break;
7589 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007590 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
7591 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7592 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d "
7593 "mIsMsdDevice = %d", this, (long long)mFrameCount, mSampleRate,
7594 kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007595 break;
7596 // case FastCapture_Dynamic:
7597 }
7598
7599 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007600 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007601 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007602 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7603 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007604 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007605 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007606 const sp<MemoryDealer> roHeap(readOnlyHeap());
7607 sp<IMemory> pipeMemory;
7608 if ((roHeap == 0) ||
7609 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007610 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007611 ALOGE("not enough memory for pipe buffer size=%zu; "
7612 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7613 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7614 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007615 goto failed;
7616 }
7617 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7618 memset(pipeBuffer, 0, pipeSize);
7619 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7620 const NBAIO_Format offers[1] = {format};
7621 size_t numCounterOffers = 0;
Jing Mike537412f2023-03-12 11:01:47 +08007622 [[maybe_unused]] ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007623 ALOG_ASSERT(index == 0);
7624 mPipeSink = pipe;
7625 PipeReader *pipeReader = new PipeReader(*pipe);
7626 numCounterOffers = 0;
7627 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7628 ALOG_ASSERT(index == 0);
7629 mPipeSource = pipeReader;
7630 mPipeFramesP2 = pipeFramesP2;
7631 mPipeMemory = pipeMemory;
7632
7633 // create fast capture
7634 mFastCapture = new FastCapture();
7635 FastCaptureStateQueue *sq = mFastCapture->sq();
7636#ifdef STATE_QUEUE_DUMP
7637 // FIXME
7638#endif
7639 FastCaptureState *state = sq->begin();
7640 state->mCblk = NULL;
7641 state->mInputSource = mInputSource.get();
7642 state->mInputSourceGen++;
7643 state->mPipeSink = pipe;
7644 state->mPipeSinkGen++;
7645 state->mFrameCount = mFrameCount;
7646 state->mCommand = FastCaptureState::COLD_IDLE;
7647 // already done in constructor initialization list
7648 //mFastCaptureFutex = 0;
7649 state->mColdFutexAddr = &mFastCaptureFutex;
7650 state->mColdGen++;
7651 state->mDumpState = &mFastCaptureDumpState;
7652#ifdef TEE_SINK
7653 // FIXME
7654#endif
7655 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7656 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7657 sq->end();
7658 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7659
7660 // start the fast capture
7661 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7662 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007663 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007664 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007665#ifdef AUDIO_WATCHDOG
7666 // FIXME
7667#endif
7668
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007669 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007670 }
Andy Hung8946a282018-04-19 20:04:56 -07007671#ifdef TEE_SINK
7672 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7673 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7674#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007675failed: ;
7676
7677 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007678}
7679
Eric Laurent81784c32012-11-19 14:55:58 -08007680AudioFlinger::RecordThread::~RecordThread()
7681{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007682 if (mFastCapture != 0) {
7683 FastCaptureStateQueue *sq = mFastCapture->sq();
7684 FastCaptureState *state = sq->begin();
7685 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7686 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7687 if (old == -1) {
7688 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7689 }
7690 }
7691 state->mCommand = FastCaptureState::EXIT;
7692 sq->end();
7693 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7694 mFastCapture->join();
7695 mFastCapture.clear();
7696 }
7697 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007698 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007699 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007700}
7701
7702void AudioFlinger::RecordThread::onFirstRef()
7703{
Glenn Kastend7dca052015-03-05 16:05:54 -08007704 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007705}
7706
Eric Laurent555530a2017-02-07 18:17:24 -08007707void AudioFlinger::RecordThread::preExit()
7708{
7709 ALOGV(" preExit()");
7710 Mutex::Autolock _l(mLock);
7711 for (size_t i = 0; i < mTracks.size(); i++) {
7712 sp<RecordTrack> track = mTracks[i];
7713 track->invalidate();
7714 }
7715 mActiveTracks.clear();
7716 mStartStopCond.broadcast();
7717}
7718
Eric Laurent81784c32012-11-19 14:55:58 -08007719bool AudioFlinger::RecordThread::threadLoop()
7720{
Eric Laurent81784c32012-11-19 14:55:58 -08007721 nsecs_t lastWarning = 0;
7722
7723 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007724
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007725reacquire_wakelock:
7726 sp<RecordTrack> activeTrack;
7727 {
7728 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007729 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007730 }
7731
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007732 // used to request a deferred sleep, to be executed later while mutex is unlocked
7733 uint32_t sleepUs = 0;
7734
Andy Hung446f4df2019-02-21 12:26:41 -08007735 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7736
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007737 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007738 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007739 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007740
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007741 // activeTracks accumulates a copy of a subset of mActiveTracks
7742 Vector< sp<RecordTrack> > activeTracks;
7743
Glenn Kasten735f45f2014-08-18 15:51:59 -07007744 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007745 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007746
Glenn Kasten735f45f2014-08-18 15:51:59 -07007747 // reference to a fast track which is about to be removed
7748 sp<RecordTrack> fastTrackToRemove;
7749
Eric Laurent33403f02020-05-29 18:35:06 -07007750 bool silenceFastCapture = false;
7751
Eric Laurent81784c32012-11-19 14:55:58 -08007752 { // scope for mLock
7753 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007754
Eric Laurent021cf962014-05-13 10:18:14 -07007755 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007756
Eric Laurent000a4192014-01-29 15:17:32 -08007757 // check exitPending here because checkForNewParameters_l() and
7758 // checkForNewParameters_l() can temporarily release mLock
7759 if (exitPending()) {
7760 break;
7761 }
7762
Eric Laurent5c25d562016-07-13 17:17:45 -07007763 // sleep with mutex unlocked
7764 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007765 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007766 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7767 ATRACE_END();
7768 sleepUs = 0;
7769 continue;
7770 }
7771
Glenn Kasten2b806402013-11-20 16:37:38 -08007772 // if no active track(s), then standby and release wakelock
7773 size_t size = mActiveTracks.size();
7774 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007775 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007776 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007777 releaseWakeLock_l();
7778 ALOGV("RecordThread: loop stopping");
7779 // go to sleep
7780 mWaitWorkCV.wait(mLock);
7781 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007782 goto reacquire_wakelock;
7783 }
7784
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007785 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007786 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007787 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007788
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007789 activeTrack = mActiveTracks[i];
7790 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007791 if (activeTrack->isFastTrack()) {
7792 ALOG_ASSERT(fastTrackToRemove == 0);
7793 fastTrackToRemove = activeTrack;
7794 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007795 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007796 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007797 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007798 continue;
7799 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007800
7801 TrackBase::track_state activeTrackState = activeTrack->mState;
7802 switch (activeTrackState) {
7803
7804 case TrackBase::PAUSING:
7805 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007806 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007807 doBroadcast = true;
7808 size--;
7809 continue;
7810
7811 case TrackBase::STARTING_1:
7812 sleepUs = 10000;
7813 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007814 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007815 continue;
7816
7817 case TrackBase::STARTING_2:
7818 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007819 if (mStandby) {
7820 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007821 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007822 mStandby = false;
7823 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007824 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007825 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007826 break;
7827
7828 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007829 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007830 break;
7831
Andy Hungce685402018-10-05 17:23:27 -07007832 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7833 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7834 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007835 default:
Andy Hungce685402018-10-05 17:23:27 -07007836 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7837 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007838 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007839
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007840 if (activeTrack->isFastTrack()) {
7841 ALOG_ASSERT(!mFastTrackAvail);
7842 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007843 // if the active fast track is silenced either:
7844 // 1) silence the whole capture from fast capture buffer if this is
7845 // the only active track
7846 // 2) invalidate this track: this will cause the client to reconnect and possibly
7847 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007848 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07007849 if (activeTrack->isSilenced()) {
7850 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007851 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07007852 } else {
7853 silenceFastCapture = true;
7854 }
7855 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007856 // Invalidate fast tracks if access to audio history is required as this is not
7857 // possible with fast tracks. Once the fast track has been invalidated, no new
7858 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
7859 if (mMaxSharedAudioHistoryMs != 0) {
7860 invalidate = true;
7861 }
7862 if (invalidate) {
7863 activeTrack->invalidate();
7864 ALOG_ASSERT(fastTrackToRemove == 0);
7865 fastTrackToRemove = activeTrack;
7866 removeTrack_l(activeTrack);
7867 mActiveTracks.remove(activeTrack);
7868 size--;
7869 continue;
7870 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007871 fastTrack = activeTrack;
7872 }
Eric Laurent33403f02020-05-29 18:35:06 -07007873
7874 activeTracks.add(activeTrack);
7875 i++;
7876
Glenn Kasten9e982352013-08-14 14:39:50 -07007877 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007878
Andy Hungdae27702016-10-31 14:01:16 -07007879 mActiveTracks.updatePowerState(this);
7880
Kevin Rocard069c2712018-03-29 19:09:14 -07007881 updateMetadata_l();
7882
Eric Laurent5c25d562016-07-13 17:17:45 -07007883 if (allStopped) {
7884 standbyIfNotAlreadyInStandby();
7885 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007886 if (doBroadcast) {
7887 mStartStopCond.broadcast();
7888 }
7889
7890 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007891 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007892 if (sleepUs == 0) {
7893 sleepUs = kRecordThreadSleepUs;
7894 }
7895 continue;
7896 }
7897 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007898
Eric Laurent81784c32012-11-19 14:55:58 -08007899 lockEffectChains_l(effectChains);
7900 }
7901
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007902 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007903
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007904 size_t size = effectChains.size();
7905 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007906 // thread mutex is not locked, but effect chain is locked
7907 effectChains[i]->process_l();
7908 }
7909
Glenn Kasten735f45f2014-08-18 15:51:59 -07007910 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007911 if (mFastCapture != 0) {
7912 FastCaptureStateQueue *sq = mFastCapture->sq();
7913 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007914 bool didModify = false;
7915 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007916 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7917 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7918 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7919 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7920 if (old == -1) {
7921 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7922 }
7923 }
7924 state->mCommand = FastCaptureState::READ_WRITE;
7925#if 0 // FIXME
7926 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007927 FastThreadDumpState::kSamplingNforLowRamDevice :
7928 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007929#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007930 didModify = true;
7931 }
7932 audio_track_cblk_t *cblkOld = state->mCblk;
7933 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7934 if (cblkNew != cblkOld) {
7935 state->mCblk = cblkNew;
7936 // block until acked if removing a fast track
7937 if (cblkOld != NULL) {
7938 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7939 }
7940 didModify = true;
7941 }
jiabin01c8f562018-07-19 17:47:28 -07007942 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7943 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7944 if (state->mFastPatchRecordBufferProvider != abp) {
7945 state->mFastPatchRecordBufferProvider = abp;
7946 state->mFastPatchRecordFormat = fastTrack == 0 ?
7947 AUDIO_FORMAT_INVALID : fastTrack->format();
7948 didModify = true;
7949 }
Eric Laurent33403f02020-05-29 18:35:06 -07007950 if (state->mSilenceCapture != silenceFastCapture) {
7951 state->mSilenceCapture = silenceFastCapture;
7952 didModify = true;
7953 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007954 sq->end(didModify);
7955 if (didModify) {
7956 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007957#if 0
7958 if (kUseFastCapture == FastCapture_Dynamic) {
7959 mNormalSource = mPipeSource;
7960 }
7961#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007962 }
7963 }
7964
Glenn Kasten735f45f2014-08-18 15:51:59 -07007965 // now run the fast track destructor with thread mutex unlocked
7966 fastTrackToRemove.clear();
7967
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007968 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7969 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7970 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7971 // If destination is non-contiguous, first read past the nominal end of buffer, then
7972 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007973
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007974 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007975 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007976 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007977
7978 // If an NBAIO source is present, use it to read the normal capture's data
7979 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007980 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007981
7982 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7983 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7984 // we immediately retry the read() to get data and prevent another overflow.
7985 for (int retries = 0; retries <= 2; ++retries) {
7986 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7987 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7988 framesToRead);
7989 if (framesRead != OVERRUN) break;
7990 }
7991
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007992 const ssize_t availableToRead = mPipeSource->availableToRead();
7993 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00007994 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07007995 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007996 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7997 "more frames to read than fifo size, %zd > %zu",
7998 availableToRead, mPipeFramesP2);
7999 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8000 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8001 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8002 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008003 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8004 }
8005 if (framesRead < 0) {
8006 status_t status = (status_t) framesRead;
8007 switch (status) {
8008 case OVERRUN:
8009 ALOGW("overrun on read from pipe");
8010 framesRead = 0;
8011 break;
8012 case NEGOTIATE:
8013 ALOGE("re-negotiation is needed");
8014 framesRead = -1; // Will cause an attempt to recover.
8015 break;
8016 default:
8017 ALOGE("unknown error %d on read from pipe", status);
8018 break;
8019 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008020 }
8021 // otherwise use the HAL / AudioStreamIn directly
8022 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008023 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008024 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008025 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008026 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008027 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008028 if (result < 0) {
8029 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008030 } else {
8031 framesRead = bytesRead / mFrameSize;
8032 }
8033 }
8034
Andy Hung446f4df2019-02-21 12:26:41 -08008035 const int64_t lastIoEndNs = systemTime(); // end IO timing
8036
Andy Hung3f0c9022016-01-15 17:49:46 -08008037 // Update server timestamp with server stats
8038 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008039 if (framesRead >= 0) {
8040 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8041 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8042 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008043
8044 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008045 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008046 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008047 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008048 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8049 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8050 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008051 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008052 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8053
8054 mTimestampVerifier.add(position, time, mSampleRate);
8055
8056 // Correct timestamps
8057 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008058 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008059 id(), (long long)time, (long long)position);
8060 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8061 position = correctedTimestamp.mFrames;
8062 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008063 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008064 id(), (long long)time, (long long)position);
8065 }
8066
Andy Hung3f0c9022016-01-15 17:49:46 -08008067 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8068 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8069 // Note: In general record buffers should tend to be empty in
8070 // a properly running pipeline.
8071 //
8072 // Also, it is not advantageous to call get_presentation_position during the read
8073 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008074 } else {
8075 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008076 }
8077 }
Andy Hunge6c37112019-02-26 17:38:10 -08008078
8079 // From the timestamp, input read latency is negative output write latency.
8080 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
8081 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
8082 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8083 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8084 mLatencyMs.add(latencyMs);
8085 }
8086
Andy Hung3f0c9022016-01-15 17:49:46 -08008087 // Use this to track timestamp information
8088 // ALOGD("%s", mTimestamp.toString().c_str());
8089
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008090 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008091 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008092 // Force input into standby so that it tries to recover at next read attempt
8093 inputStandBy();
8094 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008095 }
8096 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008097 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008098 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008099 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008100 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008101
Andy Hung8946a282018-04-19 20:04:56 -07008102#ifdef TEE_SINK
8103 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8104#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008105 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008106 {
8107 size_t part1 = mRsmpInFramesP2 - rear;
8108 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008109 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008110 (framesRead - part1) * mFrameSize);
8111 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008112 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008113 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008114
8115 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008116
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008117 // loop over each active track
8118 for (size_t i = 0; i < size; i++) {
8119 activeTrack = activeTracks[i];
8120
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008121 // skip fast tracks, as those are handled directly by FastCapture
8122 if (activeTrack->isFastTrack()) {
8123 continue;
8124 }
8125
Andy Hung73c02e42015-03-29 01:13:58 -07008126 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008127 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8128
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008129 enum {
8130 OVERRUN_UNKNOWN,
8131 OVERRUN_TRUE,
8132 OVERRUN_FALSE
8133 } overrun = OVERRUN_UNKNOWN;
8134
8135 // loop over getNextBuffer to handle circular sink
8136 for (;;) {
8137
8138 activeTrack->mSink.frameCount = ~0;
8139 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
8140 size_t framesOut = activeTrack->mSink.frameCount;
8141 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8142
Andy Hung73c02e42015-03-29 01:13:58 -07008143 // check available frames and handle overrun conditions
8144 // if the record track isn't draining fast enough.
8145 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008146 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07008147 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
8148 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008149 overrun = OVERRUN_TRUE;
8150 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008151 if (framesOut == 0 || framesIn == 0) {
8152 break;
8153 }
8154
Andy Hung6770c6f2015-04-07 13:43:36 -07008155 // Don't allow framesOut to be larger than what is possible with resampling
8156 // from framesIn.
8157 // This isn't strictly necessary but helps limit buffer resizing in
8158 // RecordBufferConverter. TODO: remove when no longer needed.
8159 framesOut = min(framesOut,
8160 destinationFramesPossible(
8161 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008162
8163 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008164 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008165 // straight from RecordThread buffer to RecordTrack buffer.
8166 AudioBufferProvider::Buffer buffer;
8167 buffer.frameCount = framesOut;
8168 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
8169 if (status == OK && buffer.frameCount != 0) {
8170 ALOGV_IF(buffer.frameCount != framesOut,
8171 "%s() read less than expected (%zu vs %zu)",
8172 __func__, buffer.frameCount, framesOut);
8173 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008174 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008175 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
8176 } else {
8177 framesOut = 0;
8178 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
8179 __func__, status, buffer.frameCount);
8180 }
8181 } else {
8182 // process frames from the RecordThread buffer provider to the RecordTrack
8183 // buffer
8184 framesOut = activeTrack->mRecordBufferConverter->convert(
8185 activeTrack->mSink.raw,
8186 activeTrack->mResamplerBufferProvider,
8187 framesOut);
8188 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008189
8190 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8191 overrun = OVERRUN_FALSE;
8192 }
8193
8194 if (activeTrack->mFramesToDrop == 0) {
8195 if (framesOut > 0) {
8196 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008197 // Sanitize before releasing if the track has no access to the source data
8198 // An idle UID receives silence from non virtual devices until active
8199 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07008200 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008201 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008202 activeTrack->releaseBuffer(&activeTrack->mSink);
8203 }
8204 } else {
8205 // FIXME could do a partial drop of framesOut
8206 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07008207 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008208 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008209 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008210 }
8211 } else {
8212 activeTrack->mFramesToDrop += framesOut;
8213 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
8214 activeTrack->mSyncStartEvent->isCancelled()) {
8215 ALOGW("Synced record %s, session %d, trigger session %d",
8216 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
8217 activeTrack->sessionId(),
8218 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08008219 activeTrack->mSyncStartEvent->triggerSession() :
8220 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008221 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008222 }
8223 }
8224 }
8225
8226 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008227 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008228 }
8229 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008230
8231 switch (overrun) {
8232 case OVERRUN_TRUE:
8233 // client isn't retrieving buffers fast enough
8234 if (!activeTrack->setOverflow()) {
8235 nsecs_t now = systemTime();
8236 // FIXME should lastWarning per track?
8237 if ((now - lastWarning) > kWarningThrottleNs) {
8238 ALOGW("RecordThread: buffer overflow");
8239 lastWarning = now;
8240 }
8241 }
8242 break;
8243 case OVERRUN_FALSE:
8244 activeTrack->clearOverflow();
8245 break;
8246 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008247 break;
8248 }
8249
Andy Hung3f0c9022016-01-15 17:49:46 -08008250 // update frame information and push timestamp out
8251 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08008252 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008253 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8254 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008255 }
8256
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008257unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008258 // enable changes in effect chain
8259 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008260 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008261 if (audio_has_proportional_frames(mFormat)
8262 && loopCount == lastLoopCountRead + 1) {
8263 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8264 const double jitterMs =
8265 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8266 {framesRead, readPeriodNs},
8267 {0, 0} /* lastTimestamp */, mSampleRate);
8268 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8269
8270 Mutex::Autolock _l(mLock);
8271 mIoJitterMs.add(jitterMs);
8272 mProcessTimeMs.add(processMs);
8273 }
8274 // update timing info.
8275 mLastIoBeginNs = lastIoBeginNs;
8276 mLastIoEndNs = lastIoEndNs;
8277 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008278 }
8279
Glenn Kasten93e471f2013-08-19 08:40:07 -07008280 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008281
8282 {
8283 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008284 for (size_t i = 0; i < mTracks.size(); i++) {
8285 sp<RecordTrack> track = mTracks[i];
8286 track->invalidate();
8287 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008288 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008289 mStartStopCond.broadcast();
8290 }
8291
8292 releaseWakeLock();
8293
8294 ALOGV("RecordThread %p exiting", this);
8295 return false;
8296}
8297
Glenn Kasten93e471f2013-08-19 08:40:07 -07008298void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008299{
8300 if (!mStandby) {
8301 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008302 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008303 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008304 mStandby = true;
8305 }
8306}
8307
8308void AudioFlinger::RecordThread::inputStandBy()
8309{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008310 // Idle the fast capture if it's currently running
8311 if (mFastCapture != 0) {
8312 FastCaptureStateQueue *sq = mFastCapture->sq();
8313 FastCaptureState *state = sq->begin();
8314 if (!(state->mCommand & FastCaptureState::IDLE)) {
8315 state->mCommand = FastCaptureState::COLD_IDLE;
8316 state->mColdFutexAddr = &mFastCaptureFutex;
8317 state->mColdGen++;
8318 mFastCaptureFutex = 0;
8319 sq->end();
8320 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8321 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8322#if 0
8323 if (kUseFastCapture == FastCapture_Dynamic) {
8324 // FIXME
8325 }
8326#endif
8327#ifdef AUDIO_WATCHDOG
8328 // FIXME
8329#endif
8330 } else {
8331 sq->end(false /*didModify*/);
8332 }
8333 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008334 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008335 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008336
8337 // If going into standby, flush the pipe source.
8338 if (mPipeSource.get() != nullptr) {
8339 const ssize_t flushed = mPipeSource->flush();
8340 if (flushed > 0) {
8341 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8342 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8343 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8344 }
8345 }
Eric Laurent81784c32012-11-19 14:55:58 -08008346}
8347
Glenn Kasten05997e22014-03-13 15:08:33 -07008348// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07008349sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08008350 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008351 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008352 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008353 audio_format_t format,
8354 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008355 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008356 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008357 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008358 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008359 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008360 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008361 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008362 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008363 audio_port_handle_t portId,
8364 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008365{
Glenn Kasten74935e42013-12-19 08:56:45 -08008366 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008367 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008368 sp<RecordTrack> track;
8369 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008370 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008371 audio_input_flags_t requestedFlags = *flags;
8372 uint32_t sampleRate;
8373
8374 lStatus = initCheck();
8375 if (lStatus != NO_ERROR) {
8376 ALOGE("createRecordTrack_l() audio driver not initialized");
8377 goto Exit;
8378 }
8379
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008380 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8381 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8382 lStatus = BAD_VALUE;
8383 goto Exit;
8384 }
8385
Eric Laurentec376dc2021-04-08 20:41:22 +02008386 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008387 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008388 lStatus = PERMISSION_DENIED;
8389 goto Exit;
8390 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008391 if (maxSharedAudioHistoryMs < 0
8392 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8393 lStatus = BAD_VALUE;
8394 goto Exit;
8395 }
8396 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008397 if (*pSampleRate == 0) {
8398 *pSampleRate = mSampleRate;
8399 }
8400 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008401
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008402 // special case for FAST flag considered OK if fast capture is present and access to
8403 // audio history is not required
8404 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008405 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8406 }
8407
Eric Laurentf14db3c2017-12-08 14:20:36 -08008408 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008409 if ((*flags & inputFlags) != *flags) {
8410 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8411 " input flags (%08x)",
8412 *flags, inputFlags);
8413 *flags = (audio_input_flags_t)(*flags & inputFlags);
8414 }
Eric Laurent81784c32012-11-19 14:55:58 -08008415
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008416 // client expresses a preference for FAST and no access to audio history,
8417 // but we get the final say
8418 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008419 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008420 // we formerly checked for a callback handler (non-0 tid),
8421 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008422 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008423 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008424 // Frame count is not specified (0), or is less than or equal the pipe depth.
8425 // It is OK to provide a higher capacity than requested.
8426 // We will force it to mPipeFramesP2 below.
8427 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008428 // PCM data
8429 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008430 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008431 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008432 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008433 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008434 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008435 hasFastCapture() &&
8436 // there are sufficient fast track slots available
8437 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008438 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008439 // check compatibility with audio effects.
8440 Mutex::Autolock _l(mLock);
8441 // Do not accept FAST flag if the session has software effects
8442 sp<EffectChain> chain = getEffectChain_l(sessionId);
8443 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008444 audio_input_flags_t old = *flags;
8445 chain->checkInputFlagCompatibility(flags);
8446 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008447 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8448 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008449 }
8450 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008451 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008452 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8453 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008454 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008455 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8456 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008457 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008458 this, frameCount, mFrameCount, mPipeFramesP2,
8459 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008460 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008461 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008462 }
8463 }
8464
Eric Laurentf14db3c2017-12-08 14:20:36 -08008465 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8466 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8467 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8468 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8469 lStatus = BAD_TYPE;
8470 goto Exit;
8471 }
8472
Glenn Kasten74105912014-07-03 12:28:53 -07008473 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008474 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008475 // fast track: frame count is exactly the pipe depth
8476 frameCount = mPipeFramesP2;
8477 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008478 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008479 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008480 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8481 // or 20 ms if there is a fast capture
8482 // TODO This could be a roundupRatio inline, and const
8483 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8484 * sampleRate + mSampleRate - 1) / mSampleRate;
8485 // minimum number of notification periods is at least kMinNotifications,
8486 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8487 static const size_t kMinNotifications = 3;
8488 static const uint32_t kMinMs = 30;
8489 // TODO This could be a roundupRatio inline
8490 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8491 // TODO This could be a roundupRatio inline
8492 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8493 maxNotificationFrames;
8494 const size_t minFrameCount = maxNotificationFrames *
8495 max(kMinNotifications, minNotificationsByMs);
8496 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008497 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8498 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008499 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008500 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008501 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008502 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008503
8504 { // scope for mLock
8505 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008506 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008507 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008508 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008509 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008510 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008511 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008512 }
Eric Laurent81784c32012-11-19 14:55:58 -08008513
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008514 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008515 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008516 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Eric Laurent9ff3e532022-11-10 16:04:44 +01008517 attributionSource, *flags, TrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008518 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008519
Glenn Kasten03003332013-08-06 15:40:54 -07008520 lStatus = track->initCheck();
8521 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008522 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008523 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008524 goto Exit;
8525 }
8526 mTracks.add(track);
8527
Eric Laurent05067782016-06-01 18:27:28 -07008528 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008529 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8530 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8531 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008532 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008533 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008534
8535 if (maxSharedAudioHistoryMs != 0) {
8536 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8537 }
Eric Laurent81784c32012-11-19 14:55:58 -08008538 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008539
Eric Laurent81784c32012-11-19 14:55:58 -08008540 lStatus = NO_ERROR;
8541
8542Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008543 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008544 return track;
8545}
8546
8547status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
8548 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008549 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008550{
8551 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8552 sp<ThreadBase> strongMe = this;
8553 status_t status = NO_ERROR;
8554
8555 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008556 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008557 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008558 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08008559 triggerSession,
8560 recordTrack->sessionId(),
8561 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008562 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08008563 // Sync event can be cancelled by the trigger session if the track is not in a
8564 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008565 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008566 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008567 } else {
8568 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08008569 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008570 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08008571 }
8572 }
8573
8574 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008575 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008576 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008577 if (recordTrack->isInvalid()) {
8578 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008579 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8580 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008581 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008582 if (mActiveTracks.indexOf(recordTrack) >= 0) {
8583 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008584 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8585 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008586 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008587 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008588 } else {
Andy Hung959b5b82021-09-24 10:46:20 -07008589 ALOGV("active record track state %d", (int)recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008590 }
8591 return status;
8592 }
8593
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008594 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8595 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8596 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008597 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08008598 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008599 status_t status = NO_ERROR;
8600 if (recordTrack->isExternalTrack()) {
8601 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008602 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008603 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008604 if (recordTrack->isInvalid()) {
8605 recordTrack->clearSyncStartEvent();
8606 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8607 recordTrack->mState = TrackBase::STARTING_2;
8608 // STARTING_2 forces destroy to call stopInput.
8609 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008610 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8611 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008612 }
8613 if (recordTrack->mState != TrackBase::STARTING_1) {
8614 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung959b5b82021-09-24 10:46:20 -07008615 __func__, recordTrack->id(), (int)recordTrack->mState);
Andy Hungce685402018-10-05 17:23:27 -07008616 // Someone else has changed state, let them take over,
8617 // leave mState in the new state.
8618 recordTrack->clearSyncStartEvent();
8619 return INVALID_OPERATION;
8620 }
8621 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008622 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008623 ALOGW("%s(%d): startInput failed, status %d",
8624 __func__, recordTrack->id(), status);
8625 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8626 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008627 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008628 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008629 return status;
8630 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008631 sendIoConfigEvent_l(
8632 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008633 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008634
8635 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8636
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008637 // Catch up with current buffer indices if thread is already running.
8638 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8639 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8640 // see previously buffered data before it called start(), but with greater risk of overrun.
8641
Andy Hung73c02e42015-03-29 01:13:58 -07008642 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008643 if (!recordTrack->isDirect()) {
8644 // clear any converter state as new data will be discontinuous
8645 recordTrack->mRecordBufferConverter->reset();
8646 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008647 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008648 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008649 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008650 return status;
8651 }
Eric Laurent81784c32012-11-19 14:55:58 -08008652}
8653
Eric Laurent81784c32012-11-19 14:55:58 -08008654void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8655{
8656 sp<SyncEvent> strongEvent = event.promote();
8657
8658 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008659 sp<RefBase> ptr = strongEvent->cookie().promote();
8660 if (ptr != 0) {
8661 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8662 recordTrack->handleSyncStartEvent(strongEvent);
8663 }
Eric Laurent81784c32012-11-19 14:55:58 -08008664 }
8665}
8666
Glenn Kastena8356f62013-07-25 14:37:52 -07008667bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008668 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008669 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008670 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008671 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008672 return false;
8673 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008674 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008675 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008676
Andy Hungabfab202019-03-07 19:45:54 -08008677 // NOTE: Waiting here is important to keep stop synchronous.
8678 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008679 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8680 mWaitWorkCV.broadcast(); // signal thread to stop
8681 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008682 }
Andy Hungce685402018-10-05 17:23:27 -07008683
8684 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008685 ALOGV("Record stopped OK");
8686 return true;
8687 }
Andy Hungce685402018-10-05 17:23:27 -07008688
8689 // don't handle anything - we've been invalidated or restarted and in a different state
8690 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8691 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008692 return false;
8693}
8694
Glenn Kasten0f11b512014-01-31 16:18:54 -08008695bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008696{
8697 return false;
8698}
8699
Glenn Kasten0f11b512014-01-31 16:18:54 -08008700status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008701{
8702#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8703 if (!isValidSyncEvent(event)) {
8704 return BAD_VALUE;
8705 }
8706
Glenn Kastend848eb42016-03-08 13:42:11 -08008707 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008708 status_t ret = NAME_NOT_FOUND;
8709
8710 Mutex::Autolock _l(mLock);
8711
8712 for (size_t i = 0; i < mTracks.size(); i++) {
8713 sp<RecordTrack> track = mTracks[i];
8714 if (eventSession == track->sessionId()) {
8715 (void) track->setSyncEvent(event);
8716 ret = NO_ERROR;
8717 }
8718 }
8719 return ret;
8720#else
8721 return BAD_VALUE;
8722#endif
8723}
8724
jiabin653cc0a2018-01-17 17:54:10 -08008725status_t AudioFlinger::RecordThread::getActiveMicrophones(
Mikhail Naganov2a6a3012023-02-13 11:45:03 -08008726 std::vector<media::MicrophoneInfoFw>* activeMicrophones)
jiabin653cc0a2018-01-17 17:54:10 -08008727{
8728 ALOGV("RecordThread::getActiveMicrophones");
8729 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008730 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008731 return NO_INIT;
8732 }
jiabin9ff780e2018-03-19 18:19:52 -07008733 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8734 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008735}
8736
Paul McLean12340082019-03-19 09:35:05 -06008737status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8738 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008739{
Paul McLean12340082019-03-19 09:35:05 -06008740 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008741 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008742 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008743 return NO_INIT;
8744 }
Paul McLean12340082019-03-19 09:35:05 -06008745 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008746}
8747
Paul McLean12340082019-03-19 09:35:05 -06008748status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008749{
Paul McLean12340082019-03-19 09:35:05 -06008750 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008751 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008752 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008753 return NO_INIT;
8754 }
Paul McLean12340082019-03-19 09:35:05 -06008755 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008756}
8757
Eric Laurentec376dc2021-04-08 20:41:22 +02008758status_t AudioFlinger::RecordThread::shareAudioHistory(
8759 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8760 int64_t sharedAudioStartMs) {
8761 AutoMutex _l(mLock);
8762 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8763}
8764
8765status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8766 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8767 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008768
Eric Laurentec376dc2021-04-08 20:41:22 +02008769 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8770 return BAD_VALUE;
8771 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008772
8773 if (sharedAudioStartMs < 0
8774 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008775 return BAD_VALUE;
8776 }
8777
Eric Laurent2407ce32021-04-26 14:56:03 +02008778 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8779 // As we cannot detect more than one wraparound, only accept values up current write position
8780 // after one wraparound
8781 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8782 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02008783 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02008784 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8785 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02008786 // Bring the start frame position within the input buffer to match the documented
8787 // "best effort" behavior of the API.
8788 if (sharedOffset < 0) {
8789 sharedAudioStartFrames = mRsmpInRear;
8790 } else if (sharedOffset > mRsmpInFrames) {
8791 sharedAudioStartFrames =
8792 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02008793 }
8794
Eric Laurentec376dc2021-04-08 20:41:22 +02008795 mSharedAudioPackageName = sharedAudioPackageName;
8796 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008797 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02008798 } else {
8799 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02008800 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008801 }
8802 return NO_ERROR;
8803}
8804
Eric Laurent92d0a322021-07-16 15:32:33 +02008805void AudioFlinger::RecordThread::resetAudioHistory_l() {
8806 mSharedAudioSessionId = AUDIO_SESSION_NONE;
8807 mSharedAudioStartFrames = -1;
8808 mSharedAudioPackageName = "";
8809}
8810
Kevin Rocard069c2712018-03-29 19:09:14 -07008811void AudioFlinger::RecordThread::updateMetadata_l()
8812{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008813 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
8814 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07008815 }
8816 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02008817 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07008818 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02008819 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07008820 }
8821 mInput->stream->updateSinkMetadata(metadata);
8822}
8823
Eric Laurent81784c32012-11-19 14:55:58 -08008824// destroyTrack_l() must be called with ThreadBase::mLock held
8825void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8826{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008827 track->terminate();
8828 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008829
Eric Laurent81784c32012-11-19 14:55:58 -08008830 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008831 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008832 removeTrack_l(track);
8833 }
8834}
8835
8836void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8837{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008838 String8 result;
8839 track->appendDump(result, false /* active */);
8840 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8841
Eric Laurent81784c32012-11-19 14:55:58 -08008842 mTracks.remove(track);
8843 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008844 if (track->isFastTrack()) {
8845 ALOG_ASSERT(!mFastTrackAvail);
8846 mFastTrackAvail = true;
8847 }
Eric Laurent81784c32012-11-19 14:55:58 -08008848}
8849
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008850void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008851{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008852 AudioStreamIn *input = mInput;
8853 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8854 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008855 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008856 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008857 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008858 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008859 }
Andy Hungbfa64962017-06-12 14:43:19 -07008860
8861 if (input != nullptr) {
8862 dprintf(fd, " Hal stream dump:\n");
8863 (void)input->stream->dump(fd);
8864 }
8865
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008866 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008867 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008868
Glenn Kasten2f90c512015-12-02 11:40:09 -08008869 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8870 // while we are dumping it. It may be inconsistent, but it won't mutate!
8871 // This is a large object so we place it on the heap.
8872 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008873 const std::unique_ptr<FastCaptureDumpState> copy =
8874 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008875 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008876}
8877
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008878void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008879{
Eric Laurent81784c32012-11-19 14:55:58 -08008880 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008881 size_t numtracks = mTracks.size();
8882 size_t numactive = mActiveTracks.size();
8883 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008884 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008885 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008886 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008887 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008888 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008889 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008890 for (size_t i = 0; i < numtracks ; ++i) {
8891 sp<RecordTrack> track = mTracks[i];
8892 if (track != 0) {
8893 bool active = mActiveTracks.indexOf(track) >= 0;
8894 if (active) {
8895 numactiveseen++;
8896 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008897 result.append(prefix);
8898 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008899 }
Eric Laurent81784c32012-11-19 14:55:58 -08008900 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008901 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008902 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008903 }
8904
Marco Nelissenb2208842014-02-07 14:00:50 -08008905 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008906 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008907 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008908 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008909 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008910 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008911 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008912 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008913 result.append(prefix);
8914 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008915 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008916 }
Eric Laurent81784c32012-11-19 14:55:58 -08008917
8918 }
8919 write(fd, result.string(), result.size());
8920}
8921
Eric Laurent5ada82e2019-08-29 17:53:54 -07008922void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008923{
8924 Mutex::Autolock _l(mLock);
8925 for (size_t i = 0; i < mTracks.size() ; i++) {
8926 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008927 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008928 track->setSilenced(silenced);
8929 }
8930 }
8931}
Andy Hung73c02e42015-03-29 01:13:58 -07008932
8933void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8934{
8935 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8936 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008937 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008938 const int32_t rear = recordThread->mRsmpInRear;
8939 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008940 if (mRecordTrack->startFrames() >= 0) {
8941 int32_t startFrames = mRecordTrack->startFrames();
8942 // Accept a recent wraparound of mRsmpInRear
8943 if (startFrames <= rear) {
8944 deltaFrames = rear - startFrames;
8945 } else {
8946 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008947 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008948 // start frame cannot be further in the past than start of resampling buffer
8949 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8950 deltaFrames = recordThread->mRsmpInFrames;
8951 }
8952 }
8953 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008954}
8955
8956void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8957 size_t *framesAvailable, bool *hasOverrun)
8958{
8959 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8960 RecordThread *recordThread = (RecordThread *) threadBase.get();
8961 const int32_t rear = recordThread->mRsmpInRear;
8962 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008963 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008964
8965 size_t framesIn;
8966 bool overrun = false;
8967 if (filled < 0) {
8968 // should not happen, but treat like a massive overrun and re-sync
8969 framesIn = 0;
8970 mRsmpInFront = rear;
8971 overrun = true;
8972 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8973 framesIn = (size_t) filled;
8974 } else {
8975 // client is not keeping up with server, but give it latest data
8976 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008977 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8978 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008979 overrun = true;
8980 }
8981 if (framesAvailable != NULL) {
8982 *framesAvailable = framesIn;
8983 }
8984 if (hasOverrun != NULL) {
8985 *hasOverrun = overrun;
8986 }
8987}
8988
Eric Laurent81784c32012-11-19 14:55:58 -08008989// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008990status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008991 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008992{
Andy Hung73c02e42015-03-29 01:13:58 -07008993 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008994 if (threadBase == 0) {
8995 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008996 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008997 return NOT_ENOUGH_DATA;
8998 }
8999 RecordThread *recordThread = (RecordThread *) threadBase.get();
9000 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009001 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009002 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009003 // FIXME should not be P2 (don't want to increase latency)
9004 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009005 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009006 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009007
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009008 front &= recordThread->mRsmpInFramesP2 - 1;
9009 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009010 if (part1 > (size_t) filled) {
9011 part1 = filled;
9012 }
9013 size_t ask = buffer->frameCount;
9014 ALOG_ASSERT(ask > 0);
9015 if (part1 > ask) {
9016 part1 = ask;
9017 }
9018 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009019 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009020 buffer->raw = NULL;
9021 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009022 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009023 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009024 }
9025
Andy Hung57446612015-04-19 23:56:46 -07009026 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009027 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009028 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009029 return NO_ERROR;
9030}
9031
9032// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009033void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
9034 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009035{
Hongwei Wang95e37682019-04-12 11:13:36 -07009036 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009037 if (stepCount == 0) {
9038 return;
9039 }
Andy Hung73c02e42015-03-29 01:13:58 -07009040 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
9041 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009042 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009043 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009044 buffer->frameCount = 0;
9045}
9046
Eric Laurentd8365c52017-07-16 15:27:05 -07009047void AudioFlinger::RecordThread::checkBtNrec()
9048{
9049 Mutex::Autolock _l(mLock);
9050 checkBtNrec_l();
9051}
9052
9053void AudioFlinger::RecordThread::checkBtNrec_l()
9054{
9055 // disable AEC and NS if the device is a BT SCO headset supporting those
9056 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009057 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07009058 mAudioFlinger->btNrecIsOff();
9059 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9060 for (size_t i = 0; i < mEffectChains.size(); i++) {
9061 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9062 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9063 }
9064 }
9065}
9066
Andy Hung97a893e2015-03-29 01:03:07 -07009067
Eric Laurent10351942014-05-08 18:49:52 -07009068bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
9069 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009070{
9071 bool reconfig = false;
9072
Eric Laurent10351942014-05-08 18:49:52 -07009073 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009074
Eric Laurent10351942014-05-08 18:49:52 -07009075 audio_format_t reqFormat = mFormat;
9076 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009077 // 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 +08009078 [[maybe_unused]] audio_channel_mask_t channelMask =
9079 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009080
9081 AudioParameter param = AudioParameter(keyValuePair);
9082 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009083
9084 // scope for AutoPark extends to end of method
9085 AutoPark<FastCapture> park(mFastCapture);
9086
Eric Laurent10351942014-05-08 18:49:52 -07009087 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9088 // channel count change can be requested. Do we mandate the first client defines the
9089 // HAL sampling rate and channel count or do we allow changes on the fly?
9090 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9091 samplingRate = value;
9092 reconfig = true;
9093 }
9094 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009095 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009096 status = BAD_VALUE;
9097 } else {
9098 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009099 reconfig = true;
9100 }
Eric Laurent10351942014-05-08 18:49:52 -07009101 }
9102 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9103 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009104 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009105 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009106 status = BAD_VALUE;
9107 } else {
9108 channelMask = mask;
9109 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009110 }
Eric Laurent10351942014-05-08 18:49:52 -07009111 }
9112 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9113 // do not accept frame count changes if tracks are open as the track buffer
9114 // size depends on frame count and correct behavior would not be guaranteed
9115 // if frame count is changed after track creation
9116 if (mActiveTracks.size() > 0) {
9117 status = INVALID_OPERATION;
9118 } else {
9119 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009120 }
Eric Laurent10351942014-05-08 18:49:52 -07009121 }
9122 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009123 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009124 }
9125 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9126 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009127 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009128 }
Glenn Kastene198c362013-08-13 09:13:36 -07009129
Eric Laurent10351942014-05-08 18:49:52 -07009130 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009131 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009132 if (status == INVALID_OPERATION) {
9133 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009134 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009135 }
9136 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009137 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009138 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9139 if (mInput->stream->getAudioProperties(&config) == OK &&
9140 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9141 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009142 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009143 status = NO_ERROR;
9144 }
Eric Laurent81784c32012-11-19 14:55:58 -08009145 }
Eric Laurent10351942014-05-08 18:49:52 -07009146 if (status == NO_ERROR) {
9147 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009148 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009149 }
9150 }
Eric Laurent81784c32012-11-19 14:55:58 -08009151 }
Eric Laurent10351942014-05-08 18:49:52 -07009152
Eric Laurent81784c32012-11-19 14:55:58 -08009153 return reconfig;
9154}
9155
9156String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
9157{
Eric Laurent81784c32012-11-19 14:55:58 -08009158 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009159 if (initCheck() == NO_ERROR) {
9160 String8 out_s8;
9161 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9162 return out_s8;
9163 }
Eric Laurent81784c32012-11-19 14:55:58 -08009164 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009165 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08009166}
9167
Mikhail Naganov88536df2021-07-26 17:30:29 -07009168void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009169 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009170 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009171 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009172 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009173 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009174 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009175 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9176 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009177 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009178 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009179 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009180 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009181 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009182 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009183 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009184 break;
9185 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07009186 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009187}
9188
Glenn Kastendeca2ae2014-02-07 10:25:56 -08009189void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009190{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009191 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9192 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009193 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009194 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9195 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009196 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9197 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009198 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009199 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009200 ALOGI("HAL format %#x is not linear pcm", mFormat);
9201 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009202 result = mInput->stream->getFrameSize(&mFrameSize);
9203 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009204 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9205 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009206 result = mInput->stream->getBufferSize(&mBufferSize);
9207 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009208 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009209 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9210 "mBufferSize=%zu, mFrameCount=%zu",
9211 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009212
Eric Laurentec376dc2021-04-08 20:41:22 +02009213 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9214 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009215 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009216
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009217 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9218 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009219
9220 audio_input_flags_t flags = mInput->flags;
9221 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9222 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9223 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9224 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9225 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9226 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9227 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9228 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9229 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009230}
9231
Glenn Kasten5f972c02014-01-13 09:59:31 -08009232uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08009233{
9234 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009235 uint32_t result;
9236 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9237 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009238 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009239 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009240}
9241
Glenn Kastend848eb42016-03-08 13:42:11 -08009242KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009243{
Glenn Kastend848eb42016-03-08 13:42:11 -08009244 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009245 Mutex::Autolock _l(mLock);
9246 for (size_t j = 0; j < mTracks.size(); ++j) {
9247 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009248 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009249 if (ids.indexOfKey(sessionId) < 0) {
9250 ids.add(sessionId, true);
9251 }
9252 }
9253 return ids;
9254}
9255
9256AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
9257{
9258 Mutex::Autolock _l(mLock);
9259 AudioStreamIn *input = mInput;
9260 mInput = NULL;
9261 return input;
9262}
9263
9264// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009265sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009266{
9267 if (mInput == NULL) {
9268 return NULL;
9269 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009270 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009271}
9272
9273status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
9274{
Eric Laurent81784c32012-11-19 14:55:58 -08009275 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009276 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009277 chain->setInBuffer(NULL);
9278 chain->setOutBuffer(NULL);
9279
9280 checkSuspendOnAddEffectChain_l(chain);
9281
Eric Laurent1b928682014-10-02 19:41:47 -07009282 // make sure enabled pre processing effects state is communicated to the HAL as we
9283 // just moved them to a new input stream.
9284 chain->syncHalEffectsState();
9285
Eric Laurent81784c32012-11-19 14:55:58 -08009286 mEffectChains.add(chain);
9287
9288 return NO_ERROR;
9289}
9290
9291size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
9292{
9293 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009294
9295 for (size_t i = 0; i < mEffectChains.size(); i++) {
9296 if (chain == mEffectChains[i]) {
9297 mEffectChains.removeAt(i);
9298 break;
9299 }
Eric Laurent81784c32012-11-19 14:55:58 -08009300 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009301 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009302}
9303
Eric Laurent1c333e22014-05-20 10:48:17 -07009304status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
9305 audio_patch_handle_t *handle)
9306{
9307 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009308
9309 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009310 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009311 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009312 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009313 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009314 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009315 }
9316
Eric Laurentd8365c52017-07-16 15:27:05 -07009317 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009318
9319 // store new source and send to effects
9320 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9321 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009322 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009323 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009324 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009325 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009326
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009327 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009328 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9329 status = hwDevice->createAudioPatch(patch->num_sources,
9330 patch->sources,
9331 patch->num_sinks,
9332 patch->sinks,
9333 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009334 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009335 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9336 patch->sinks[0].ext.mix.usecase.source,
9337 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009338 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009339 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009340
jiabinc52b1ff2019-10-31 17:20:42 -07009341 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009342 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009343 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009344 }
Eric Laurent296fb132015-05-01 11:38:42 -07009345
Andy Hungc2b11cb2020-04-22 09:04:01 -07009346 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009347 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009348 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009349 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009350 // also dispatch to active AudioRecords
9351 for (const auto &track : mActiveTracks) {
9352 track->logEndInterval();
9353 track->logBeginInterval(pathSourcesAsString);
9354 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009355 return status;
9356}
9357
9358status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9359{
9360 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009361
jiabinc52b1ff2019-10-31 17:20:42 -07009362 mPatch = audio_patch{};
9363 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009364
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009365 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009366 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9367 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009368 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009369 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009370 }
9371 return status;
9372}
9373
jiabinc52b1ff2019-10-31 17:20:42 -07009374void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
9375{
wendy lin56aa82b2020-12-02 15:19:55 +08009376 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009377 mOutDevices = outDevices;
9378 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9379 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009380 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009381 }
9382}
9383
Eric Laurentec376dc2021-04-08 20:41:22 +02009384int32_t AudioFlinger::RecordThread::getOldestFront_l()
9385{
9386 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009387 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009388 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009389 int32_t oldestFront = mRsmpInRear;
9390 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009391 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009392 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9393 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009394 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009395 if (filled > maxFilled) {
9396 oldestFront = front;
9397 maxFilled = filled;
9398 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009399 }
Eric Laurent92d0a322021-07-16 15:32:33 +02009400 if (maxFilled > mRsmpInFrames) {
9401 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9402 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009403 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009404}
9405
9406void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
9407{
9408 if (offset == 0) {
9409 return;
9410 }
9411 for (size_t i = 0; i < mTracks.size(); i++) {
9412 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9413 front = audio_utils::safe_sub_overflow(front, offset);
9414 mTracks[i]->mResamplerBufferProvider->setFront(front);
9415 }
9416}
9417
9418void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
9419{
9420 // This is the formula for calculating the temporary buffer size.
9421 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9422 // 1 full output buffer, regardless of the alignment of the available input.
9423 // The value is somewhat arbitrary, and could probably be even larger.
9424 // A larger value should allow more old data to be read after a track calls start(),
9425 // without increasing latency.
9426 //
9427 // Note this is independent of the maximum downsampling ratio permitted for capture.
9428 size_t minRsmpInFrames = mFrameCount * 7;
9429
9430 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9431 // capture history available to another client using the same session ID:
9432 // dimension the resampler input buffer accordingly.
9433
9434 // Get oldest client read position: getOldestFront_l() must be called before altering
9435 // mRsmpInRear, or mRsmpInFrames
9436 int32_t previousFront = getOldestFront_l();
9437 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9438 int32_t previousRear = mRsmpInRear;
9439 mRsmpInRear = 0;
9440
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009441 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
9442 && maxSharedAudioHistoryMs <= AudioFlinger::kMaxSharedAudioHistoryMs,
9443 "resizeInputBuffer_l() called with invalid max shared history %d",
9444 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009445 if (maxSharedAudioHistoryMs != 0) {
9446 // resizeInputBuffer_l should never be called with a non zero shared history if the
9447 // buffer was not already allocated
9448 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9449 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9450 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9451 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009452 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009453 return;
9454 }
9455 mRsmpInFrames = rsmpInFrames;
9456 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009457 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009458 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9459 // initialized
9460 if (mRsmpInFrames < minRsmpInFrames) {
9461 mRsmpInFrames = minRsmpInFrames;
9462 }
9463 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9464
9465 // TODO optimize audio capture buffer sizes ...
9466 // Here we calculate the size of the sliding buffer used as a source
9467 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9468 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9469 // be better to have it derived from the pipe depth in the long term.
9470 // The current value is higher than necessary. However it should not add to latency.
9471
9472 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9473 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9474
9475 void *rsmpInBuffer;
9476 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9477 // if posix_memalign fails, will segv here.
9478 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9479
9480 // Copy audio history if any from old buffer before freeing it
9481 if (previousRear != 0) {
9482 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9483 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9484
9485 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9486 previousFront &= previousRsmpInFramesP2 - 1;
9487 size_t part1 = previousRsmpInFramesP2 - previousFront;
9488 if (part1 > (size_t) unread) {
9489 part1 = unread;
9490 }
9491 if (part1 != 0) {
9492 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9493 part1 * mFrameSize);
9494 mRsmpInRear = part1;
9495 part1 = unread - part1;
9496 if (part1 != 0) {
9497 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9498 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9499 mRsmpInRear += part1;
9500 }
9501 }
9502 // Update front for all clients according to new rear
9503 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9504 } else {
9505 mRsmpInRear = 0;
9506 }
9507 free(mRsmpInBuffer);
9508 mRsmpInBuffer = rsmpInBuffer;
9509}
9510
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009511void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009512{
9513 Mutex::Autolock _l(mLock);
9514 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009515 if (record->getSource()) {
9516 mSource = record->getSource();
9517 }
Eric Laurent83b88082014-06-20 18:31:16 -07009518}
9519
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009520void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009521{
9522 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009523 if (mSource == record->getSource()) {
9524 mSource = mInput;
9525 }
Eric Laurent83b88082014-06-20 18:31:16 -07009526 destroyTrack_l(record);
9527}
9528
Mikhail Naganovdc769682018-05-04 15:34:08 -07009529void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07009530{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009531 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009532 config->role = AUDIO_PORT_ROLE_SINK;
9533 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9534 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009535 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9536 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9537 config->flags.input = mInput->flags;
9538 }
Eric Laurent83b88082014-06-20 18:31:16 -07009539}
Eric Laurent1c333e22014-05-20 10:48:17 -07009540
Eric Laurent6acd1d42017-01-04 14:23:29 -08009541// ----------------------------------------------------------------------------
9542// Mmap
9543// ----------------------------------------------------------------------------
9544
9545AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
9546 : mThread(thread)
9547{
Phil Burk9fabbf82017-08-03 12:02:00 -07009548 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009549}
9550
9551AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9552{
Phil Burk9fabbf82017-08-03 12:02:00 -07009553 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009554}
9555
9556status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9557 struct audio_mmap_buffer_info *info)
9558{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009559 return mThread->createMmapBuffer(minSizeFrames, info);
9560}
9561
9562status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9563{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009564 return mThread->getMmapPosition(position);
9565}
9566
jiabinb7d8c5a2020-08-26 17:24:52 -07009567status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9568 int64_t *timeNanos) {
9569 return mThread->getExternalPosition(position, timeNanos);
9570}
9571
Eric Laurenta54f1282017-07-01 19:39:32 -07009572status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009573 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009574
9575{
jiabind1f1cb62020-03-24 11:57:57 -07009576 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009577}
9578
9579status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9580{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009581 return mThread->stop(handle);
9582}
9583
Eric Laurent18b57012017-02-13 16:23:52 -08009584status_t AudioFlinger::MmapThreadHandle::standby()
9585{
Eric Laurent18b57012017-02-13 16:23:52 -08009586 return mThread->standby();
9587}
9588
Eric Laurent6acd1d42017-01-04 14:23:29 -08009589
9590AudioFlinger::MmapThread::MmapThread(
9591 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07009592 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009593 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009594 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009595 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009596 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009597 mActiveTracks(&this->mLocalLog),
9598 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9599 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009600{
Eric Laurent18b57012017-02-13 16:23:52 -08009601 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009602 readHalParameters_l();
9603}
9604
9605AudioFlinger::MmapThread::~MmapThread()
9606{
9607}
9608
9609void AudioFlinger::MmapThread::onFirstRef()
9610{
9611 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9612}
9613
9614void AudioFlinger::MmapThread::disconnect()
9615{
Eric Laurent331679c2018-04-16 17:03:16 -07009616 ActiveTracks<MmapTrack> activeTracks;
9617 {
9618 Mutex::Autolock _l(mLock);
9619 for (const sp<MmapTrack> &t : mActiveTracks) {
9620 activeTracks.add(t);
9621 }
9622 }
9623 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009624 stop(t->portId());
9625 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009626 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009627 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009628 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009629 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009630 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009631 }
9632}
9633
9634
9635void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9636 audio_stream_type_t streamType __unused,
9637 audio_session_t sessionId,
9638 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009639 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009640 audio_port_handle_t portId)
9641{
9642 mAttr = *attr;
9643 mSessionId = sessionId;
9644 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009645 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009646 mPortId = portId;
9647}
9648
9649status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9650 struct audio_mmap_buffer_info *info)
9651{
9652 if (mHalStream == 0) {
9653 return NO_INIT;
9654 }
Eric Laurent18b57012017-02-13 16:23:52 -08009655 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009656 return mHalStream->createMmapBuffer(minSizeFrames, info);
9657}
9658
9659status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9660{
9661 if (mHalStream == 0) {
9662 return NO_INIT;
9663 }
9664 return mHalStream->getMmapPosition(position);
9665}
9666
Eric Laurent331679c2018-04-16 17:03:16 -07009667status_t AudioFlinger::MmapThread::exitStandby()
9668{
9669 status_t ret = mHalStream->start();
9670 if (ret != NO_ERROR) {
9671 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9672 return ret;
9673 }
Andy Hungcf10d742020-04-28 15:38:24 -07009674 if (mStandby) {
9675 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009676 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07009677 mStandby = false;
9678 }
Eric Laurent331679c2018-04-16 17:03:16 -07009679 return NO_ERROR;
9680}
9681
Eric Laurenta54f1282017-07-01 19:39:32 -07009682status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009683 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009684 audio_port_handle_t *handle)
9685{
Eric Laurenta54f1282017-07-01 19:39:32 -07009686 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009687 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009688 if (mHalStream == 0) {
9689 return NO_INIT;
9690 }
9691
9692 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009693
Eric Laurenta54f1282017-07-01 19:39:32 -07009694 if (*handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009695 // For the first track, reuse portId and session allocated when the stream was opened.
9696 ret = exitStandby();
9697 if (ret == NO_ERROR) {
9698 acquireWakeLock();
9699 }
9700 return ret;
Eric Laurenta54f1282017-07-01 19:39:32 -07009701 }
9702
9703 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9704
9705 audio_io_handle_t io = mId;
9706 if (isOutput()) {
9707 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9708 config.sample_rate = mSampleRate;
9709 config.channel_mask = mChannelMask;
9710 config.format = mFormat;
9711 audio_stream_type_t stream = streamType();
9712 audio_output_flags_t flags =
9713 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009714 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009715 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02009716 bool isSpatialized;
Eric Laurenta54f1282017-07-01 19:39:32 -07009717 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9718 mSessionId,
9719 &stream,
Svet Ganov33761132021-05-13 22:51:08 +00009720 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009721 &config,
9722 flags,
9723 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009724 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02009725 &secondaryOutputs,
9726 &isSpatialized);
Kevin Rocard153f92d2018-12-18 18:33:28 -08009727 ALOGD_IF(!secondaryOutputs.empty(),
9728 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009729 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009730 audio_config_base_t config;
9731 config.sample_rate = mSampleRate;
9732 config.channel_mask = mChannelMask;
9733 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009734 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009735 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009736 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009737 mSessionId,
Svet Ganov33761132021-05-13 22:51:08 +00009738 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009739 &config,
9740 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9741 &deviceId,
9742 &portId);
9743 }
9744 // APM should not chose a different input or output stream for the same set of attributes
9745 // and audo configuration
9746 if (ret != NO_ERROR || io != mId) {
9747 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9748 __FUNCTION__, ret, io, mId);
9749 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009750 }
9751
9752 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009753 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009754 } else {
jiabincfc10a42022-06-15 19:26:01 +00009755 {
9756 // Add the track record before starting input so that the silent status for the
9757 // client can be cached.
9758 Mutex::Autolock _l(mLock);
9759 setClientSilencedState_l(portId, false /*silenced*/);
9760 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08009761 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009762 }
9763
Eric Laurent331679c2018-04-16 17:03:16 -07009764 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009765 // abort if start is rejected by audio policy manager
9766 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009767 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009768 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009769 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009770 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009771 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009772 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009773 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009774 }
Eric Laurent331679c2018-04-16 17:03:16 -07009775 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009776 } else {
9777 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009778 }
jiabincfc10a42022-06-15 19:26:01 +00009779 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009780 return PERMISSION_DENIED;
9781 }
9782
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009783 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009784 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +00009785 mChannelMask, mSessionId, isOutput(),
9786 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009787 IPCThreadState::self()->getCallingPid(), portId);
jiabincfc10a42022-06-15 19:26:01 +00009788 if (!isOutput()) {
9789 track->setSilenced_l(isClientSilenced_l(portId));
9790 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009791
Eric Laurent4eb58f12018-12-07 16:41:02 -08009792 if (isOutput()) {
9793 // force volume update when a new track is added
9794 mHalVolFloat = -1.0f;
9795 } else if (!track->isSilenced_l()) {
9796 for (const sp<MmapTrack> &t : mActiveTracks) {
Svet Ganov33761132021-05-13 22:51:08 +00009797 if (t->isSilenced_l() && t->uid() != client.attributionSource.uid)
Eric Laurent4eb58f12018-12-07 16:41:02 -08009798 t->invalidate();
9799 }
9800 }
9801
9802
Eric Laurent6acd1d42017-01-04 14:23:29 -08009803 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009804 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009805 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02009806 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009807 chain->incTrackCnt();
9808 chain->incActiveTrackCnt();
9809 }
9810
Andy Hungc2b11cb2020-04-22 09:04:01 -07009811 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009812 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009813 broadcast_l();
9814
Eric Laurenta54f1282017-07-01 19:39:32 -07009815 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009816
9817 return NO_ERROR;
9818}
9819
9820status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9821{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009822 ALOGV("%s handle %d", __FUNCTION__, handle);
9823
9824 if (mHalStream == 0) {
9825 return NO_INIT;
9826 }
9827
Eric Laurenta54f1282017-07-01 19:39:32 -07009828 if (handle == mPortId) {
9829 mHalStream->stop();
Phil Burk98ab4082020-09-25 21:46:34 +00009830 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009831 return NO_ERROR;
9832 }
9833
Eric Laurent331679c2018-04-16 17:03:16 -07009834 Mutex::Autolock _l(mLock);
9835
Eric Laurent6acd1d42017-01-04 14:23:29 -08009836 sp<MmapTrack> track;
9837 for (const sp<MmapTrack> &t : mActiveTracks) {
9838 if (handle == t->portId()) {
9839 track = t;
9840 break;
9841 }
9842 }
9843 if (track == 0) {
9844 return BAD_VALUE;
9845 }
9846
9847 mActiveTracks.remove(track);
jiabincfc10a42022-06-15 19:26:01 +00009848 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009849
Eric Laurent331679c2018-04-16 17:03:16 -07009850 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009851 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009852 AudioSystem::stopOutput(track->portId());
9853 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009854 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009855 AudioSystem::stopInput(track->portId());
9856 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009857 }
Eric Laurent331679c2018-04-16 17:03:16 -07009858 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009859
9860 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9861 if (chain != 0) {
9862 chain->decActiveTrackCnt();
9863 chain->decTrackCnt();
9864 }
9865
9866 broadcast_l();
9867
Eric Laurent6acd1d42017-01-04 14:23:29 -08009868 return NO_ERROR;
9869}
9870
Eric Laurent18b57012017-02-13 16:23:52 -08009871status_t AudioFlinger::MmapThread::standby()
9872{
9873 ALOGV("%s", __FUNCTION__);
9874
9875 if (mHalStream == 0) {
9876 return NO_INIT;
9877 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009878 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009879 return INVALID_OPERATION;
9880 }
9881 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009882 if (!mStandby) {
9883 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009884 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07009885 mStandby = true;
9886 }
Eric Laurent18b57012017-02-13 16:23:52 -08009887 releaseWakeLock();
9888 return NO_ERROR;
9889}
9890
Eric Laurent6acd1d42017-01-04 14:23:29 -08009891
9892void AudioFlinger::MmapThread::readHalParameters_l()
9893{
9894 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9895 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9896 mFormat = mHALFormat;
9897 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9898 result = mHalStream->getFrameSize(&mFrameSize);
9899 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009900 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9901 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009902 result = mHalStream->getBufferSize(&mBufferSize);
9903 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9904 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009905
Andy Hungcf10d742020-04-28 15:38:24 -07009906 // TODO: make a readHalParameters call?
9907 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009908 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9909 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9910 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9911 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9912 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9913 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9914 /*
9915 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9916 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9917 (int32_t)mHapticChannelMask)
9918 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9919 (int32_t)mHapticChannelCount)
9920 */
9921 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9922 formatToString(mHALFormat).c_str())
9923 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9924 (int32_t)mFrameCount) // sic - added HAL
9925 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009926}
9927
9928bool AudioFlinger::MmapThread::threadLoop()
9929{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009930 checkSilentMode_l();
9931
9932 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9933
9934 while (!exitPending())
9935 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009936 Vector< sp<EffectChain> > effectChains;
9937
Andy Hung13850be2019-03-14 11:33:09 -07009938 { // under Thread lock
9939 Mutex::Autolock _l(mLock);
9940
Eric Laurent6acd1d42017-01-04 14:23:29 -08009941 if (mSignalPending) {
9942 // A signal was raised while we were unlocked
9943 mSignalPending = false;
9944 } else {
9945 if (mConfigEvents.isEmpty()) {
9946 // we're about to wait, flush the binder command buffer
9947 IPCThreadState::self()->flushCommands();
9948
9949 if (exitPending()) {
9950 break;
9951 }
9952
Eric Laurent6acd1d42017-01-04 14:23:29 -08009953 // wait until we have something to do...
9954 ALOGV("%s going to sleep", myName.string());
9955 mWaitWorkCV.wait(mLock);
9956 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009957
9958 checkSilentMode_l();
9959
9960 continue;
9961 }
9962 }
9963
9964 processConfigEvents_l();
9965
9966 processVolume_l();
9967
9968 checkInvalidTracks_l();
9969
9970 mActiveTracks.updatePowerState(this);
9971
Kevin Rocard069c2712018-03-29 19:09:14 -07009972 updateMetadata_l();
9973
Eric Laurent6acd1d42017-01-04 14:23:29 -08009974 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009975 } // release Thread lock
9976
Eric Laurent6acd1d42017-01-04 14:23:29 -08009977 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009978 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009979 }
Andy Hung13850be2019-03-14 11:33:09 -07009980
9981 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009982 unlockEffectChains(effectChains);
9983 // Effect chains will be actually deleted here if they were removed from
9984 // mEffectChains list during mixing or effects processing
9985 }
9986
9987 threadLoop_exit();
9988
9989 if (!mStandby) {
9990 threadLoop_standby();
9991 mStandby = true;
9992 }
9993
Eric Laurent6acd1d42017-01-04 14:23:29 -08009994 ALOGV("Thread %p type %d exiting", this, mType);
9995 return false;
9996}
9997
9998// checkForNewParameter_l() must be called with ThreadBase::mLock held
9999bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
10000 status_t& status)
10001{
10002 AudioParameter param = AudioParameter(keyValuePair);
10003 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010004 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010005 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010006 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010007 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010008 if (sendToHal) {
10009 status = mHalStream->setParameters(keyValuePair);
10010 } else {
10011 status = NO_ERROR;
10012 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010013
10014 return false;
10015}
10016
10017String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
10018{
10019 Mutex::Autolock _l(mLock);
10020 String8 out_s8;
10021 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10022 return out_s8;
10023 }
10024 return String8();
10025}
10026
Mikhail Naganov88536df2021-07-26 17:30:29 -070010027void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010028 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010029 sp<AudioIoDescriptor> desc;
10030 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010031 switch (event) {
10032 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010033 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010034 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010035 isInput = true;
10036 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010037 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010038 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010039 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010040 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10041 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010042 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010043 case AUDIO_INPUT_CLOSED:
10044 case AUDIO_OUTPUT_CLOSED:
10045 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010046 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010047 break;
10048 }
10049 mAudioFlinger->ioConfigChanged(event, desc, pid);
10050}
10051
10052status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
10053 audio_patch_handle_t *handle)
10054{
10055 status_t status = NO_ERROR;
10056
10057 // store new device and send to effects
10058 audio_devices_t type = AUDIO_DEVICE_NONE;
10059 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010060 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10061 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10062 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010063 if (isOutput()) {
10064 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010065 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10066 && !mAudioHwDev->supportsAudioPatches(),
10067 "Enumerated device type(%#x) must not be used "
10068 "as it does not support audio patches",
10069 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010070 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -070010071 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
10072 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010073 }
10074 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010075 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010076 } else {
10077 type = patch->sources[0].ext.device.type;
10078 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010079 numDevices = mPatch.num_sources;
10080 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010081 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010082 }
10083
10084 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010085 if (isOutput()) {
10086 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10087 } else {
10088 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10089 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010090 }
10091
jiabinc52b1ff2019-10-31 17:20:42 -070010092 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010093 // store new source and send to effects
10094 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10095 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10096 for (size_t i = 0; i < mEffectChains.size(); i++) {
10097 mEffectChains[i]->setAudioSource_l(mAudioSource);
10098 }
10099 }
10100 }
10101
10102 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010103 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10104 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010105 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010106 audio_port_config port;
10107 std::optional<audio_source_t> source;
10108 if (isOutput()) {
10109 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010110 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010111 port = patch->sources[0];
10112 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010113 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010114 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010115 *handle = AUDIO_PATCH_HANDLE_NONE;
10116 }
10117
jiabinc52b1ff2019-10-31 17:20:42 -070010118 if (numDevices == 0 || mDeviceId != deviceId) {
10119 if (isOutput()) {
10120 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10121 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010122 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010123 } else {
10124 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10125 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10126 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010127 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010128 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010129 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010130 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -070010131 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010132 }
jiabinc52b1ff2019-10-31 17:20:42 -070010133 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010134 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010135 }
10136 return status;
10137}
10138
10139status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
10140{
10141 status_t status = NO_ERROR;
10142
jiabinc52b1ff2019-10-31 17:20:42 -070010143 mPatch = audio_patch{};
10144 mOutDeviceTypeAddrs.clear();
10145 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010146
10147 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10148 supportsAudioPatches : false;
10149
10150 if (supportsAudioPatches) {
10151 status = mHalDevice->releaseAudioPatch(handle);
10152 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010153 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010154 }
10155 return status;
10156}
10157
Mikhail Naganovdc769682018-05-04 15:34:08 -070010158void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010159{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010160 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010161 if (isOutput()) {
10162 config->role = AUDIO_PORT_ROLE_SOURCE;
10163 config->ext.mix.hw_module = mAudioHwDev->handle();
10164 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10165 } else {
10166 config->role = AUDIO_PORT_ROLE_SINK;
10167 config->ext.mix.hw_module = mAudioHwDev->handle();
10168 config->ext.mix.usecase.source = mAudioSource;
10169 }
10170}
10171
10172status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
10173{
10174 audio_session_t session = chain->sessionId();
10175
10176 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10177 // Attach all tracks with same session ID to this chain.
10178 // indicate all active tracks in the chain
10179 for (const sp<MmapTrack> &track : mActiveTracks) {
10180 if (session == track->sessionId()) {
10181 chain->incTrackCnt();
10182 chain->incActiveTrackCnt();
10183 }
10184 }
10185
10186 chain->setThread(this);
10187 chain->setInBuffer(nullptr);
10188 chain->setOutBuffer(nullptr);
10189 chain->syncHalEffectsState();
10190
10191 mEffectChains.add(chain);
10192 checkSuspendOnAddEffectChain_l(chain);
10193 return NO_ERROR;
10194}
10195
10196size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
10197{
10198 audio_session_t session = chain->sessionId();
10199
10200 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10201
10202 for (size_t i = 0; i < mEffectChains.size(); i++) {
10203 if (chain == mEffectChains[i]) {
10204 mEffectChains.removeAt(i);
10205 // detach all active tracks from the chain
10206 // detach all tracks with same session ID from this chain
10207 for (const sp<MmapTrack> &track : mActiveTracks) {
10208 if (session == track->sessionId()) {
10209 chain->decActiveTrackCnt();
10210 chain->decTrackCnt();
10211 }
10212 }
10213 break;
10214 }
10215 }
10216 return mEffectChains.size();
10217}
10218
Eric Laurent6acd1d42017-01-04 14:23:29 -080010219void AudioFlinger::MmapThread::threadLoop_standby()
10220{
10221 mHalStream->standby();
10222}
10223
10224void AudioFlinger::MmapThread::threadLoop_exit()
10225{
Phil Burk7dce7282017-09-27 13:51:41 -070010226 // Do not call callback->onTearDown() because it is redundant for thread exit
10227 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010228}
10229
10230status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
10231{
10232 return BAD_VALUE;
10233}
10234
10235bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
10236{
10237 return false;
10238}
10239
10240status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
10241 const effect_descriptor_t *desc, audio_session_t sessionId)
10242{
10243 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010244 if (audio_is_global_session(sessionId)) {
10245 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010246 desc->name, mThreadName);
10247 return BAD_VALUE;
10248 }
10249
10250 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10251 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10252 desc->name);
10253 return BAD_VALUE;
10254 }
10255 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010256 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10257 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010258 return BAD_VALUE;
10259 }
10260
10261 // Only allow effects without processing load or latency
10262 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10263 return BAD_VALUE;
10264 }
10265
jiabineb3bda02020-06-30 14:07:03 -070010266 if (EffectModule::isHapticGenerator(&desc->type)) {
10267 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10268 return BAD_VALUE;
10269 }
10270
Eric Laurent6acd1d42017-01-04 14:23:29 -080010271 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010272}
10273
10274void AudioFlinger::MmapThread::checkInvalidTracks_l()
10275{
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010276 sp<MmapStreamCallback> callback;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010277 for (const sp<MmapTrack> &track : mActiveTracks) {
10278 if (track->isInvalid()) {
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010279 callback = mCallback.promote();
10280 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10281 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
Eric Laurent331679c2018-04-16 17:03:16 -070010282 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010283 }
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010284 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010285 }
10286 }
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010287 if (callback != 0) {
10288 mLock.unlock();
10289 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10290 mLock.lock();
10291 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010292}
10293
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010294void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010295{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010296 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10297 mAttr.content_type, mAttr.usage, mAttr.source);
10298 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010299 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010300 dprintf(fd, " No active clients\n");
10301 }
10302}
10303
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010304void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010305{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010306 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010307 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010308 dprintf(fd, " %zu Tracks\n", numtracks);
10309 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010310 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010311 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010312 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010313 for (size_t i = 0; i < numtracks ; ++i) {
10314 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010315 result.append(prefix);
10316 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010317 }
10318 } else {
10319 dprintf(fd, "\n");
10320 }
10321 write(fd, result.string(), result.size());
10322}
10323
10324AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
10325 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010326 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010327 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010328 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010329 mStreamVolume(1.0),
10330 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010331 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010332{
10333 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10334 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
10335 mMasterVolume = audioFlinger->masterVolume_l();
10336 mMasterMute = audioFlinger->masterMute_l();
10337 if (mAudioHwDev) {
10338 if (mAudioHwDev->canSetMasterVolume()) {
10339 mMasterVolume = 1.0;
10340 }
10341
10342 if (mAudioHwDev->canSetMasterMute()) {
10343 mMasterMute = false;
10344 }
10345 }
10346}
10347
10348void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
10349 audio_stream_type_t streamType,
10350 audio_session_t sessionId,
10351 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010352 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010353 audio_port_handle_t portId)
10354{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010355 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010356 mStreamType = streamType;
10357}
10358
10359AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
10360{
10361 Mutex::Autolock _l(mLock);
10362 AudioStreamOut *output = mOutput;
10363 mOutput = NULL;
10364 return output;
10365}
10366
10367void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
10368{
10369 Mutex::Autolock _l(mLock);
10370 // Don't apply master volume in SW if our HAL can do it for us.
10371 if (mAudioHwDev &&
10372 mAudioHwDev->canSetMasterVolume()) {
10373 mMasterVolume = 1.0;
10374 } else {
10375 mMasterVolume = value;
10376 }
10377}
10378
10379void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
10380{
10381 Mutex::Autolock _l(mLock);
10382 // Don't apply master mute in SW if our HAL can do it for us.
10383 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10384 mMasterMute = false;
10385 } else {
10386 mMasterMute = muted;
10387 }
10388}
10389
10390void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
10391{
10392 Mutex::Autolock _l(mLock);
10393 if (stream == mStreamType) {
10394 mStreamVolume = value;
10395 broadcast_l();
10396 }
10397}
10398
10399float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
10400{
10401 Mutex::Autolock _l(mLock);
10402 if (stream == mStreamType) {
10403 return mStreamVolume;
10404 }
10405 return 0.0f;
10406}
10407
10408void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
10409{
10410 Mutex::Autolock _l(mLock);
10411 if (stream == mStreamType) {
10412 mStreamMute= muted;
10413 broadcast_l();
10414 }
10415}
10416
10417void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
10418{
10419 Mutex::Autolock _l(mLock);
10420 if (streamType == mStreamType) {
10421 for (const sp<MmapTrack> &track : mActiveTracks) {
10422 track->invalidate();
10423 }
10424 broadcast_l();
10425 }
10426}
10427
10428void AudioFlinger::MmapPlaybackThread::processVolume_l()
10429{
10430 float volume;
10431
10432 if (mMasterMute || mStreamMute) {
10433 volume = 0;
10434 } else {
10435 volume = mMasterVolume * mStreamVolume;
10436 }
10437
10438 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010439
10440 // Convert volumes from float to 8.24
10441 uint32_t vol = (uint32_t)(volume * (1 << 24));
10442
10443 // Delegate volume control to effect in track effect chain if needed
10444 // only one effect chain can be present on DirectOutputThread, so if
10445 // there is one, the track is connected to it
10446 if (!mEffectChains.isEmpty()) {
10447 mEffectChains[0]->setVolume_l(&vol, &vol);
10448 volume = (float)vol / (1 << 24);
10449 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010450 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010451 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10452 mHalVolFloat = volume; // HW volume control worked, so update value.
10453 mNoCallbackWarningCount = 0;
10454 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010455 sp<MmapStreamCallback> callback = mCallback.promote();
10456 if (callback != 0) {
10457 int channelCount;
10458 if (isOutput()) {
10459 channelCount = audio_channel_count_from_out_mask(mChannelMask);
10460 } else {
10461 channelCount = audio_channel_count_from_in_mask(mChannelMask);
10462 }
10463 Vector<float> values;
10464 for (int i = 0; i < channelCount; i++) {
10465 values.add(volume);
10466 }
Phil Burk56ecf3e2018-03-12 15:38:17 -070010467 mHalVolFloat = volume; // SW volume control worked, so update value.
10468 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010469 mLock.unlock();
10470 callback->onVolumeChanged(mChannelMask, values);
10471 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010472 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010473 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10474 ALOGW("Could not set MMAP stream volume: no volume callback!");
10475 mNoCallbackWarningCount++;
10476 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010477 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010478 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010479 for (const sp<MmapTrack> &track : mActiveTracks) {
10480 track->setMetadataHasChanged();
10481 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010482 }
10483}
10484
Kevin Rocard069c2712018-03-29 19:09:14 -070010485void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
10486{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010487 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10488 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010489 }
10490 StreamOutHalInterface::SourceMetadata metadata;
10491 for (const sp<MmapTrack> &track : mActiveTracks) {
10492 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010493 playback_track_metadata_v7_t trackMetadata;
10494 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010495 .usage = track->attributes().usage,
10496 .content_type = track->attributes().content_type,
10497 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010498 };
10499 trackMetadata.channel_mask = track->channelMask(),
10500 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10501 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010502 }
10503 mOutput->stream->updateSourceMetadata(metadata);
10504}
10505
Eric Laurent6acd1d42017-01-04 14:23:29 -080010506void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
10507{
10508 if (!mMasterMute) {
10509 char value[PROPERTY_VALUE_MAX];
10510 if (property_get("ro.audio.silent", value, "0") > 0) {
10511 char *endptr;
10512 unsigned long ul = strtoul(value, &endptr, 0);
10513 if (*endptr == '\0' && ul != 0) {
10514 ALOGD("Silence is golden");
10515 // The setprop command will not allow a property to be changed after
10516 // the first time it is set, so we don't have to worry about un-muting.
10517 setMasterMute_l(true);
10518 }
10519 }
10520 }
10521}
10522
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010523void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
10524{
10525 MmapThread::toAudioPortConfig(config);
10526 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10527 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10528 config->flags.output = mOutput->flags;
10529 }
10530}
10531
jiabinb7d8c5a2020-08-26 17:24:52 -070010532status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
10533 int64_t *timeNanos)
10534{
10535 if (mOutput == nullptr) {
10536 return NO_INIT;
10537 }
10538 struct timespec timestamp;
10539 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10540 if (status == NO_ERROR) {
10541 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10542 }
10543 return status;
10544}
10545
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010546void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010547{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010548 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010549
Glenn Kastend3bb6452016-12-05 18:14:37 -080010550 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10551 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010552 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10553}
10554
10555AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10556 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010557 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010558 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010559 mInput(input)
10560{
10561 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10562 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10563}
10564
Eric Laurent331679c2018-04-16 17:03:16 -070010565status_t AudioFlinger::MmapCaptureThread::exitStandby()
10566{
Phil Burkf054fc32018-12-06 09:45:59 -080010567 {
10568 // mInput might have been cleared by clearInput()
10569 Mutex::Autolock _l(mLock);
10570 if (mInput != nullptr && mInput->stream != nullptr) {
10571 mInput->stream->setGain(1.0f);
10572 }
10573 }
Eric Laurent331679c2018-04-16 17:03:16 -070010574 return MmapThread::exitStandby();
10575}
10576
Eric Laurent6acd1d42017-01-04 14:23:29 -080010577AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10578{
10579 Mutex::Autolock _l(mLock);
10580 AudioStreamIn *input = mInput;
10581 mInput = NULL;
10582 return input;
10583}
Kevin Rocard069c2712018-03-29 19:09:14 -070010584
Eric Laurent331679c2018-04-16 17:03:16 -070010585
10586void AudioFlinger::MmapCaptureThread::processVolume_l()
10587{
10588 bool changed = false;
10589 bool silenced = false;
10590
10591 sp<MmapStreamCallback> callback = mCallback.promote();
10592 if (callback == 0) {
10593 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10594 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10595 mNoCallbackWarningCount++;
10596 }
10597 }
10598
10599 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10600 // track is silenced and unmute otherwise
10601 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10602 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10603 changed = true;
10604 silenced = mActiveTracks[i]->isSilenced_l();
10605 }
10606 }
10607
10608 if (changed) {
10609 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10610 }
10611}
10612
Kevin Rocard069c2712018-03-29 19:09:14 -070010613void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10614{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010615 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10616 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010617 }
10618 StreamInHalInterface::SinkMetadata metadata;
10619 for (const sp<MmapTrack> &track : mActiveTracks) {
10620 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010621 record_track_metadata_v7_t trackMetadata;
10622 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010623 .source = track->attributes().source,
10624 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010625 };
10626 trackMetadata.channel_mask = track->channelMask(),
10627 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10628 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010629 }
10630 mInput->stream->updateSinkMetadata(metadata);
10631}
10632
Eric Laurent5ada82e2019-08-29 17:53:54 -070010633void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010634{
10635 Mutex::Autolock _l(mLock);
10636 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010637 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010638 mActiveTracks[i]->setSilenced_l(silenced);
10639 broadcast_l();
10640 }
10641 }
jiabincfc10a42022-06-15 19:26:01 +000010642 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070010643}
10644
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010645void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10646{
10647 MmapThread::toAudioPortConfig(config);
10648 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10649 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10650 config->flags.input = mInput->flags;
10651 }
10652}
10653
jiabinb7d8c5a2020-08-26 17:24:52 -070010654status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10655 uint64_t *position, int64_t *timeNanos)
10656{
10657 if (mInput == nullptr) {
10658 return NO_INIT;
10659 }
10660 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10661}
10662
Glenn Kasten63238ef2015-03-02 15:50:29 -080010663} // namespace android