blob: c0e612dcf8b7e604c7c3a56cb4881a0e9087875f [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 Hung5d8618d2022-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).
274 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
275 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
276}
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 {
2143 // setEventCallback will need a strong pointer as a parameter. Calling it
2144 // here instead of constructor of PlaybackThread so that the onFirstRef
2145 // callback would not be made on an incompletely constructed object.
2146 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002147 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002148 }
2149 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002150 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002151 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002152}
2153
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002154// ThreadBase virtuals
2155void AudioFlinger::PlaybackThread::preExit()
2156{
2157 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002158 status_t result = mOutput->stream->exit();
2159 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002160}
2161
2162void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002163{
Eric Laurent81784c32012-11-19 14:55:58 -08002164 String8 result;
2165
Marco Nelissenb2208842014-02-07 14:00:50 -08002166 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002167 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2168 const stream_type_t *st = &mStreamTypes[i];
2169 if (i > 0) {
2170 result.appendFormat(", ");
2171 }
2172 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2173 if (st->mute) {
2174 result.append("M");
2175 }
2176 }
2177 result.append("\n");
2178 write(fd, result.string(), result.length());
2179 result.clear();
2180
Eric Laurent81784c32012-11-19 14:55:58 -08002181 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2182 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002183 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002184 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002185
2186 size_t numtracks = mTracks.size();
2187 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002188 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002189 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002190 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002191 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002192 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002193 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002194 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002195 for (size_t i = 0; i < numtracks; ++i) {
2196 sp<Track> track = mTracks[i];
2197 if (track != 0) {
2198 bool active = mActiveTracks.indexOf(track) >= 0;
2199 if (active) {
2200 numactiveseen++;
2201 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002202 result.append(prefix);
2203 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002204 }
2205 }
2206 } else {
2207 result.append("\n");
2208 }
2209 if (numactiveseen != numactive) {
2210 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002211 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002212 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002213 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002214 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002215 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002216 sp<Track> track = mActiveTracks[i];
2217 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002218 result.append(prefix);
2219 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002220 }
2221 }
2222 }
2223
2224 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002225}
2226
Andy Hung61589a42021-06-16 09:37:53 -07002227void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002228{
Andy Hung04cb8f72020-03-20 13:44:33 -07002229 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002230 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002231 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2232 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002233 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2234 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2235 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2236 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002237 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002238 dprintf(fd, " Total writes: %d\n", mNumWrites);
2239 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2240 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2241 dprintf(fd, " Suspend count: %d\n", mSuspended);
2242 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2243 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2244 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2245 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002246 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002247 AudioStreamOut *output = mOutput;
2248 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002249 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002250 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002251 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2252 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2253 if (mPipeSink.get() != nullptr) {
2254 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2255 }
2256 if (output != nullptr) {
2257 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002258 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002259 }
Eric Laurent81784c32012-11-19 14:55:58 -08002260}
2261
Eric Laurent81784c32012-11-19 14:55:58 -08002262// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2263sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2264 const sp<AudioFlinger::Client>& client,
2265 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002266 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002267 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002268 audio_format_t format,
2269 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002270 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002271 size_t *pNotificationFrameCount,
2272 uint32_t notificationsPerBuffer,
2273 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002274 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002275 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002276 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002277 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002278 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002279 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002280 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002281 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002282 const sp<media::IAudioTrackCallback>& callback,
2283 bool isSpatialized)
Eric Laurent81784c32012-11-19 14:55:58 -08002284{
Glenn Kasten74935e42013-12-19 08:56:45 -08002285 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002286 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002287 sp<Track> track;
2288 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002289 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002290 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002291 uint32_t sampleRate;
2292
2293 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2294 lStatus = BAD_VALUE;
2295 goto Exit;
2296 }
Eric Laurent21da6472017-11-09 16:29:26 -08002297
2298 if (*pSampleRate == 0) {
2299 *pSampleRate = mSampleRate;
2300 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002301 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002302
2303 // special case for FAST flag considered OK if fast mixer is present
2304 if (hasFastMixer()) {
2305 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2306 }
2307
2308 // Check if requested flags are compatible with output stream flags
2309 if ((*flags & outputFlags) != *flags) {
2310 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2311 *flags, outputFlags);
2312 *flags = (audio_output_flags_t)(*flags & outputFlags);
2313 }
Eric Laurent81784c32012-11-19 14:55:58 -08002314
Eric Laurent81784c32012-11-19 14:55:58 -08002315 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002316 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002317 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002318 // PCM data
2319 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002320 // TODO: extract as a data library function that checks that a computationally
2321 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002322 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002323 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2324 (channelMask == AUDIO_CHANNEL_OUT_MONO
2325 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002326 // hardware sample rate
2327 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002328 // normal mixer has an associated fast mixer
2329 hasFastMixer() &&
2330 // there are sufficient fast track slots available
2331 (mFastTrackAvailMask != 0)
2332 // FIXME test that MixerThread for this fast track has a capable output HAL
2333 // FIXME add a permission test also?
2334 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002335 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2336 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002337 // read the fast track multiplier property the first time it is needed
2338 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2339 if (ok != 0) {
2340 ALOGE("%s pthread_once failed: %d", __func__, ok);
2341 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002342 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002343 }
Eric Laurent4c415062016-06-17 16:14:16 -07002344
2345 // check compatibility with audio effects.
2346 { // scope for mLock
2347 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002348 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002349 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002350 AUDIO_SESSION_OUTPUT_STAGE,
2351 AUDIO_SESSION_OUTPUT_MIX,
2352 sessionId,
2353 }) {
2354 sp<EffectChain> chain = getEffectChain_l(session);
2355 if (chain.get() != nullptr) {
2356 audio_output_flags_t old = *flags;
2357 chain->checkOutputFlagCompatibility(flags);
2358 if (old != *flags) {
2359 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2360 (int)session, (int)old, (int)*flags);
2361 }
Eric Laurent4c415062016-06-17 16:14:16 -07002362 }
2363 }
2364 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002365 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002366 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2367 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002368 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002369 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002370 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002371 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002372 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002373 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002374 audio_is_linear_pcm(format), channelMask, sampleRate,
2375 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002376 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002377 }
2378 }
Eric Laurent21da6472017-11-09 16:29:26 -08002379
2380 if (!audio_has_proportional_frames(format)) {
2381 if (sharedBuffer != 0) {
2382 // Same comment as below about ignoring frameCount parameter for set()
2383 frameCount = sharedBuffer->size();
2384 } else if (frameCount == 0) {
2385 frameCount = mNormalFrameCount;
2386 }
2387 if (notificationFrameCount != frameCount) {
2388 notificationFrameCount = frameCount;
2389 }
2390 } else if (sharedBuffer != 0) {
2391 // FIXME: Ensure client side memory buffers need
2392 // not have additional alignment beyond sample
2393 // (e.g. 16 bit stereo accessed as 32 bit frame).
2394 size_t alignment = audio_bytes_per_sample(format);
2395 if (alignment & 1) {
2396 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2397 alignment = 1;
2398 }
2399 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2400 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2401 if (channelCount > 1) {
2402 // More than 2 channels does not require stronger alignment than stereo
2403 alignment <<= 1;
2404 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002405 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002406 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002407 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002408 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002409 goto Exit;
2410 }
Eric Laurent21da6472017-11-09 16:29:26 -08002411
2412 // When initializing a shared buffer AudioTrack via constructors,
2413 // there's no frameCount parameter.
2414 // But when initializing a shared buffer AudioTrack via set(),
2415 // there _is_ a frameCount parameter. We silently ignore it.
2416 frameCount = sharedBuffer->size() / frameSize;
2417 } else {
2418 size_t minFrameCount = 0;
2419 // For fast tracks we try to respect the application's request for notifications per buffer.
2420 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2421 if (notificationsPerBuffer > 0) {
2422 // Avoid possible arithmetic overflow during multiplication.
2423 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2424 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2425 notificationsPerBuffer, mFrameCount);
2426 } else {
2427 minFrameCount = mFrameCount * notificationsPerBuffer;
2428 }
2429 }
2430 } else {
2431 // For normal PCM streaming tracks, update minimum frame count.
2432 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2433 // cover audio hardware latency.
2434 // This is probably too conservative, but legacy application code may depend on it.
2435 // If you change this calculation, also review the start threshold which is related.
2436 uint32_t latencyMs = latency_l();
2437 if (latencyMs == 0) {
2438 ALOGE("Error when retrieving output stream latency");
2439 lStatus = UNKNOWN_ERROR;
2440 goto Exit;
2441 }
2442
2443 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2444 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2445
Eric Laurent81784c32012-11-19 14:55:58 -08002446 }
Eric Laurent21da6472017-11-09 16:29:26 -08002447 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002448 frameCount = minFrameCount;
2449 }
Eric Laurent81784c32012-11-19 14:55:58 -08002450 }
Eric Laurent21da6472017-11-09 16:29:26 -08002451
2452 // Make sure that application is notified with sufficient margin before underrun.
2453 // The client can divide the AudioTrack buffer into sub-buffers,
2454 // and expresses its desire to server as the notification frame count.
2455 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2456 size_t maxNotificationFrames;
2457 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2458 // notify every HAL buffer, regardless of the size of the track buffer
2459 maxNotificationFrames = mFrameCount;
2460 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002461 // Triple buffer the notification period for a triple buffered mixer period;
2462 // otherwise, double buffering for the notification period is fine.
2463 //
2464 // TODO: This should be moved to AudioTrack to modify the notification period
2465 // on AudioTrack::setBufferSizeInFrames() changes.
2466 const int nBuffering =
2467 (uint64_t{frameCount} * mSampleRate)
2468 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2469
Eric Laurent21da6472017-11-09 16:29:26 -08002470 maxNotificationFrames = frameCount / nBuffering;
2471 // If client requested a fast track but this was denied, then use the smaller maximum.
2472 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2473 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2474 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2475 maxNotificationFrames = maxNotificationFramesFastDenied;
2476 }
2477 }
2478 }
2479 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2480 if (notificationFrameCount == 0) {
2481 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2482 maxNotificationFrames, frameCount);
2483 } else {
2484 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2485 notificationFrameCount, maxNotificationFrames, frameCount);
2486 }
2487 notificationFrameCount = maxNotificationFrames;
2488 }
2489 }
2490
Glenn Kasten74935e42013-12-19 08:56:45 -08002491 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002492 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002493
Glenn Kastenc3df8382014-03-13 15:05:25 -07002494 switch (mType) {
2495
2496 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002497 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002498 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002499 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2500 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002501 sampleRate, format, channelMask, mOutput, mFormat);
2502 lStatus = BAD_VALUE;
2503 goto Exit;
2504 }
2505 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002506 break;
2507
2508 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002509 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002510 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2511 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002512 sampleRate, format, channelMask, mOutput, mFormat);
2513 lStatus = BAD_VALUE;
2514 goto Exit;
2515 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002516 break;
2517
2518 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002519 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002520 ALOGE("createTrack_l() Bad parameter: format %#x \""
2521 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002522 format, mOutput, mFormat);
2523 lStatus = BAD_VALUE;
2524 goto Exit;
2525 }
Andy Hungcd044842014-08-07 11:04:34 -07002526 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002527 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2528 lStatus = BAD_VALUE;
2529 goto Exit;
2530 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002531 break;
2532
Eric Laurent81784c32012-11-19 14:55:58 -08002533 }
2534
2535 lStatus = initCheck();
2536 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002537 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002538 goto Exit;
2539 }
2540
2541 { // scope for mLock
2542 Mutex::Autolock _l(mLock);
2543
2544 // all tracks in same audio session must share the same routing strategy otherwise
2545 // conflicts will happen when tracks are moved from one output to another by audio policy
2546 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002547 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002548 for (size_t i = 0; i < mTracks.size(); ++i) {
2549 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002550 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002551 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002552 if (sessionId == t->sessionId() && strategy != actual) {
2553 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2554 strategy, actual);
2555 lStatus = BAD_VALUE;
2556 goto Exit;
2557 }
2558 }
2559 }
2560
yucliuc9c49cd2020-07-13 16:25:21 -07002561 // Set DIRECT flag if current thread is DirectOutputThread. This can
2562 // happen when the playback is rerouted to direct output thread by
2563 // dynamic audio policy.
2564 // Do NOT report the flag changes back to client, since the client
2565 // doesn't explicitly request a direct flag.
2566 audio_output_flags_t trackFlags = *flags;
2567 if (mType == DIRECT) {
2568 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2569 }
2570
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002571 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002572 channelMask, frameCount,
2573 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002574 sessionId, creatorPid, attributionSource, trackFlags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002575 TrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
2576 speed, isSpatialized);
Glenn Kasten03003332013-08-06 15:40:54 -07002577
Glenn Kasten03003332013-08-06 15:40:54 -07002578 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2579 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002580 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002581 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002582 goto Exit;
2583 }
2584 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002585 {
2586 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2587 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002588 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002589 }
2590 }
Eric Laurent81784c32012-11-19 14:55:58 -08002591
2592 sp<EffectChain> chain = getEffectChain_l(sessionId);
2593 if (chain != 0) {
2594 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2595 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002596 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002597 chain->incTrackCnt();
2598 }
2599
Eric Laurent05067782016-06-01 18:27:28 -07002600 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002601 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2602 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2603 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002604 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002605 }
2606 }
2607
2608 lStatus = NO_ERROR;
2609
2610Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002611 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002612 return track;
2613}
2614
Andy Hung1bc088a2018-02-09 15:57:31 -08002615template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002616ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2617{
Andy Hungc0691382018-09-12 18:01:57 -07002618 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002619 const ssize_t index = mTracks.remove(track);
2620 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002621 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002622 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002623 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002624 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002625 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002626 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002627 }
2628 return index;
2629}
2630
Eric Laurent81784c32012-11-19 14:55:58 -08002631uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2632{
2633 return latency;
2634}
2635
2636uint32_t AudioFlinger::PlaybackThread::latency() const
2637{
2638 Mutex::Autolock _l(mLock);
2639 return latency_l();
2640}
2641uint32_t AudioFlinger::PlaybackThread::latency_l() const
2642{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002643 uint32_t latency;
2644 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2645 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002646 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002647 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002648}
2649
2650void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2651{
2652 Mutex::Autolock _l(mLock);
2653 // Don't apply master volume in SW if our HAL can do it for us.
2654 if (mOutput && mOutput->audioHwDev &&
2655 mOutput->audioHwDev->canSetMasterVolume()) {
2656 mMasterVolume = 1.0;
2657 } else {
2658 mMasterVolume = value;
2659 }
2660}
2661
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002662void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2663{
2664 mMasterBalance.store(balance);
2665}
2666
Eric Laurent81784c32012-11-19 14:55:58 -08002667void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2668{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002669 if (isDuplicating()) {
2670 return;
2671 }
Eric Laurent81784c32012-11-19 14:55:58 -08002672 Mutex::Autolock _l(mLock);
2673 // Don't apply master mute in SW if our HAL can do it for us.
2674 if (mOutput && mOutput->audioHwDev &&
2675 mOutput->audioHwDev->canSetMasterMute()) {
2676 mMasterMute = false;
2677 } else {
2678 mMasterMute = muted;
2679 }
2680}
2681
2682void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2683{
2684 Mutex::Autolock _l(mLock);
2685 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002686 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002687}
2688
2689void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2690{
2691 Mutex::Autolock _l(mLock);
2692 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002693 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002694}
2695
2696float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2697{
2698 Mutex::Autolock _l(mLock);
2699 return mStreamTypes[stream].volume;
2700}
2701
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002702void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2703{
2704 mOutput->stream->setVolume(left, right);
2705}
2706
Eric Laurent81784c32012-11-19 14:55:58 -08002707// addTrack_l() must be called with ThreadBase::mLock held
2708status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2709{
2710 status_t status = ALREADY_EXISTS;
2711
Eric Laurent81784c32012-11-19 14:55:58 -08002712 if (mActiveTracks.indexOf(track) < 0) {
2713 // the track is newly added, make sure it fills up all its
2714 // buffers before playing. This is to ensure the client will
2715 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002716 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002717 TrackBase::track_state state = track->mState;
2718 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002719 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002720 mLock.lock();
2721 // abort track was stopped/paused while we released the lock
2722 if (state != track->mState) {
2723 if (status == NO_ERROR) {
2724 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002725 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002726 mLock.lock();
2727 }
2728 return INVALID_OPERATION;
2729 }
2730 // abort if start is rejected by audio policy manager
2731 if (status != NO_ERROR) {
2732 return PERMISSION_DENIED;
2733 }
2734#ifdef ADD_BATTERY_DATA
2735 // to track the speaker usage
2736 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2737#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002738 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002739 }
2740
Eric Laurent51716182016-02-29 18:00:56 -08002741 // set retry count for buffer fill
2742 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002743 if (track->isStopping_1()) {
2744 track->mRetryCount = kMaxTrackStopRetriesOffload;
2745 } else {
2746 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2747 }
2748 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002749 } else {
2750 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002751 track->mFillingUpStatus =
2752 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002753 }
2754
jiabineb3bda02020-06-30 14:07:03 -07002755 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2756 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2757 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2758 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002759 // Unlock due to VibratorService will lock for this call and will
2760 // call Tracks.mute/unmute which also require thread's lock.
2761 mLock.unlock();
2762 const int intensity = AudioFlinger::onExternalVibrationStart(
2763 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002764 std::optional<media::AudioVibratorInfo> vibratorInfo;
2765 {
2766 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2767 // used to play this track.
2768 Mutex::Autolock _l(mAudioFlinger->mLock);
2769 vibratorInfo = std::move(mAudioFlinger->getDefaultVibratorInfo_l());
2770 }
jiabin57303cc2018-12-18 15:45:57 -08002771 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002772 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
Lais Andradebc3f37a2021-07-02 00:13:19 +01002773 if (vibratorInfo) {
2774 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2775 }
2776
jiabin57303cc2018-12-18 15:45:57 -08002777 // Haptic playback should be enabled by vibrator service.
2778 if (track->getHapticPlaybackEnabled()) {
2779 // Disable haptic playback of all active track to ensure only
2780 // one track playing haptic if current track should play haptic.
2781 for (const auto &t : mActiveTracks) {
2782 t->setHapticPlaybackEnabled(false);
2783 }
jiabin245cdd92018-12-07 17:55:15 -08002784 }
jiabine70bc7f2020-06-30 22:07:55 -07002785
2786 // Set haptic intensity for effect
2787 if (chain != nullptr) {
2788 chain->setHapticIntensity_l(track->id(), intensity);
2789 }
jiabin245cdd92018-12-07 17:55:15 -08002790 }
2791
Eric Laurent81784c32012-11-19 14:55:58 -08002792 track->mResetDone = false;
Andy Hung59de4262021-06-14 10:53:54 -07002793 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002794 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002795 if (chain != 0) {
2796 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2797 track->sessionId());
2798 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002799 }
2800
Andy Hungc2b11cb2020-04-22 09:04:01 -07002801 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002802 status = NO_ERROR;
2803 }
2804
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002805 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002806 return status;
2807}
2808
Eric Laurentbfb1b832013-01-07 09:53:42 -08002809bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002810{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002811 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002812 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002813 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2814 track->mState = TrackBase::STOPPED;
2815 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002816 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002817 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002818 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002819 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002820
2821 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002822}
2823
2824void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2825{
2826 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002827
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002828 String8 result;
2829 track->appendDump(result, false /* active */);
2830 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002831
Eric Laurent81784c32012-11-19 14:55:58 -08002832 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002833 {
2834 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2835 mAudioTrackCallbacks.erase(track);
2836 }
Eric Laurent81784c32012-11-19 14:55:58 -08002837 if (track->isFastTrack()) {
2838 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002839 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002840 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2841 mFastTrackAvailMask |= 1 << index;
2842 // redundant as track is about to be destroyed, for dumpsys only
2843 track->mFastIndex = -1;
2844 }
2845 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2846 if (chain != 0) {
2847 chain->decTrackCnt();
2848 }
2849}
2850
2851String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2852{
Eric Laurent81784c32012-11-19 14:55:58 -08002853 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002854 String8 out_s8;
2855 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2856 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002857 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002858 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002859}
2860
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002861status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2862 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002863 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002864 return NO_INIT;
2865 }
2866 return mOutput->stream->selectPresentation(presentationId, programId);
2867}
2868
Mikhail Naganov88536df2021-07-26 17:30:29 -07002869void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002870 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002871 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07002872 sp<AudioIoDescriptor> desc;
2873 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002874 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002875 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002876 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002877 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002878 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
2879 mSampleRate, mFormat, mChannelMask,
2880 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
2881 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08002882 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002883 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002884 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07002885 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002886 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002887 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002888 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08002889 break;
2890 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002891 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002892}
2893
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002894void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002895{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002896 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002897}
2898
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002899void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002900{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002901 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002902}
2903
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002904void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002905{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002906 mCallbackThread->setAsyncError();
2907}
2908
jiabinf6eb4c32020-02-25 14:06:25 -08002909void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2910 const std::basic_string<uint8_t>& metadataBs)
2911{
Kuowei Li9e2f6162022-11-23 16:25:26 +08002912 wp<AudioFlinger::PlaybackThread> weakPointerThis = this;
2913 std::thread([this, metadataBs, weakPointerThis]() {
2914 sp<AudioFlinger::PlaybackThread> playbackThread = weakPointerThis.promote();
2915 if (playbackThread == nullptr) {
2916 ALOGW("PlaybackThread was destroyed, skip codec format change event");
2917 return;
2918 }
2919
jiabinf6eb4c32020-02-25 14:06:25 -08002920 audio_utils::metadata::Data metadata =
2921 audio_utils::metadata::dataFromByteString(metadataBs);
2922 if (metadata.empty()) {
2923 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2924 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2925 (int)metadataBs.size());
2926 return;
2927 }
2928
2929 audio_utils::metadata::ByteString metaDataStr =
2930 audio_utils::metadata::byteStringFromData(metadata);
2931 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2932 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002933 for (const auto& callbackPair : mAudioTrackCallbacks) {
2934 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002935 }
2936 }).detach();
2937}
2938
Eric Laurent3b4529e2013-09-05 18:09:19 -07002939void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002940{
2941 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002942 // reject out of sequence requests
2943 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2944 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002945 mWaitWorkCV.signal();
2946 }
2947}
2948
Eric Laurent3b4529e2013-09-05 18:09:19 -07002949void AudioFlinger::PlaybackThread::resetDraining(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 ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002954 // Register discontinuity when HW drain is completed because that can cause
2955 // the timestamp frame position to reset to 0 for direct and offload threads.
2956 // (Out of sequence requests are ignored, since the discontinuity would be handled
2957 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002958 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002959 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002960 mWaitWorkCV.signal();
2961 }
2962}
2963
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002964void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002965{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002966 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002967 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2968 mSampleRate = audioConfig.sample_rate;
2969 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002970 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002971 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002972 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002973 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07002974 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2975 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002976 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02002977
2978 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
2979 mMixerChannelMask = mChannelMask;
2980 }
2981
Andy Hunge5412692014-05-16 11:25:07 -07002982 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002983 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002984
Eric Laurentf1f22e72021-07-13 14:04:14 +02002985 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
2986
Phil Burkca5e6142015-07-14 09:42:29 -07002987 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002988 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002989 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002990 // Get format from the shim, which will be different than the HAL format
2991 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002992 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002993 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002994 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002995 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002996 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07002997 LOG_FATAL("HAL format %#x not supported for mixed output",
2998 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002999 }
Phil Burk062e67a2015-02-11 13:40:50 -08003000 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003001 result = mOutput->stream->getBufferSize(&mBufferSize);
3002 LOG_ALWAYS_FATAL_IF(result != OK,
3003 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003004 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003005 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003006 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003007 mFrameCount);
3008 }
3009
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003010 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
3011 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003012 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07003013 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003014 }
3015 }
3016
Eric Laurentd1f69b02014-12-15 14:33:13 -08003017 mHwSupportsPause = false;
3018 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003019 bool supportsPause = false, supportsResume = false;
3020 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3021 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003022 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003023 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003024 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003025 } else if (supportsResume) {
3026 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003027 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003028 }
3029 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003030 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3031 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3032 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003033
Andy Hungfbfc3952015-01-15 13:33:51 -08003034 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3035 // For best precision, we use float instead of the associated output
3036 // device format (typically PCM 16 bit).
3037
3038 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3039 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3040 mBufferSize = mFrameSize * mFrameCount;
3041
3042 // TODO: We currently use the associated output device channel mask and sample rate.
3043 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3044 // (if a valid mask) to avoid premature downmix.
3045 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3046 // instead of the output device sample rate to avoid loss of high frequency information.
3047 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3048 }
3049
Andy Hung09a50072014-02-27 14:30:47 -08003050 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003051 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003052 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003053 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3054 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003055 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3056 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003057
Eric Laurent81784c32012-11-19 14:55:58 -08003058 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3059 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3060 maxNormalFrameCount = maxNormalFrameCount & ~15;
3061 if (maxNormalFrameCount < minNormalFrameCount) {
3062 maxNormalFrameCount = minNormalFrameCount;
3063 }
3064 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3065 if (multiplier <= 1.0) {
3066 multiplier = 1.0;
3067 } else if (multiplier <= 2.0) {
3068 if (2 * mFrameCount <= maxNormalFrameCount) {
3069 multiplier = 2.0;
3070 } else {
3071 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3072 }
3073 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003074 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003075 }
3076 }
3077 mNormalFrameCount = multiplier * mFrameCount;
3078 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003079 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003080 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3081 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003082 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003083 mNormalFrameCount);
3084
Andy Hung08fb1742015-05-31 23:22:10 -07003085 // Check if we want to throttle the processing to no more than 2x normal rate
3086 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003087 mThreadThrottleTimeMs = 0;
3088 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003089 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3090
Andy Hung010a1a12014-03-13 13:57:33 -07003091 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3092 // Originally this was int16_t[] array, need to remove legacy implications.
3093 free(mSinkBuffer);
3094 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003095
Andy Hung5b10a202014-03-13 13:59:29 -07003096 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3097 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3098 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003099 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003100
Andy Hung69aed5f2014-02-25 17:24:40 -08003101 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3102 // drives the output.
3103 free(mMixerBuffer);
3104 mMixerBuffer = NULL;
3105 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003106 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003107 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003108 * audio_bytes_per_sample(mMixerBufferFormat);
3109 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3110 }
Andy Hung98ef9782014-03-04 14:46:50 -08003111 free(mEffectBuffer);
3112 mEffectBuffer = NULL;
3113 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07003114 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003115 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003116 * audio_bytes_per_sample(mEffectBufferFormat);
3117 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3118 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003119
Eric Laurentb62d0362021-10-26 17:40:18 +02003120 if (mType == SPATIALIZER) {
3121 free(mPostSpatializerBuffer);
3122 mPostSpatializerBuffer = nullptr;
3123 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3124 * audio_bytes_per_sample(mEffectBufferFormat);
3125 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3126 }
3127
Mikhail Naganov55773032020-10-01 15:08:13 -07003128 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3129 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003130 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3131 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003132 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003133
Eric Laurent81784c32012-11-19 14:55:58 -08003134 // force reconfiguration of effect chains and engines to take new buffer size and audio
3135 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003136 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003137 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3138 // matter.
3139 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
3140 Vector< sp<EffectChain> > effectChains = mEffectChains;
3141 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07003142 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
3143 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003144 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003145
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003146 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003147 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003148 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3149 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3150 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3151 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3152 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3153 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3154 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3155 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3156 (int32_t)mHapticChannelMask)
3157 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3158 (int32_t)mHapticChannelCount)
3159 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3160 formatToString(mHALFormat).c_str())
3161 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3162 (int32_t)mFrameCount) // sic - added HAL
3163 ;
3164 uint32_t latencyMs;
3165 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3166 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3167 }
3168 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003169}
3170
Kevin Rocard069c2712018-03-29 19:09:14 -07003171void AudioFlinger::PlaybackThread::updateMetadata_l()
3172{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003173 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Kevin Rocard12381092018-04-11 09:19:59 -07003174 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003175 }
3176 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003177 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07003178 for (const sp<Track> &track : mActiveTracks) {
3179 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003180 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003181 }
Kevin Rocard12381092018-04-11 09:19:59 -07003182 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00003183}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003184
Kevin Rocard12381092018-04-11 09:19:59 -07003185void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
3186 const StreamOutHalInterface::SourceMetadata& metadata)
3187{
3188 mOutput->stream->updateSourceMetadata(metadata);
3189};
3190
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003191status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08003192{
3193 if (halFrames == NULL || dspFrames == NULL) {
3194 return BAD_VALUE;
3195 }
3196 Mutex::Autolock _l(mLock);
3197 if (initCheck() != NO_ERROR) {
3198 return INVALID_OPERATION;
3199 }
Andy Hung818e7a32016-02-16 18:08:07 -08003200 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003201 *halFrames = framesWritten;
3202
3203 if (isSuspended()) {
3204 // return an estimation of rendered frames when the output is suspended
3205 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003206 *dspFrames = (uint32_t)
3207 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003208 return NO_ERROR;
3209 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003210 status_t status;
3211 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003212 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003213 *dspFrames = (size_t)frames;
3214 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003215 }
3216}
3217
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003218product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003219{
3220 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3221 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3222 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003223 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003224 }
3225 for (size_t i = 0; i < mTracks.size(); i++) {
3226 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003227 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003228 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003229 }
3230 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003231 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003232}
3233
3234
Phil Burk062e67a2015-02-11 13:40:50 -08003235AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003236{
3237 Mutex::Autolock _l(mLock);
3238 return mOutput;
3239}
3240
Phil Burk062e67a2015-02-11 13:40:50 -08003241AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003242{
3243 Mutex::Autolock _l(mLock);
3244 AudioStreamOut *output = mOutput;
3245 mOutput = NULL;
3246 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3247 // must push a NULL and wait for ack
3248 mOutputSink.clear();
3249 mPipeSink.clear();
3250 mNormalSink.clear();
3251 return output;
3252}
3253
3254// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003255sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003256{
3257 if (mOutput == NULL) {
3258 return NULL;
3259 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003260 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003261}
3262
3263uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3264{
3265 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3266}
3267
3268status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3269{
3270 if (!isValidSyncEvent(event)) {
3271 return BAD_VALUE;
3272 }
3273
3274 Mutex::Autolock _l(mLock);
3275
3276 for (size_t i = 0; i < mTracks.size(); ++i) {
3277 sp<Track> track = mTracks[i];
3278 if (event->triggerSession() == track->sessionId()) {
3279 (void) track->setSyncEvent(event);
3280 return NO_ERROR;
3281 }
3282 }
3283
3284 return NAME_NOT_FOUND;
3285}
3286
3287bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3288{
3289 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3290}
3291
3292void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3293 const Vector< sp<Track> >& tracksToRemove)
3294{
Andy Hungfe726a62018-09-27 15:17:25 -07003295 // Miscellaneous track cleanup when removed from the active list,
3296 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003297#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003298 for (const auto& track : tracksToRemove) {
3299 if (track->isExternalTrack()) {
3300 // to track the speaker usage
3301 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003302 }
3303 }
Andy Hungfe726a62018-09-27 15:17:25 -07003304#else
3305 (void)tracksToRemove; // suppress unused warning
3306#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003307}
3308
3309void AudioFlinger::PlaybackThread::checkSilentMode_l()
3310{
3311 if (!mMasterMute) {
3312 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003313 if (mOutDeviceTypeAddrs.empty()) {
3314 ALOGD("ro.audio.silent is ignored since no output device is set");
3315 return;
3316 }
jiabinc52b1ff2019-10-31 17:20:42 -07003317 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003318 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3319 return;
3320 }
Eric Laurent81784c32012-11-19 14:55:58 -08003321 if (property_get("ro.audio.silent", value, "0") > 0) {
3322 char *endptr;
3323 unsigned long ul = strtoul(value, &endptr, 0);
3324 if (*endptr == '\0' && ul != 0) {
3325 ALOGD("Silence is golden");
3326 // The setprop command will not allow a property to be changed after
3327 // the first time it is set, so we don't have to worry about un-muting.
3328 setMasterMute_l(true);
3329 }
3330 }
3331 }
3332}
3333
3334// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003335ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003336{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003337 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003338 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003339 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003340 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003341
3342 // If an NBAIO sink is present, use it to write the normal mixer's submix
3343 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003344
Andy Hung010a1a12014-03-13 13:57:33 -07003345 const size_t count = mBytesRemaining / mFrameSize;
3346
Simon Wilson2d590962012-11-29 15:18:50 -08003347 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003348 // update the setpoint when AudioFlinger::mScreenState changes
3349 uint32_t screenState = AudioFlinger::mScreenState;
3350 if (screenState != mScreenState) {
3351 mScreenState = screenState;
3352 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3353 if (pipe != NULL) {
3354 pipe->setAvgFrames((mScreenState & 1) ?
3355 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3356 }
3357 }
Andy Hung010a1a12014-03-13 13:57:33 -07003358 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003359 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003360 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003361 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003362#ifdef TEE_SINK
3363 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3364#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003365 } else {
3366 bytesWritten = framesWritten;
3367 }
3368 // otherwise use the HAL / AudioStreamOut directly
3369 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003370 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003371
Eric Laurentbfb1b832013-01-07 09:53:42 -08003372 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003373 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3374 mWriteAckSequence += 2;
3375 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003376 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003377 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003378 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003379 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003380 // FIXME We should have an implementation of timestamps for direct output threads.
3381 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003382 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003383 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003384
Eric Laurentbfb1b832013-01-07 09:53:42 -08003385 if (mUseAsyncWrite &&
3386 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3387 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003388 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003389 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003390 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003391 }
Eric Laurent81784c32012-11-19 14:55:58 -08003392 }
3393
Eric Laurent81784c32012-11-19 14:55:58 -08003394 mNumWrites++;
3395 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003396 if (mStandby) {
3397 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003398 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003399 mStandby = false;
3400 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003401 return bytesWritten;
3402}
3403
3404void AudioFlinger::PlaybackThread::threadLoop_drain()
3405{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003406 bool supportsDrain = false;
3407 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003408 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3409 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003410 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3411 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003412 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003413 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003414 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003415 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003416 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003417 }
3418}
3419
3420void AudioFlinger::PlaybackThread::threadLoop_exit()
3421{
Eric Laurent275e8e92014-11-30 15:14:47 -08003422 {
3423 Mutex::Autolock _l(mLock);
3424 for (size_t i = 0; i < mTracks.size(); i++) {
3425 sp<Track> track = mTracks[i];
3426 track->invalidate();
3427 }
Andy Hungdae27702016-10-31 14:01:16 -07003428 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3429 // After we exit there are no more track changes sent to BatteryNotifier
3430 // because that requires an active threadLoop.
3431 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3432 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003433 }
Eric Laurent81784c32012-11-19 14:55:58 -08003434}
3435
3436/*
3437The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003438 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003439 - mActiveSleepTimeUs from activeSleepTimeUs()
3440 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003441 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3442 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003443 - maxPeriod from frame count and sample rate (MIXER only)
3444
3445The parameters that affect these derived values are:
3446 - frame count
3447 - frame size
3448 - sample rate
3449 - device type: A2DP or not
3450 - device latency
3451 - format: PCM or not
3452 - active sleep time
3453 - idle sleep time
3454*/
3455
3456void AudioFlinger::PlaybackThread::cacheParameters_l()
3457{
Andy Hung25c2dac2014-02-27 14:56:00 -08003458 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003459 mActiveSleepTimeUs = activeSleepTimeUs();
3460 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003461
3462 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3463 // truncating audio when going to standby.
3464 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003465 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003466 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3467 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3468 }
3469 }
Eric Laurent81784c32012-11-19 14:55:58 -08003470}
3471
Eric Laurent13084622016-05-17 10:51:49 -07003472bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003473{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003474 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003475 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003476 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003477 size_t size = mTracks.size();
3478 for (size_t i = 0; i < size; i++) {
3479 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003480 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003481 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003482 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003483 }
3484 }
Eric Laurent13084622016-05-17 10:51:49 -07003485 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003486}
3487
Haynes Mathew George05317d22016-05-03 16:34:26 -07003488void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3489{
3490 Mutex::Autolock _l(mLock);
3491 invalidateTracks_l(streamType);
3492}
3493
jiabinf042b9b2021-05-07 23:46:28 +00003494// getTrackById_l must be called with holding thread lock
3495AudioFlinger::PlaybackThread::Track* AudioFlinger::PlaybackThread::getTrackById_l(
3496 audio_port_handle_t trackPortId) {
3497 for (size_t i = 0; i < mTracks.size(); i++) {
3498 if (mTracks[i]->portId() == trackPortId) {
3499 return mTracks[i].get();
3500 }
3501 }
3502 return nullptr;
3503}
3504
Eric Laurent81784c32012-11-19 14:55:58 -08003505status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3506{
Glenn Kastend848eb42016-03-08 13:42:11 -08003507 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003508 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003509 effect_buffer_t *buffer = nullptr; // only used for non global sessions
3510
Andy Hungd3639922022-04-28 18:00:49 -07003511 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003512 if (!audio_is_global_session(session)) {
3513 // player sessions on a spatializer output will use a dedicated input buffer and
3514 // will either output multi channel to mEffectBuffer if the track is spatilaized
3515 // or stereo to mPostSpatializerBuffer if not spatialized.
3516 uint32_t channelMask;
3517 bool isSessionSpatialized =
3518 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3519 if (isSessionSpatialized) {
3520 channelMask = mMixerChannelMask;
3521 } else {
3522 channelMask = mChannelMask;
3523 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003524 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003525 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003526 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003527 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003528 &halInBuffer);
3529 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003530
3531 result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3532 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3533 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3534 &halOutBuffer);
3535 if (result != OK) return result;
3536
rago94a1ee82017-07-21 15:11:02 -07003537#ifdef FLOAT_EFFECT_CHAIN
3538 buffer = halInBuffer->audioBuffer()->f32;
3539#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003540 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003541#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003542 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3543 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003544 } else {
3545 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3546 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3547 // mPostSpatializerBuffer as output buffer
3548 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
3549 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3550 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3551 if (result != OK) return result;
3552 result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3553 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3554 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003555
Eric Laurentb62d0362021-10-26 17:40:18 +02003556 if (session == AUDIO_SESSION_DEVICE) {
3557 halInBuffer = halOutBuffer;
3558 }
3559 }
3560 } else {
3561 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3562 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3563 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3564 &halInBuffer);
3565 if (result != OK) return result;
3566 halOutBuffer = halInBuffer;
3567 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3568 if (!audio_is_global_session(session)) {
3569 buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
3570 // Only one effect chain can be present in direct output thread and it uses
3571 // the sink buffer as input
3572 if (mType != DIRECT) {
3573 size_t numSamples = mNormalFrameCount
3574 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3575 + mHapticChannelCount);
3576 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
3577 numSamples * sizeof(effect_buffer_t),
3578 &halInBuffer);
3579 if (result != OK) return result;
3580#ifdef FLOAT_EFFECT_CHAIN
3581 buffer = halInBuffer->audioBuffer()->f32;
3582#else
3583 buffer = halInBuffer->audioBuffer()->s16;
3584#endif
3585 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3586 buffer, session);
3587 }
3588 }
3589 }
3590
3591 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003592 // Attach all tracks with same session ID to this chain.
3593 for (size_t i = 0; i < mTracks.size(); ++i) {
3594 sp<Track> track = mTracks[i];
3595 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003596 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3597 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003598 track->setMainBuffer(buffer);
3599 chain->incTrackCnt();
3600 }
3601 }
3602
3603 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003604 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003605 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003606 ALOGV("addEffectChain_l() activating track %p on session %d",
3607 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003608 chain->incActiveTrackCnt();
3609 }
3610 }
3611 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003612
Eric Laurentaaa44472014-09-12 17:41:50 -07003613 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003614 chain->setInBuffer(halInBuffer);
3615 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003616 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3617 // chains list in order to be processed last as it contains output device effects.
3618 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3619 // processing effects specific to an output stream before effects applied to all streams
3620 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003621 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3622 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003623 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003624 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003625 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003626 // Effect chain for other sessions are inserted at beginning of effect
3627 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003628 // sessions is not important.
3629 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003630 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3631 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003632 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003633 size_t size = mEffectChains.size();
3634 size_t i = 0;
3635 for (i = 0; i < size; i++) {
3636 if (mEffectChains[i]->sessionId() < session) {
3637 break;
3638 }
3639 }
3640 mEffectChains.insertAt(chain, i);
3641 checkSuspendOnAddEffectChain_l(chain);
3642
3643 return NO_ERROR;
3644}
3645
3646size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3647{
Glenn Kastend848eb42016-03-08 13:42:11 -08003648 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003649
3650 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3651
3652 for (size_t i = 0; i < mEffectChains.size(); i++) {
3653 if (chain == mEffectChains[i]) {
3654 mEffectChains.removeAt(i);
3655 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003656 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003657 if (session == track->sessionId()) {
3658 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3659 chain.get(), session);
3660 chain->decActiveTrackCnt();
3661 }
3662 }
3663
3664 // detach all tracks with same session ID from this chain
3665 for (size_t i = 0; i < mTracks.size(); ++i) {
3666 sp<Track> track = mTracks[i];
3667 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003668 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003669 chain->decTrackCnt();
3670 }
3671 }
3672 break;
3673 }
3674 }
3675 return mEffectChains.size();
3676}
3677
3678status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003679 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003680{
3681 Mutex::Autolock _l(mLock);
3682 return attachAuxEffect_l(track, EffectId);
3683}
3684
3685status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003686 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003687{
3688 status_t status = NO_ERROR;
3689
3690 if (EffectId == 0) {
3691 track->setAuxBuffer(0, NULL);
3692 } else {
3693 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3694 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3695 if (effect != 0) {
3696 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3697 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3698 } else {
3699 status = INVALID_OPERATION;
3700 }
3701 } else {
3702 status = BAD_VALUE;
3703 }
3704 }
3705 return status;
3706}
3707
3708void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3709{
3710 for (size_t i = 0; i < mTracks.size(); ++i) {
3711 sp<Track> track = mTracks[i];
3712 if (track->auxEffectId() == effectId) {
3713 attachAuxEffect_l(track, 0);
3714 }
3715 }
3716}
3717
3718bool AudioFlinger::PlaybackThread::threadLoop()
3719{
Glenn Kasten388d5712017-04-07 14:38:41 -07003720 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003721
Eric Laurent81784c32012-11-19 14:55:58 -08003722 Vector< sp<Track> > tracksToRemove;
3723
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003724 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003725 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003726
3727 // MIXER
3728 nsecs_t lastWarning = 0;
3729
3730 // DUPLICATING
3731 // FIXME could this be made local to while loop?
3732 writeFrames = 0;
3733
3734 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003735 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003736
Andy Hungd3639922022-04-28 18:00:49 -07003737 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003738 sleepTimeShift = 0;
3739 }
3740
3741 CpuStats cpuStats;
3742 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3743
3744 acquireWakeLock();
3745
Glenn Kasteneef598c2017-04-03 14:41:13 -07003746 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3747 // thread associated with this PlaybackThread.
3748 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3749 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003750 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3751 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003752 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003753 const char *logString = NULL;
3754
rago1bb90822017-05-02 18:31:48 -07003755 // Estimated time for next buffer to be written to hal. This is used only on
3756 // suspended mode (for now) to help schedule the wait time until next iteration.
3757 nsecs_t timeLoopNextNs = 0;
3758
Eric Laurent664539d2013-09-23 18:24:31 -07003759 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003760
Andy Hung2dbffc22018-08-08 18:50:41 -07003761 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003762
Eric Laurentb3f315a2021-07-13 15:09:05 +02003763 sendCheckOutputStageEffectsEvent();
3764
Andy Hung446f4df2019-02-21 12:26:41 -08003765 // loopCount is used for statistics and diagnostics.
3766 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003767 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003768 // Log merge requests are performed during AudioFlinger binder transactions, but
3769 // that does not cover audio playback. It's requested here for that reason.
3770 mAudioFlinger->requestLogMerge();
3771
Eric Laurent81784c32012-11-19 14:55:58 -08003772 cpuStats.sample(myName);
3773
3774 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003775 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003776 bool isHapticSessionSpatialized = false;
Andy Hungc1646382019-04-30 16:12:10 -07003777 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003778
Andy Hung2dbffc22018-08-08 18:50:41 -07003779 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3780 //
jiabinc52b1ff2019-10-31 17:20:42 -07003781 // Note: we access outDeviceTypes() outside of mLock.
3782 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003783 // Here, we try for the AF lock, but do not block on it as the latency
3784 // is more informational.
3785 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3786 std::vector<PatchPanel::SoftwarePatch> swPatches;
3787 double latencyMs;
3788 status_t status = INVALID_OPERATION;
3789 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3790 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3791 && swPatches.size() > 0) {
3792 status = swPatches[0].getLatencyMs_l(&latencyMs);
3793 downstreamPatchHandle = swPatches[0].getPatchHandle();
3794 }
3795 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003796 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003797 lastDownstreamPatchHandle = downstreamPatchHandle;
3798 }
3799 if (status == OK) {
3800 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003801 // latency of 5 seconds).
3802 const double minLatency = 0., maxLatency = 5000.;
3803 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003804 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003805 } else {
3806 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003807 if (latencyMs < minLatency) latencyMs = minLatency;
3808 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003809 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003810 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003811 }
3812 mAudioFlinger->mLock.unlock();
3813 }
3814 } else {
3815 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3816 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003817 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003818 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3819 }
3820 }
3821
Eric Laurentb3f315a2021-07-13 15:09:05 +02003822 if (mCheckOutputStageEffects.exchange(false)) {
3823 checkOutputStageEffects();
3824 }
3825
Eric Laurent81784c32012-11-19 14:55:58 -08003826 { // scope for mLock
3827
3828 Mutex::Autolock _l(mLock);
3829
Eric Laurent021cf962014-05-13 10:18:14 -07003830 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003831 if (mCheckOutputStageEffects.load()) {
3832 continue;
3833 }
Eric Laurent10351942014-05-08 18:49:52 -07003834
Glenn Kasteneef598c2017-04-03 14:41:13 -07003835 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003836 if (logString != NULL) {
3837 mNBLogWriter->logTimestamp();
3838 mNBLogWriter->log(logString);
3839 logString = NULL;
3840 }
3841
Dean Wheatley12473e92021-03-18 23:00:55 +11003842 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003843
Eric Laurent81784c32012-11-19 14:55:58 -08003844 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003845 if (mSignalPending) {
3846 // A signal was raised while we were unlocked
3847 mSignalPending = false;
3848 } else if (waitingAsyncCallback_l()) {
3849 if (exitPending()) {
3850 break;
3851 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003852 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003853 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003854 releaseWakeLock_l();
3855 released = true;
3856 }
Andy Hung10cbff12017-02-21 17:30:14 -08003857
3858 const int64_t waitNs = computeWaitTimeNs_l();
3859 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3860 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3861 if (status == TIMED_OUT) {
3862 mSignalPending = true; // if timeout recheck everything
3863 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003864 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003865 if (released) {
3866 acquireWakeLock_l();
3867 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003868 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3869 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003870
3871 continue;
3872 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003873 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003874 isSuspended()) {
3875 // put audio hardware into standby after short delay
3876 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003877
3878 threadLoop_standby();
3879
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003880 // This is where we go into standby
3881 if (!mStandby) {
3882 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003883 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003884 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07003885 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003886 }
Andy Hungd0979812019-02-21 15:51:44 -08003887 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003888 }
3889
Eric Tan39ec8d62018-07-24 09:49:29 -07003890 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003891 // we're about to wait, flush the binder command buffer
3892 IPCThreadState::self()->flushCommands();
3893
3894 clearOutputTracks();
3895
3896 if (exitPending()) {
3897 break;
3898 }
3899
3900 releaseWakeLock_l();
3901 // wait until we have something to do...
3902 ALOGV("%s going to sleep", myName.string());
3903 mWaitWorkCV.wait(mLock);
3904 ALOGV("%s waking up", myName.string());
3905 acquireWakeLock_l();
3906
3907 mMixerStatus = MIXER_IDLE;
3908 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3909 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003910 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003911 checkSilentMode_l();
3912
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003913 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3914 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07003915 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003916 sleepTimeShift = 0;
3917 }
3918
3919 continue;
3920 }
3921 }
Eric Laurent81784c32012-11-19 14:55:58 -08003922 // mMixerStatusIgnoringFastTracks is also updated internally
3923 mMixerStatus = prepareTracks_l(&tracksToRemove);
3924
Andy Hungdae27702016-10-31 14:01:16 -07003925 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003926
Kevin Rocard069c2712018-03-29 19:09:14 -07003927 updateMetadata_l();
3928
Eric Laurent81784c32012-11-19 14:55:58 -08003929 // prevent any changes in effect chain list and in each effect chain
3930 // during mixing and effect process as the audio buffers could be deleted
3931 // or modified if an effect is created or deleted
3932 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003933
3934 // Determine which session to pick up haptic data.
3935 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003936 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003937 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02003938 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07003939 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003940 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02003941 if (effectChain != nullptr
3942 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07003943 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02003944 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02003945 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07003946 break;
3947 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003948 if (activeHapticSessionId == AUDIO_SESSION_NONE
3949 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07003950 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02003951 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02003952 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07003953 }
3954 }
3955 }
3956
Andy Hungc1646382019-04-30 16:12:10 -07003957 // Acquire a local copy of active tracks with lock (release w/o lock).
3958 //
3959 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3960 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3961 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3962 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent6f9534f2022-05-03 18:15:04 +02003963
3964 setHalLatencyMode_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003965 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003966
Eric Laurentbfb1b832013-01-07 09:53:42 -08003967 if (mBytesRemaining == 0) {
3968 mCurrentWriteLength = 0;
3969 if (mMixerStatus == MIXER_TRACKS_READY) {
3970 // threadLoop_mix() sets mCurrentWriteLength
3971 threadLoop_mix();
3972 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3973 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003974 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003975 // must be written to HAL
3976 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003977 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003978 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003979
3980 // Tally underrun frames as we are inserting 0s here.
3981 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003982 if (track->mFillingUpStatus == Track::FS_ACTIVE
3983 && !track->isStopped()
3984 && !track->isPaused()
3985 && !track->isTerminated()) {
3986 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3987 __func__, track->id(), track->getTrackStateAsString(),
3988 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003989 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3990 }
3991 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003992 }
3993 }
Andy Hung98ef9782014-03-04 14:46:50 -08003994 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003995 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003996 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3997 // or mSinkBuffer (if there are no effects).
3998 //
3999 // This is done pre-effects computation; if effects change to
4000 // support higher precision, this needs to move.
4001 //
4002 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004003 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004004 uint32_t mixerChannelCount = mEffectBufferValid ?
4005 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
Andy Hung98ef9782014-03-04 14:46:50 -08004006 if (mMixerBufferValid) {
4007 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4008 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4009
David Li88ee0902022-06-22 10:01:21 +08004010 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4011 // do these processes after effects are applied.
4012 if (!mEffectBufferValid) {
4013 // mono blend occurs for mixer threads only (not direct or offloaded)
4014 // and is handled here if we're going directly to the sink.
4015 if (requireMonoBlend()) {
4016 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4017 mNormalFrameCount, true /*limit*/);
4018 }
Andy Hung2ddee192015-12-18 17:34:44 -08004019
David Li88ee0902022-06-22 10:01:21 +08004020 if (!hasFastMixer()) {
4021 // Balance must take effect after mono conversion.
4022 // We do it here if there is no FastMixer.
4023 // mBalance detects zero balance within the class for speed
4024 // (not needed here).
4025 mBalance.setBalance(mMasterBalance.load());
4026 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4027 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004028 }
4029
Andy Hung98ef9782014-03-04 14:46:50 -08004030 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004031 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004032
4033 // If we're going directly to the sink and there are haptic channels,
4034 // we should adjust channels as the sample data is partially interleaved
4035 // in this case.
4036 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4037 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4038 mChannelCount + mHapticChannelCount,
4039 audio_bytes_per_sample(format),
4040 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4041 }
Andy Hung98ef9782014-03-04 14:46:50 -08004042 }
4043
Eric Laurentbfb1b832013-01-07 09:53:42 -08004044 mBytesRemaining = mCurrentWriteLength;
4045 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004046 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4047 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4048 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4049 mBytesWritten += mBytesRemaining;
4050 mFramesWritten += framesRemaining;
4051 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004052 mBytesRemaining = 0;
4053 }
Eric Laurent81784c32012-11-19 14:55:58 -08004054
Eric Laurentbfb1b832013-01-07 09:53:42 -08004055 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004056 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004057 for (size_t i = 0; i < effectChains.size(); i ++) {
4058 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004059 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004060 if (activeHapticSessionId != AUDIO_SESSION_NONE
4061 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004062 // Haptic data is active in this case, copy it directly from
4063 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004064 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4065 audio_channel_count_from_out_mask(mMixerChannelMask) :
4066 mChannelCount;
4067 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4068 hapticSessionChannelCount = mChannelCount;
4069 }
4070
jiabin47affe52019-04-04 18:02:07 -07004071 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004072 * audio_bytes_per_frame(hapticSessionChannelCount,
4073 EFFECT_BUFFER_FORMAT);
jiabin47affe52019-04-04 18:02:07 -07004074 memcpy_by_audio_format(
4075 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
4076 EFFECT_BUFFER_FORMAT,
4077 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
4078 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
4079 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004080 }
Eric Laurent81784c32012-11-19 14:55:58 -08004081 }
4082 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004083 // Process effect chains for offloaded thread even if no audio
4084 // was read from audio track: process only updates effect state
4085 // and thus does have to be synchronized with audio writes but may have
4086 // to be called while waiting for async write callback
4087 if (mType == OFFLOAD) {
4088 for (size_t i = 0; i < effectChains.size(); i ++) {
4089 effectChains[i]->process_l();
4090 }
4091 }
Eric Laurent81784c32012-11-19 14:55:58 -08004092
Andy Hung98ef9782014-03-04 14:46:50 -08004093 // Only if the Effects buffer is enabled and there is data in the
4094 // Effects buffer (buffer valid), we need to
4095 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004096 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08004097 if (mEffectBufferValid) {
4098 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004099 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004100 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004101 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004102 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004103 }
4104
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004105 if (!hasFastMixer()) {
4106 // Balance must take effect after mono conversion.
4107 // We do it here if there is no FastMixer.
4108 // mBalance detects zero balance within the class for speed (not needed here).
4109 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004110 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004111 }
4112
Eric Laurentb62d0362021-10-26 17:40:18 +02004113 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4114 // mPostSpatializerBuffer if the haptics track is spatialized.
4115 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4116 // For other thread types, the haptics channels are already in mEffectBuffer.
4117 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4118 const size_t srcBufferSize = mNormalFrameCount *
4119 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4120 mEffectBufferFormat);
4121 const size_t dstBufferSize = mNormalFrameCount
4122 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4123
4124 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4125 mEffectBufferFormat,
4126 (uint8_t*)mEffectBuffer + srcBufferSize,
4127 mEffectBufferFormat,
4128 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004129 }
Atneya Nair68436cf2022-09-19 17:51:37 -07004130 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4131 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4132 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4133 // Clamp PCM float values more than this distance from 0 to insulate
4134 // a HAL which doesn't handle NaN correctly.
4135 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4136 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4137 static_cast<const float*>(effectBuffer),
4138 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4139 } else {
4140 memcpy_by_audio_format(mSinkBuffer, mFormat,
4141 effectBuffer, mEffectBufferFormat, framesToCopy);
4142 }
jiabin245cdd92018-12-07 17:55:15 -08004143 // The sample data is partially interleaved when haptic channels exist,
4144 // we need to adjust channels here.
4145 if (mHapticChannelCount > 0) {
4146 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4147 mChannelCount + mHapticChannelCount,
4148 audio_bytes_per_sample(mFormat),
4149 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4150 }
Andy Hung98ef9782014-03-04 14:46:50 -08004151 }
4152
Eric Laurent81784c32012-11-19 14:55:58 -08004153 // enable changes in effect chain
4154 unlockEffectChains(effectChains);
4155
Eric Laurentbfb1b832013-01-07 09:53:42 -08004156 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004157 // mSleepTimeUs == 0 means we must write to audio hardware
4158 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004159 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004160 // writePeriodNs is updated >= 0 when ret > 0.
4161 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004162 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004163 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004164 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004165 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004166 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004167 if (ret < 0) {
4168 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004169 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004170 mBytesWritten += ret;
4171 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004172 const int64_t frames = ret / mFrameSize;
4173 mFramesWritten += frames;
4174
4175 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4176 // process information relating to write time.
4177 if (audio_has_proportional_frames(mFormat)) {
4178 // we are in a continuous mixing cycle
4179 if (mMixerStatus == MIXER_TRACKS_READY &&
4180 loopCount == lastLoopCountWritten + 1) {
4181
4182 const double jitterMs =
4183 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4184 {frames, writePeriodNs},
4185 {0, 0} /* lastTimestamp */, mSampleRate);
4186 const double processMs =
4187 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4188
4189 Mutex::Autolock _l(mLock);
4190 mIoJitterMs.add(jitterMs);
4191 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004192
4193 if (mPipeSink.get() != nullptr) {
4194 // Using the Monopipe availableToWrite, we estimate the current
4195 // buffer size.
4196 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4197 const ssize_t
4198 availableToWrite = mPipeSink->availableToWrite();
4199 const size_t pipeFrames = monoPipe->maxFrames();
4200 const size_t
4201 remainingFrames = pipeFrames - max(availableToWrite, 0);
4202 mMonopipePipeDepthStats.add(remainingFrames);
4203 }
Andy Hung446f4df2019-02-21 12:26:41 -08004204 }
4205
4206 // write blocked detection
4207 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004208 if ((mType == MIXER || mType == SPATIALIZER)
4209 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004210 mNumDelayedWrites++;
4211 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4212 ATRACE_NAME("underrun");
4213 ALOGW("write blocked for %lld msecs, "
4214 "%d delayed writes, thread %d",
4215 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4216 mNumDelayedWrites, mId);
4217 lastWarning = lastIoEndNs;
4218 }
4219 }
4220 }
4221 // update timing info.
4222 mLastIoBeginNs = lastIoBeginNs;
4223 mLastIoEndNs = lastIoEndNs;
4224 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004225 }
4226 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4227 (mMixerStatus == MIXER_DRAIN_ALL)) {
4228 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004229 }
Andy Hungd3639922022-04-28 18:00:49 -07004230 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004231
4232 if (mThreadThrottle
4233 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004234 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004235 // Limit MixerThread data processing to no more than twice the
4236 // expected processing rate.
4237 //
4238 // This helps prevent underruns with NuPlayer and other applications
4239 // which may set up buffers that are close to the minimum size, or use
4240 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4241 //
4242 // The throttle smooths out sudden large data drains from the device,
4243 // e.g. when it comes out of standby, which often causes problems with
4244 // (1) mixer threads without a fast mixer (which has its own warm-up)
4245 // (2) minimum buffer sized tracks (even if the track is full,
4246 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004247 //
4248 // Total time spent in last processing cycle equals time spent in
4249 // 1. threadLoop_write, as well as time spent in
4250 // 2. threadLoop_mix (significant for heavy mixing, especially
4251 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004252
Andy Hung446f4df2019-02-21 12:26:41 -08004253 // it's OK if deltaMs is an overestimate.
4254
4255 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004256
Ivan Lozanoea04d392017-11-07 14:37:07 -08004257 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004258 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004259 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004260
Andy Hung08fb1742015-05-31 23:22:10 -07004261 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004262 // notify of throttle start on verbose log
4263 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4264 "mixer(%p) throttle begin:"
4265 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004266 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004267 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004268 // Throttle must be attributed to the previous mixer loop's write time
4269 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004270 // This also ensures proper timing statistics.
4271 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004272 } else {
4273 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4274 if (diff > 0) {
4275 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004276 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004277 ALOGD_IF(!isSingleDeviceType(
4278 outDeviceTypes(), audio_is_a2dp_out_device) &&
4279 !isSingleDeviceType(
4280 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004281 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004282 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4283 }
Andy Hung08fb1742015-05-31 23:22:10 -07004284 }
4285 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004286 }
Eric Laurent81784c32012-11-19 14:55:58 -08004287
Eric Laurentbfb1b832013-01-07 09:53:42 -08004288 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004289 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004290 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004291 // suspended requires accurate metering of sleep time.
4292 if (isSuspended()) {
4293 // advance by expected sleepTime
4294 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4295 const nsecs_t nowNs = systemTime();
4296
4297 // compute expected next time vs current time.
4298 // (negative deltas are treated as delays).
4299 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4300 if (deltaNs < -kMaxNextBufferDelayNs) {
4301 // Delays longer than the max allowed trigger a reset.
4302 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4303 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4304 timeLoopNextNs = nowNs + deltaNs;
4305 } else if (deltaNs < 0) {
4306 // Delays within the max delay allowed: zero the delta/sleepTime
4307 // to help the system catch up in the next iteration(s)
4308 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4309 deltaNs = 0;
4310 }
4311 // update sleep time (which is >= 0)
4312 mSleepTimeUs = deltaNs / 1000;
4313 }
Eric Laurente93cc032016-05-05 10:15:10 -07004314 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4315 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004316 }
Glenn Kastene7754022014-10-31 12:11:26 -07004317 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004318 }
Eric Laurent81784c32012-11-19 14:55:58 -08004319 }
4320
4321 // Finally let go of removed track(s), without the lock held
4322 // since we can't guarantee the destructors won't acquire that
4323 // same lock. This will also mutate and push a new fast mixer state.
4324 threadLoop_removeTracks(tracksToRemove);
4325 tracksToRemove.clear();
4326
4327 // FIXME I don't understand the need for this here;
4328 // it was in the original code but maybe the
4329 // assignment in saveOutputTracks() makes this unnecessary?
4330 clearOutputTracks();
4331
4332 // Effect chains will be actually deleted here if they were removed from
4333 // mEffectChains list during mixing or effects processing
4334 effectChains.clear();
4335
4336 // FIXME Note that the above .clear() is no longer necessary since effectChains
4337 // is now local to this block, but will keep it for now (at least until merge done).
4338 }
4339
Eric Laurentbfb1b832013-01-07 09:53:42 -08004340 threadLoop_exit();
4341
Eric Laurentcf817a22014-08-04 20:36:31 -07004342 if (!mStandby) {
4343 threadLoop_standby();
4344 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004345 }
4346
4347 releaseWakeLock();
4348
4349 ALOGV("Thread %p type %d exiting", this, mType);
4350 return false;
4351}
4352
Dean Wheatley12473e92021-03-18 23:00:55 +11004353void AudioFlinger::PlaybackThread::collectTimestamps_l()
4354{
Dean Wheatley12473e92021-03-18 23:00:55 +11004355 if (mStandby) {
4356 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4357 return;
4358 } else if (mHwPaused) {
4359 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4360 return;
4361 }
4362
4363 // Gather the framesReleased counters for all active tracks,
4364 // and associate with the sink frames written out. We need
4365 // this to convert the sink timestamp to the track timestamp.
4366 bool kernelLocationUpdate = false;
4367 ExtendedTimestamp timestamp; // use private copy to fetch
4368
4369 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4370 // HAL may be draining some small duration buffered data for fade out.
4371 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4372 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4373 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4374 mSampleRate);
4375
4376 if (isTimestampCorrectionEnabled()) {
4377 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4378 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4379 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4380 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4381 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4382 = correctedTimestamp.mFrames;
4383 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4384 = correctedTimestamp.mTimeNs;
4385 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4386 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4387 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4388
4389 // Note: Downstream latency only added if timestamp correction enabled.
4390 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4391 const int64_t newPosition =
4392 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4393 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4394 // prevent retrograde
4395 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4396 newPosition,
4397 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4398 - mSuspendedFrames));
4399 }
4400 }
4401
4402 // We always fetch the timestamp here because often the downstream
4403 // sink will block while writing.
4404
4405 // We keep track of the last valid kernel position in case we are in underrun
4406 // and the normal mixer period is the same as the fast mixer period, or there
4407 // is some error from the HAL.
4408 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4409 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4410 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4411 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4412 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4413
4414 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4415 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4416 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4417 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4418 }
4419
4420 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4421 kernelLocationUpdate = true;
4422 } else {
4423 ALOGVV("getTimestamp error - no valid kernel position");
4424 }
4425
4426 // copy over kernel info
4427 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4428 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4429 + mSuspendedFrames; // add frames discarded when suspended
4430 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4431 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4432 } else {
4433 mTimestampVerifier.error();
4434 }
4435
4436 // mFramesWritten for non-offloaded tracks are contiguous
4437 // even after standby() is called. This is useful for the track frame
4438 // to sink frame mapping.
4439 bool serverLocationUpdate = false;
4440 if (mFramesWritten != mLastFramesWritten) {
4441 serverLocationUpdate = true;
4442 mLastFramesWritten = mFramesWritten;
4443 }
4444 // Only update timestamps if there is a meaningful change.
4445 // Either the kernel timestamp must be valid or we have written something.
4446 if (kernelLocationUpdate || serverLocationUpdate) {
4447 if (serverLocationUpdate) {
4448 // use the time before we called the HAL write - it is a bit more accurate
4449 // to when the server last read data than the current time here.
4450 //
4451 // If we haven't written anything, mLastIoBeginNs will be -1
4452 // and we use systemTime().
4453 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4454 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4455 ? systemTime() : mLastIoBeginNs;
4456 }
4457
4458 for (const sp<Track> &t : mActiveTracks) {
4459 if (!t->isFastTrack()) {
4460 t->updateTrackFrameInfo(
4461 t->mAudioTrackServerProxy->framesReleased(),
4462 mFramesWritten,
4463 mSampleRate,
4464 mTimestamp);
4465 }
4466 }
4467 }
4468
4469 if (audio_has_proportional_frames(mFormat)) {
4470 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4471 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4472 mLatencyMs.add(latencyMs);
4473 }
4474 }
4475#if 0
4476 // logFormat example
4477 if (z % 100 == 0) {
4478 timespec ts;
4479 clock_gettime(CLOCK_MONOTONIC, &ts);
4480 LOGT("This is an integer %d, this is a float %f, this is my "
4481 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4482 LOGT("A deceptive null-terminated string %\0");
4483 }
4484 ++z;
4485#endif
4486}
4487
Eric Laurentbfb1b832013-01-07 09:53:42 -08004488// removeTracks_l() must be called with ThreadBase::mLock held
4489void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4490{
Andy Hungfe726a62018-09-27 15:17:25 -07004491 for (const auto& track : tracksToRemove) {
4492 mActiveTracks.remove(track);
4493 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4494 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4495 if (chain != 0) {
4496 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4497 __func__, track->id(), chain.get(), track->sessionId());
4498 chain->decActiveTrackCnt();
4499 }
4500 // If an external client track, inform APM we're no longer active, and remove if needed.
4501 // We do this under lock so that the state is consistent if the Track is destroyed.
4502 if (track->isExternalTrack()) {
4503 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004504 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004505 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004506 }
4507 }
Andy Hungfe726a62018-09-27 15:17:25 -07004508 if (track->isTerminated()) {
4509 // remove from our tracks vector
4510 removeTrack_l(track);
4511 }
jiabineb3bda02020-06-30 14:07:03 -07004512 if (mHapticChannelCount > 0 &&
4513 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4514 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004515 mLock.unlock();
4516 // Unlock due to VibratorService will lock for this call and will
4517 // call Tracks.mute/unmute which also require thread's lock.
4518 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4519 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004520
4521 // When the track is stop, set the haptic intensity as MUTE
4522 // for the HapticGenerator effect.
4523 if (chain != nullptr) {
4524 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4525 }
jiabin245cdd92018-12-07 17:55:15 -08004526 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004527 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004528}
Eric Laurent81784c32012-11-19 14:55:58 -08004529
Eric Laurentaccc1472013-09-20 09:36:34 -07004530status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4531{
4532 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004533 ExtendedTimestamp ets;
4534 status_t status = mNormalSink->getTimestamp(ets);
4535 if (status == NO_ERROR) {
4536 status = ets.getBestTimestamp(&timestamp);
4537 }
4538 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004539 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004540 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004541 collectTimestamps_l();
4542 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4543 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004544 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004545 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4546 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4547 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4548 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4549 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004550 }
4551 return INVALID_OPERATION;
4552}
Eric Laurent1c333e22014-05-20 10:48:17 -07004553
Eric Laurenteab90452019-06-24 15:17:46 -07004554// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4555// still applied by the mixer.
4556// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4557// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4558// if more than one track are active
4559status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4560{
4561 status_t result = NO_ERROR;
4562 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4563 if (*volume != mLeftVolFloat) {
4564 result = mOutput->stream->setVolume(*volume, *volume);
4565 ALOGE_IF(result != OK,
4566 "Error when setting output stream volume: %d", result);
4567 if (result == NO_ERROR) {
4568 mLeftVolFloat = *volume;
4569 }
4570 }
4571 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4572 // remove stream volume contribution from software volume.
4573 if (mLeftVolFloat == *volume) {
4574 *volume = 1.0f;
4575 }
4576 }
4577 return result;
4578}
4579
Eric Laurent054d9d32015-04-24 08:48:48 -07004580status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4581 audio_patch_handle_t *handle)
4582{
Andy Hungf60abce2016-08-26 11:37:54 -07004583 status_t status;
4584 if (property_get_bool("af.patch_park", false /* default_value */)) {
4585 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4586 // or if HAL does not properly lock against access.
4587 AutoPark<FastMixer> park(mFastMixer);
4588 status = PlaybackThread::createAudioPatch_l(patch, handle);
4589 } else {
4590 status = PlaybackThread::createAudioPatch_l(patch, handle);
4591 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004592 return status;
4593}
4594
Eric Laurent1c333e22014-05-20 10:48:17 -07004595status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4596 audio_patch_handle_t *handle)
4597{
4598 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004599
4600 // store new device and send to effects
4601 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004602 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004603 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004604 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4605 && !mOutput->audioHwDev->supportsAudioPatches(),
4606 "Enumerated device type(%#x) must not be used "
4607 "as it does not support audio patches",
4608 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004609 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07004610 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4611 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004612 }
4613
François Gaffie0c280aa2018-07-25 10:02:15 +02004614 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004615#ifdef ADD_BATTERY_DATA
4616 // when changing the audio output device, call addBatteryData to notify
4617 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004618 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004619 uint32_t params = 0;
4620 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004621 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004622 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004623 }
4624
Eric Laurent054d9d32015-04-24 08:48:48 -07004625 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004626 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004627 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4628 }
4629
4630 if (params != 0) {
4631 addBatteryData(params);
4632 }
4633 }
4634#endif
4635
4636 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004637 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004638 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004639
jiabinc52b1ff2019-10-31 17:20:42 -07004640 // mPatch.num_sinks is not set when the thread is created so that
4641 // the first patch creation triggers an ioConfigChanged callback
4642 bool configChanged = (mPatch.num_sinks == 0) ||
4643 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004644 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004645 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004646 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004647
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004648 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004649 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4650 status = hwDevice->createAudioPatch(patch->num_sources,
4651 patch->sources,
4652 patch->num_sinks,
4653 patch->sinks,
4654 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004655 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004656 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004657 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004658 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004659 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004660
4661 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004662 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004663 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004664 // also dispatch to active AudioTracks for MediaMetrics
4665 for (const auto &track : mActiveTracks) {
4666 track->logEndInterval();
4667 track->logBeginInterval(patchSinksAsString);
4668 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004669
Eric Laurente8726fe2015-06-26 09:39:24 -07004670 if (configChanged) {
4671 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4672 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004673 return status;
4674}
4675
Eric Laurent054d9d32015-04-24 08:48:48 -07004676status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4677{
Andy Hungf60abce2016-08-26 11:37:54 -07004678 status_t status;
4679 if (property_get_bool("af.patch_park", false /* default_value */)) {
4680 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4681 // or if HAL does not properly lock against access.
4682 AutoPark<FastMixer> park(mFastMixer);
4683 status = PlaybackThread::releaseAudioPatch_l(handle);
4684 } else {
4685 status = PlaybackThread::releaseAudioPatch_l(handle);
4686 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004687 return status;
4688}
4689
Eric Laurent1c333e22014-05-20 10:48:17 -07004690status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4691{
4692 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004693
jiabinc52b1ff2019-10-31 17:20:42 -07004694 mPatch = audio_patch{};
4695 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004696
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004697 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004698 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4699 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004700 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004701 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004702 }
4703 return status;
4704}
4705
Eric Laurent83b88082014-06-20 18:31:16 -07004706void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4707{
4708 Mutex::Autolock _l(mLock);
4709 mTracks.add(track);
4710}
4711
4712void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4713{
4714 Mutex::Autolock _l(mLock);
4715 destroyTrack_l(track);
4716}
4717
Mikhail Naganovdc769682018-05-04 15:34:08 -07004718void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004719{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004720 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004721 config->role = AUDIO_PORT_ROLE_SOURCE;
4722 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4723 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004724 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4725 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4726 config->flags.output = mOutput->flags;
4727 }
Eric Laurent83b88082014-06-20 18:31:16 -07004728}
4729
Eric Laurent81784c32012-11-19 14:55:58 -08004730// ----------------------------------------------------------------------------
4731
4732AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004733 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
4734 : PlaybackThread(audioFlinger, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004735 // mAudioMixer below
4736 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004737 mFastMixerFutex(0),
4738 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004739 // mOutputSink below
4740 // mPipeSink below
4741 // mNormalSink below
4742{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004743 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004744 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004745 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004746 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004747 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4748 mNormalFrameCount);
4749 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4750
Andy Hungfbfc3952015-01-15 13:33:51 -08004751 if (type == DUPLICATING) {
4752 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4753 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4754 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4755 return;
4756 }
Eric Laurent81784c32012-11-19 14:55:58 -08004757 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004758 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004759 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004760 const NBAIO_Format offers[1] = {Format_from_SR_C(
4761 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004762#if !LOG_NDEBUG
4763 ssize_t index =
4764#else
4765 (void)
4766#endif
4767 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004768 ALOG_ASSERT(index == 0);
4769
4770 // initialize fast mixer depending on configuration
4771 bool initFastMixer;
Eric Laurentb62d0362021-10-26 17:40:18 +02004772 if (mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004773 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004774 } else {
4775 switch (kUseFastMixer) {
4776 case FastMixer_Never:
4777 initFastMixer = false;
4778 break;
4779 case FastMixer_Always:
4780 initFastMixer = true;
4781 break;
4782 case FastMixer_Static:
4783 case FastMixer_Dynamic:
4784 initFastMixer = mFrameCount < mNormalFrameCount;
4785 break;
4786 }
4787 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4788 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4789 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004790 }
4791 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004792 audio_format_t fastMixerFormat;
4793 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4794 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4795 } else {
4796 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4797 }
4798 if (mFormat != fastMixerFormat) {
4799 // change our Sink format to accept our intermediate precision
4800 mFormat = fastMixerFormat;
4801 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004802 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004803 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4804 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4805 }
Eric Laurent81784c32012-11-19 14:55:58 -08004806
4807 // create a MonoPipe to connect our submix to FastMixer
4808 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004809
Andy Hung1258c1a2014-05-23 21:22:17 -07004810 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004811 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004812 format.mFormat = fastMixerFormat;
4813 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4814
Eric Laurent81784c32012-11-19 14:55:58 -08004815 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4816 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4817 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4818 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4819 const NBAIO_Format offers[1] = {format};
4820 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004821#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004822 ssize_t index =
4823#else
4824 (void)
4825#endif
4826 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004827 ALOG_ASSERT(index == 0);
4828 monoPipe->setAvgFrames((mScreenState & 1) ?
4829 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4830 mPipeSink = monoPipe;
4831
Eric Laurent81784c32012-11-19 14:55:58 -08004832 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004833 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004834 FastMixerStateQueue *sq = mFastMixer->sq();
4835#ifdef STATE_QUEUE_DUMP
4836 sq->setObserverDump(&mStateQueueObserverDump);
4837 sq->setMutatorDump(&mStateQueueMutatorDump);
4838#endif
4839 FastMixerState *state = sq->begin();
4840 FastTrack *fastTrack = &state->mFastTracks[0];
4841 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4842 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4843 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004844 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4845 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4846 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004847 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004848 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004849 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01004850 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08004851 fastTrack->mGeneration++;
4852 state->mFastTracksGen++;
4853 state->mTrackMask = 1;
4854 // fast mixer will use the HAL output sink
4855 state->mOutputSink = mOutputSink.get();
4856 state->mOutputSinkGen++;
4857 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004858 // specify sink channel mask when haptic channel mask present as it can not
4859 // be calculated directly from channel count
4860 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004861 ? AUDIO_CHANNEL_NONE
4862 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004863 state->mCommand = FastMixerState::COLD_IDLE;
4864 // already done in constructor initialization list
4865 //mFastMixerFutex = 0;
4866 state->mColdFutexAddr = &mFastMixerFutex;
4867 state->mColdGen++;
4868 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004869 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4870 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004871 sq->end();
4872 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4873
Eric Tan0513b5d2018-09-17 10:32:48 -07004874 NBLog::thread_info_t info;
4875 info.id = mId;
4876 info.type = NBLog::FASTMIXER;
4877 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4878
Eric Laurent81784c32012-11-19 14:55:58 -08004879 // start the fast mixer
4880 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4881 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004882 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004883 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004884
4885#ifdef AUDIO_WATCHDOG
4886 // create and start the watchdog
4887 mAudioWatchdog = new AudioWatchdog();
4888 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4889 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4890 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004891 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004892#endif
Andy Hung8946a282018-04-19 20:04:56 -07004893 } else {
4894#ifdef TEE_SINK
4895 // Only use the MixerThread tee if there is no FastMixer.
4896 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4897 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4898#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004899 }
4900
4901 switch (kUseFastMixer) {
4902 case FastMixer_Never:
4903 case FastMixer_Dynamic:
4904 mNormalSink = mOutputSink;
4905 break;
4906 case FastMixer_Always:
4907 mNormalSink = mPipeSink;
4908 break;
4909 case FastMixer_Static:
4910 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4911 break;
4912 }
4913}
4914
4915AudioFlinger::MixerThread::~MixerThread()
4916{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004917 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004918 FastMixerStateQueue *sq = mFastMixer->sq();
4919 FastMixerState *state = sq->begin();
4920 if (state->mCommand == FastMixerState::COLD_IDLE) {
4921 int32_t old = android_atomic_inc(&mFastMixerFutex);
4922 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004923 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004924 }
4925 }
4926 state->mCommand = FastMixerState::EXIT;
4927 sq->end();
4928 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4929 mFastMixer->join();
4930 // Though the fast mixer thread has exited, it's state queue is still valid.
4931 // We'll use that extract the final state which contains one remaining fast track
4932 // corresponding to our sub-mix.
4933 state = sq->begin();
4934 ALOG_ASSERT(state->mTrackMask == 1);
4935 FastTrack *fastTrack = &state->mFastTracks[0];
4936 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4937 delete fastTrack->mBufferProvider;
4938 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004939 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004940#ifdef AUDIO_WATCHDOG
4941 if (mAudioWatchdog != 0) {
4942 mAudioWatchdog->requestExit();
4943 mAudioWatchdog->requestExitAndWait();
4944 mAudioWatchdog.clear();
4945 }
4946#endif
4947 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004948 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004949 delete mAudioMixer;
4950}
4951
4952
4953uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4954{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004955 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004956 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4957 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4958 }
4959 return latency;
4960}
4961
Eric Laurentbfb1b832013-01-07 09:53:42 -08004962ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004963{
4964 // FIXME we should only do one push per cycle; confirm this is true
4965 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004966 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004967 FastMixerStateQueue *sq = mFastMixer->sq();
4968 FastMixerState *state = sq->begin();
4969 if (state->mCommand != FastMixerState::MIX_WRITE &&
4970 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4971 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004972
4973 // FIXME workaround for first HAL write being CPU bound on some devices
4974 ATRACE_BEGIN("write");
4975 mOutput->write((char *)mSinkBuffer, 0);
4976 ATRACE_END();
4977
Eric Laurent81784c32012-11-19 14:55:58 -08004978 int32_t old = android_atomic_inc(&mFastMixerFutex);
4979 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004980 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004981 }
4982#ifdef AUDIO_WATCHDOG
4983 if (mAudioWatchdog != 0) {
4984 mAudioWatchdog->resume();
4985 }
4986#endif
4987 }
4988 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004989#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004990 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004991 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004992#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004993 sq->end();
4994 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4995 if (kUseFastMixer == FastMixer_Dynamic) {
4996 mNormalSink = mPipeSink;
4997 }
4998 } else {
4999 sq->end(false /*didModify*/);
5000 }
5001 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005002 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005003}
5004
5005void AudioFlinger::MixerThread::threadLoop_standby()
5006{
5007 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005008 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005009 FastMixerStateQueue *sq = mFastMixer->sq();
5010 FastMixerState *state = sq->begin();
5011 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005012 // Report any frames trapped in the Monopipe
5013 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5014 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5015 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5016 "monoPipeWritten:%lld monoPipeLeft:%lld",
5017 (long long)mFramesWritten, (long long)mSuspendedFrames,
5018 (long long)mPipeSink->framesWritten(), pipeFrames);
5019 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5020
Eric Laurent81784c32012-11-19 14:55:58 -08005021 state->mCommand = FastMixerState::COLD_IDLE;
5022 state->mColdFutexAddr = &mFastMixerFutex;
5023 state->mColdGen++;
5024 mFastMixerFutex = 0;
5025 sq->end();
5026 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5027 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5028 if (kUseFastMixer == FastMixer_Dynamic) {
5029 mNormalSink = mOutputSink;
5030 }
5031#ifdef AUDIO_WATCHDOG
5032 if (mAudioWatchdog != 0) {
5033 mAudioWatchdog->pause();
5034 }
5035#endif
5036 } else {
5037 sq->end(false /*didModify*/);
5038 }
5039 }
5040 PlaybackThread::threadLoop_standby();
5041}
5042
Eric Laurentbfb1b832013-01-07 09:53:42 -08005043bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
5044{
5045 return false;
5046}
5047
5048bool AudioFlinger::PlaybackThread::shouldStandby_l()
5049{
5050 return !mStandby;
5051}
5052
5053bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
5054{
5055 Mutex::Autolock _l(mLock);
5056 return waitingAsyncCallback_l();
5057}
5058
Eric Laurent81784c32012-11-19 14:55:58 -08005059// shared by MIXER and DIRECT, overridden by DUPLICATING
5060void AudioFlinger::PlaybackThread::threadLoop_standby()
5061{
5062 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005063 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005064 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005065 // discard any pending drain or write ack by incrementing sequence
5066 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5067 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005068 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005069 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5070 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005071 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005072 mHwPaused = false;
Eric Laurent6f9534f2022-05-03 18:15:04 +02005073 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005074}
5075
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005076void AudioFlinger::PlaybackThread::onAddNewTrack_l()
5077{
5078 ALOGV("signal playback thread");
5079 broadcast_l();
5080}
5081
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005082void AudioFlinger::PlaybackThread::onAsyncError()
5083{
5084 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5085 invalidateTracks((audio_stream_type_t)i);
5086 }
5087}
5088
Eric Laurent81784c32012-11-19 14:55:58 -08005089void AudioFlinger::MixerThread::threadLoop_mix()
5090{
Eric Laurent81784c32012-11-19 14:55:58 -08005091 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005092 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005093 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005094 // increase sleep time progressively when application underrun condition clears.
5095 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5096 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5097 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005098 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005099 sleepTimeShift--;
5100 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005101 mSleepTimeUs = 0;
5102 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005103 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005104
Eric Laurent81784c32012-11-19 14:55:58 -08005105}
5106
5107void AudioFlinger::MixerThread::threadLoop_sleepTime()
5108{
5109 // If no tracks are ready, sleep once for the duration of an output
5110 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005111 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005112 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005113 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5114 // Using the Monopipe availableToWrite, we estimate the
5115 // sleep time to retry for more data (before we underrun).
5116 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5117 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5118 const size_t pipeFrames = monoPipe->maxFrames();
5119 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5120 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5121 const size_t framesDelay = std::min(
5122 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5123 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5124 pipeFrames, framesLeft, framesDelay);
5125 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5126 } else {
5127 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5128 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5129 mSleepTimeUs = kMinThreadSleepTimeUs;
5130 }
5131 // reduce sleep time in case of consecutive application underruns to avoid
5132 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5133 // duration we would end up writing less data than needed by the audio HAL if
5134 // the condition persists.
5135 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5136 sleepTimeShift++;
5137 }
Eric Laurent81784c32012-11-19 14:55:58 -08005138 }
5139 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005140 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005141 }
5142 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005143 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5144 // before effects processing or output.
5145 if (mMixerBufferValid) {
5146 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005147 if (mType == SPATIALIZER) {
5148 memset(mSinkBuffer, 0, mSinkBufferSize);
5149 }
Andy Hung98ef9782014-03-04 14:46:50 -08005150 } else {
5151 memset(mSinkBuffer, 0, mSinkBufferSize);
5152 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005153 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005154 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5155 "anticipated start");
5156 }
5157 // TODO add standby time extension fct of effect tail
5158}
5159
5160// prepareTracks_l() must be called with ThreadBase::mLock held
5161AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
5162 Vector< sp<Track> > *tracksToRemove)
5163{
Andy Hungc0691382018-09-12 18:01:57 -07005164 // clean up deleted track ids in AudioMixer before allocating new tracks
5165 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5166 // for each trackId, destroy it in the AudioMixer
5167 if (mAudioMixer->exists(trackId)) {
5168 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005169 }
5170 });
Andy Hungc0691382018-09-12 18:01:57 -07005171 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005172
5173 mixer_state mixerStatus = MIXER_IDLE;
5174 // find out which tracks need to be processed
5175 size_t count = mActiveTracks.size();
5176 size_t mixedTracks = 0;
5177 size_t tracksWithEffect = 0;
5178 // counts only _active_ fast tracks
5179 size_t fastTracks = 0;
5180 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5181
5182 float masterVolume = mMasterVolume;
5183 bool masterMute = mMasterMute;
5184
5185 if (masterMute) {
5186 masterVolume = 0;
5187 }
5188 // Delegate master volume control to effect in output mix effect chain if needed
5189 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
5190 if (chain != 0) {
5191 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5192 chain->setVolume_l(&v, &v);
5193 masterVolume = (float)((v + (1 << 23)) >> 24);
5194 chain.clear();
5195 }
5196
5197 // prepare a new state to push
5198 FastMixerStateQueue *sq = NULL;
5199 FastMixerState *state = NULL;
5200 bool didModify = false;
5201 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005202 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005203 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005204 sq = mFastMixer->sq();
5205 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005206 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005207 }
5208
Andy Hung69aed5f2014-02-25 17:24:40 -08005209 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005210 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005211
Andy Hungbd3b2b02018-05-21 10:53:11 -07005212 // DeferredOperations handles statistics after setting mixerStatus.
5213 class DeferredOperations {
5214 public:
Andy Hungea840382020-05-05 21:50:17 -07005215 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5216 : mMixerStatus(mixerStatus)
5217 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005218
5219 // when leaving scope, tally frames properly.
5220 ~DeferredOperations() {
5221 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5222 // because that is when the underrun occurs.
5223 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005224 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005225 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005226 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005227 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005228 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005229 }
5230 }
Andy Hungea840382020-05-05 21:50:17 -07005231 // send the max underrun frames for this mixer period
5232 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005233 }
5234
5235 // tallyUnderrunFrames() is called to update the track counters
5236 // with the number of underrun frames for a particular mixer period.
5237 // We defer tallying until we know the final mixer status.
5238 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
5239 mUnderrunFrames.emplace_back(track, underrunFrames);
5240 }
5241
5242 private:
5243 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005244 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07005245 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005246 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005247 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005248
jiabin245cdd92018-12-07 17:55:15 -08005249 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005250 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07005251 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005252
5253 // this const just means the local variable doesn't change
5254 Track* const track = t.get();
5255
5256 // process fast tracks
5257 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005258 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5259 "%s(%d): FastTrack(%d) present without FastMixer",
5260 __func__, id(), track->id());
5261
jiabin245cdd92018-12-07 17:55:15 -08005262 if (track->getHapticPlaybackEnabled()) {
5263 noFastHapticTrack = false;
5264 }
Eric Laurent81784c32012-11-19 14:55:58 -08005265
5266 // It's theoretically possible (though unlikely) for a fast track to be created
5267 // and then removed within the same normal mix cycle. This is not a problem, as
5268 // the track never becomes active so it's fast mixer slot is never touched.
5269 // The converse, of removing an (active) track and then creating a new track
5270 // at the identical fast mixer slot within the same normal mix cycle,
5271 // is impossible because the slot isn't marked available until the end of each cycle.
5272 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005273 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005274 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5275 FastTrack *fastTrack = &state->mFastTracks[j];
5276
5277 // Determine whether the track is currently in underrun condition,
5278 // and whether it had a recent underrun.
5279 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5280 FastTrackUnderruns underruns = ftDump->mUnderruns;
5281 uint32_t recentFull = (underruns.mBitFields.mFull -
5282 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
5283 uint32_t recentPartial = (underruns.mBitFields.mPartial -
5284 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
5285 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
5286 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
5287 uint32_t recentUnderruns = recentPartial + recentEmpty;
5288 track->mObservedUnderruns = underruns;
5289 // don't count underruns that occur while stopping or pausing
5290 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005291 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005292 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5293 recentUnderruns > 0) {
5294 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005295 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005296 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005297 // Immediately account for FastTrack underruns.
5298 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005299
5300 // This is similar to the state machine for normal tracks,
5301 // with a few modifications for fast tracks.
5302 bool isActive = true;
5303 switch (track->mState) {
5304 case TrackBase::STOPPING_1:
5305 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005306 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005307 track->mState = TrackBase::STOPPING_2;
5308 }
5309 break;
5310 case TrackBase::PAUSING:
5311 // ramp down is not yet implemented
5312 track->setPaused();
5313 break;
5314 case TrackBase::RESUMING:
5315 // ramp up is not yet implemented
5316 track->mState = TrackBase::ACTIVE;
5317 break;
5318 case TrackBase::ACTIVE:
5319 if (recentFull > 0 || recentPartial > 0) {
5320 // track has provided at least some frames recently: reset retry count
5321 track->mRetryCount = kMaxTrackRetries;
5322 }
5323 if (recentUnderruns == 0) {
5324 // no recent underruns: stay active
5325 break;
5326 }
5327 // there has recently been an underrun of some kind
5328 if (track->sharedBuffer() == 0) {
5329 // were any of the recent underruns "empty" (no frames available)?
5330 if (recentEmpty == 0) {
5331 // no, then ignore the partial underruns as they are allowed indefinitely
5332 break;
5333 }
5334 // there has recently been an "empty" underrun: decrement the retry counter
5335 if (--(track->mRetryCount) > 0) {
5336 break;
5337 }
5338 // indicate to client process that the track was disabled because of underrun;
5339 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005340 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005341 // remove from active list, but state remains ACTIVE [confusing but true]
5342 isActive = false;
5343 break;
5344 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005345 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005346 case TrackBase::STOPPING_2:
5347 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005348 case TrackBase::STOPPED:
5349 case TrackBase::FLUSHED: // flush() while active
5350 // Check for presentation complete if track is inactive
5351 // We have consumed all the buffers of this track.
5352 // This would be incomplete if we auto-paused on underrun
5353 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005354 uint32_t latency = 0;
5355 status_t result = mOutput->stream->getLatency(&latency);
5356 ALOGE_IF(result != OK,
5357 "Error when retrieving output stream latency: %d", result);
5358 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005359 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005360 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5361 // track stays in active list until presentation is complete
5362 break;
5363 }
5364 }
5365 if (track->isStopping_2()) {
5366 track->mState = TrackBase::STOPPED;
5367 }
5368 if (track->isStopped()) {
5369 // Can't reset directly, as fast mixer is still polling this track
5370 // track->reset();
5371 // So instead mark this track as needing to be reset after push with ack
5372 resetMask |= 1 << i;
5373 }
5374 isActive = false;
5375 break;
5376 case TrackBase::IDLE:
5377 default:
Andy Hung959b5b82021-09-24 10:46:20 -07005378 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005379 }
5380
5381 if (isActive) {
5382 // was it previously inactive?
5383 if (!(state->mTrackMask & (1 << j))) {
5384 ExtendedAudioBufferProvider *eabp = track;
5385 VolumeProvider *vp = track;
5386 fastTrack->mBufferProvider = eabp;
5387 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005388 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005389 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005390 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005391 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005392 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005393 fastTrack->mGeneration++;
5394 state->mTrackMask |= 1 << j;
5395 didModify = true;
5396 // no acknowledgement required for newly active tracks
5397 }
Kevin Rocard12381092018-04-11 09:19:59 -07005398 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005399 float volume;
5400 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5401 volume = 0.f;
5402 } else {
5403 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5404 }
5405
5406 handleVoipVolume_l(&volume);
5407
Eric Laurent81784c32012-11-19 14:55:58 -08005408 // cache the combined master volume and stream type volume for fast mixer; this
5409 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005410 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005411 proxy->framesReleased()).first;
5412 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005413 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005414 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5415 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5416 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005417
Kevin Rocard12381092018-04-11 09:19:59 -07005418 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005419 ++fastTracks;
5420 } else {
5421 // was it previously active?
5422 if (state->mTrackMask & (1 << j)) {
5423 fastTrack->mBufferProvider = NULL;
5424 fastTrack->mGeneration++;
5425 state->mTrackMask &= ~(1 << j);
5426 didModify = true;
5427 // If any fast tracks were removed, we must wait for acknowledgement
5428 // because we're about to decrement the last sp<> on those tracks.
5429 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5430 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005431 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5432 // AudioTrack may start (which may not be with a start() but with a write()
5433 // after underrun) and immediately paused or released. In that case the
5434 // FastTrack state hasn't had time to update.
5435 // TODO Remove the ALOGW when this theory is confirmed.
5436 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005437 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung959b5b82021-09-24 10:46:20 -07005438 j, (int)track->mState, state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005439 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005440 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005441 }
5442 tracksToRemove->add(track);
5443 // Avoids a misleading display in dumpsys
5444 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5445 }
jiabin245cdd92018-12-07 17:55:15 -08005446 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5447 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5448 didModify = true;
5449 }
Eric Laurent81784c32012-11-19 14:55:58 -08005450 continue;
5451 }
5452
5453 { // local variable scope to avoid goto warning
5454
5455 audio_track_cblk_t* cblk = track->cblk();
5456
5457 // The first time a track is added we wait
5458 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005459 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005460
5461 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005462 // use the trackId as the AudioMixer name.
5463 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005464 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005465 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005466 track->mChannelMask,
5467 track->mFormat,
5468 track->mSessionId);
5469 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005470 ALOGW("%s(): AudioMixer cannot create track(%d)"
5471 " mask %#x, format %#x, sessionId %d",
5472 __func__, trackId,
5473 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005474 tracksToRemove->add(track);
5475 track->invalidate(); // consider it dead.
5476 continue;
5477 }
5478 }
5479
Eric Laurent81784c32012-11-19 14:55:58 -08005480 // make sure that we have enough frames to mix one full buffer.
5481 // enforce this condition only once to enable draining the buffer in case the client
5482 // app does not call stop() and relies on underrun to stop:
5483 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5484 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005485 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005486 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005487 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005488
5489 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005490 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005491 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5492 // add frames already consumed but not yet released by the resampler
5493 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005494 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005495
Eric Laurent81784c32012-11-19 14:55:58 -08005496 uint32_t minFrames = 1;
5497 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5498 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005499 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005500 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005501
5502 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005503 if (ATRACE_ENABLED()) {
5504 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005505 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005506 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005507 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005508 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005509 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005510 !track->isPaused() && !track->isTerminated())
5511 {
Andy Hungc0691382018-09-12 18:01:57 -07005512 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005513
5514 mixedTracks++;
5515
Andy Hung69aed5f2014-02-25 17:24:40 -08005516 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5517 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005518 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005519 if (track->mainBuffer() != mSinkBuffer &&
5520 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005521 if (mEffectBufferEnabled) {
5522 mEffectBufferValid = true; // Later can set directly.
5523 }
Eric Laurent81784c32012-11-19 14:55:58 -08005524 chain = getEffectChain_l(track->sessionId());
5525 // Delegate volume control to effect in track effect chain if needed
5526 if (chain != 0) {
5527 tracksWithEffect++;
5528 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005529 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005530 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005531 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005532 }
5533 }
5534
5535
5536 int param = AudioMixer::VOLUME;
5537 if (track->mFillingUpStatus == Track::FS_FILLED) {
5538 // no ramp for the first volume setting
5539 track->mFillingUpStatus = Track::FS_ACTIVE;
5540 if (track->mState == TrackBase::RESUMING) {
5541 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005542 // If a new track is paused immediately after start, do not ramp on resume.
5543 if (cblk->mServer != 0) {
5544 param = AudioMixer::RAMP_VOLUME;
5545 }
Eric Laurent81784c32012-11-19 14:55:58 -08005546 }
Andy Hungc0691382018-09-12 18:01:57 -07005547 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005548 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005549 // FIXME should not make a decision based on mServer
5550 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005551 // If the track is stopped before the first frame was mixed,
5552 // do not apply ramp
5553 param = AudioMixer::RAMP_VOLUME;
5554 }
5555
5556 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005557 uint32_t vl, vr; // in U8.24 integer format
5558 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005559 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005560 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005561 // Always fetch volumeshaper volume to ensure state is updated.
5562 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5563 const float vh = track->getVolumeHandler()->getVolume(
5564 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005565
Eric Laurenteab90452019-06-24 15:17:46 -07005566 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5567 v = 0;
5568 }
5569
5570 handleVoipVolume_l(&v);
5571
5572 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005573 vl = vr = 0;
5574 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005575 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005576 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005577 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005578 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5579 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005580 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005581 if (vlf > GAIN_FLOAT_UNITY) {
5582 ALOGV("Track left volume out of range: %.3g", vlf);
5583 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005584 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005585 if (vrf > GAIN_FLOAT_UNITY) {
5586 ALOGV("Track right volume out of range: %.3g", vrf);
5587 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005588 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005589 // now apply the master volume and stream type volume and shaper volume
5590 vlf *= v * vh;
5591 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005592 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005593 // then derive vl and vr as U8.24 versions for the effect chain
5594 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5595 vl = (uint32_t) (scaleto8_24 * vlf);
5596 vr = (uint32_t) (scaleto8_24 * vrf);
5597 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005598 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005599 // send level comes from shared memory and so may be corrupt
5600 if (sendLevel > MAX_GAIN_INT) {
5601 ALOGV("Track send level out of range: %04X", sendLevel);
5602 sendLevel = MAX_GAIN_INT;
5603 }
Andy Hung6be49402014-05-30 10:42:03 -07005604 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5605 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005606 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005607
Kevin Rocard12381092018-04-11 09:19:59 -07005608 track->setFinalVolume((vrf + vlf) / 2.f);
5609
Eric Laurent81784c32012-11-19 14:55:58 -08005610 // Delegate volume control to effect in track effect chain if needed
5611 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5612 // Do not ramp volume if volume is controlled by effect
5613 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005614 // Update remaining floating point volume levels
5615 vlf = (float)vl / (1 << 24);
5616 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005617 track->mHasVolumeController = true;
5618 } else {
5619 // force no volume ramp when volume controller was just disabled or removed
5620 // from effect chain to avoid volume spike
5621 if (track->mHasVolumeController) {
5622 param = AudioMixer::VOLUME;
5623 }
5624 track->mHasVolumeController = false;
5625 }
5626
Eric Laurent81784c32012-11-19 14:55:58 -08005627 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005628 mAudioMixer->setBufferProvider(trackId, track);
5629 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005630
Andy Hungc0691382018-09-12 18:01:57 -07005631 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5632 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5633 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005634 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005635 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005636 AudioMixer::TRACK,
5637 AudioMixer::FORMAT, (void *)track->format());
5638 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005639 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005640 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005641 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005642
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005643 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005644 mAudioMixer->setParameter(
5645 trackId,
5646 AudioMixer::TRACK,
5647 AudioMixer::MIXER_CHANNEL_MASK,
5648 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5649 } else {
5650 mAudioMixer->setParameter(
5651 trackId,
5652 AudioMixer::TRACK,
5653 AudioMixer::MIXER_CHANNEL_MASK,
5654 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5655 }
5656
Glenn Kastene3aa6592012-12-04 12:22:46 -08005657 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005658 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005659 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005660 if (reqSampleRate == 0) {
5661 reqSampleRate = mSampleRate;
5662 } else if (reqSampleRate > maxSampleRate) {
5663 reqSampleRate = maxSampleRate;
5664 }
Eric Laurent81784c32012-11-19 14:55:58 -08005665 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005666 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005667 AudioMixer::RESAMPLE,
5668 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005669 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005670
Andy Hung333ab962019-05-28 20:23:35 -07005671 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005672 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005673 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005674 AudioMixer::TIMESTRETCH,
5675 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005676 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005677
Andy Hung69aed5f2014-02-25 17:24:40 -08005678 /*
5679 * Select the appropriate output buffer for the track.
5680 *
Andy Hung98ef9782014-03-04 14:46:50 -08005681 * Tracks with effects go into their own effects chain buffer
5682 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005683 *
5684 * Other tracks can use mMixerBuffer for higher precision
5685 * channel accumulation. If this buffer is enabled
5686 * (mMixerBufferEnabled true), then selected tracks will accumulate
5687 * into it.
5688 *
5689 */
5690 if (mMixerBufferEnabled
5691 && (track->mainBuffer() == mSinkBuffer
5692 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005693 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005694 mAudioMixer->setParameter(
5695 trackId,
5696 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005697 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005698 mAudioMixer->setParameter(
5699 trackId,
5700 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005701 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005702 } else {
5703 mAudioMixer->setParameter(
5704 trackId,
5705 AudioMixer::TRACK,
5706 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5707 mAudioMixer->setParameter(
5708 trackId,
5709 AudioMixer::TRACK,
5710 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5711 // TODO: override track->mainBuffer()?
5712 mMixerBufferValid = true;
5713 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005714 } else {
5715 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005716 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005717 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005718 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005719 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005720 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005721 AudioMixer::TRACK,
5722 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5723 }
Eric Laurent81784c32012-11-19 14:55:58 -08005724 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005725 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005726 AudioMixer::TRACK,
5727 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005728 mAudioMixer->setParameter(
5729 trackId,
5730 AudioMixer::TRACK,
5731 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005732 mAudioMixer->setParameter(
5733 trackId,
5734 AudioMixer::TRACK,
5735 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Lais Andradebc3f37a2021-07-02 00:13:19 +01005736 mAudioMixer->setParameter(
5737 trackId,
5738 AudioMixer::TRACK,
5739 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)(&(track->mHapticMaxAmplitude)));
Eric Laurent81784c32012-11-19 14:55:58 -08005740
5741 // reset retry count
5742 track->mRetryCount = kMaxTrackRetries;
5743
5744 // If one track is ready, set the mixer ready if:
5745 // - the mixer was not ready during previous round OR
5746 // - no other track is not ready
5747 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5748 mixerStatus != MIXER_TRACKS_ENABLED) {
5749 mixerStatus = MIXER_TRACKS_READY;
5750 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005751
5752 // Enable the next few lines to instrument a test for underrun log handling.
5753 // TODO: Remove when we have a better way of testing the underrun log.
5754#if 0
5755 static int i;
5756 if ((++i & 0xf) == 0) {
5757 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5758 }
5759#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005760 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005761 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005762 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005763 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5764 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005765 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005766 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005767 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005768
Eric Laurent81784c32012-11-19 14:55:58 -08005769 // clear effect chain input buffer if an active track underruns to avoid sending
5770 // previous audio buffer again to effects
5771 chain = getEffectChain_l(track->sessionId());
5772 if (chain != 0) {
5773 chain->clearInputBuffer();
5774 }
5775
Andy Hungc0691382018-09-12 18:01:57 -07005776 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005777 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5778 track->isStopped() || track->isPaused()) {
5779 // We have consumed all the buffers of this track.
5780 // Remove it from the list of active tracks.
5781 // TODO: use actual buffer filling status instead of latency when available from
5782 // audio HAL
5783 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005784 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005785 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5786 if (track->isStopped()) {
5787 track->reset();
5788 }
5789 tracksToRemove->add(track);
5790 }
5791 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005792 // No buffers for this track. Give it a few chances to
5793 // fill a buffer, then remove it from active list.
5794 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005795 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5796 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005797 tracksToRemove->add(track);
5798 // indicate to client process that the track was disabled because of underrun;
5799 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005800 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005801 // If one track is not ready, mark the mixer also not ready if:
5802 // - the mixer was ready during previous round OR
5803 // - no other track is ready
5804 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5805 mixerStatus != MIXER_TRACKS_READY) {
5806 mixerStatus = MIXER_TRACKS_ENABLED;
5807 }
5808 }
Andy Hungc0691382018-09-12 18:01:57 -07005809 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005810 }
5811
5812 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005813
5814 }
5815
jiabin245cdd92018-12-07 17:55:15 -08005816 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5817 // When there is no fast track playing haptic and FastMixer exists,
5818 // enabling the first FastTrack, which provides mixed data from normal
5819 // tracks, to play haptic data.
5820 FastTrack *fastTrack = &state->mFastTracks[0];
5821 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5822 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5823 didModify = true;
5824 }
5825 }
5826
Eric Laurent81784c32012-11-19 14:55:58 -08005827 // Push the new FastMixer state if necessary
5828 bool pauseAudioWatchdog = false;
5829 if (didModify) {
5830 state->mFastTracksGen++;
5831 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5832 if (kUseFastMixer == FastMixer_Dynamic &&
5833 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5834 state->mCommand = FastMixerState::COLD_IDLE;
5835 state->mColdFutexAddr = &mFastMixerFutex;
5836 state->mColdGen++;
5837 mFastMixerFutex = 0;
5838 if (kUseFastMixer == FastMixer_Dynamic) {
5839 mNormalSink = mOutputSink;
5840 }
5841 // If we go into cold idle, need to wait for acknowledgement
5842 // so that fast mixer stops doing I/O.
5843 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5844 pauseAudioWatchdog = true;
5845 }
Eric Laurent81784c32012-11-19 14:55:58 -08005846 }
5847 if (sq != NULL) {
5848 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005849 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5850 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5851 // when bringing the output sink into standby.)
5852 //
5853 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5854 //
5855 // This occurs with BT suspend when we idle the FastMixer with
5856 // active tracks, which may be added or removed.
5857 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005858 }
5859#ifdef AUDIO_WATCHDOG
5860 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5861 mAudioWatchdog->pause();
5862 }
5863#endif
5864
5865 // Now perform the deferred reset on fast tracks that have stopped
5866 while (resetMask != 0) {
5867 size_t i = __builtin_ctz(resetMask);
5868 ALOG_ASSERT(i < count);
5869 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005870 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005871 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5872 track->reset();
5873 }
5874
Andy Hung80d03d22018-04-10 10:32:11 -07005875 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5876 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5877 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5878 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5879 // See also the implementation of destroyTrack_l().
5880 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005881 const int trackId = track->id();
5882 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5883 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005884 }
5885 }
5886
Eric Laurent81784c32012-11-19 14:55:58 -08005887 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005888 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005889
Eric Laurentb3f315a2021-07-13 15:09:05 +02005890 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
5891 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07005892 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005893 }
5894
5895 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005896 // as long as there are effects we should clear the effects buffer, to avoid
5897 // passing a non-clean buffer to the effect chain
5898 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02005899 if (mType == SPATIALIZER) {
5900 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
5901 }
Eric Laurent97d547d2014-09-02 14:45:53 -07005902 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005903 // sink or mix buffer must be cleared if all tracks are connected to an
5904 // effect chain as in this case the mixer will not write to the sink or mix buffer
5905 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02005906 // always clear sink buffer for spatializer output as the output of the spatializer
5907 // effect will be accumulated into it
5908 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5909 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005910 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005911 if (mMixerBufferValid) {
5912 memset(mMixerBuffer, 0, mMixerBufferSize);
5913 // TODO: In testing, mSinkBuffer below need not be cleared because
5914 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5915 // after mixing.
5916 //
5917 // To enforce this guarantee:
5918 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5919 // (mixedTracks == 0 && fastTracks > 0))
5920 // must imply MIXER_TRACKS_READY.
5921 // Later, we may clear buffers regardless, and skip much of this logic.
5922 }
Andy Hung98ef9782014-03-04 14:46:50 -08005923 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005924 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005925 }
5926
5927 // if any fast tracks, then status is ready
5928 mMixerStatusIgnoringFastTracks = mixerStatus;
5929 if (fastTracks > 0) {
5930 mixerStatus = MIXER_TRACKS_READY;
5931 }
5932 return mixerStatus;
5933}
5934
Eric Laurentad7dd962016-09-22 12:38:37 -07005935// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005936uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005937{
5938 uint32_t trackCount = 0;
5939 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005940 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005941 trackCount++;
5942 }
5943 }
5944 return trackCount;
5945}
5946
Brian Lindahl9e661ad2022-07-27 18:01:07 +02005947bool AudioFlinger::PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut * output)
ziyangch8f194f12021-12-01 13:48:04 -08005948{
Brian Lindahl9e661ad2022-07-27 18:01:07 +02005949 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
5950 // could falsely detect that the frame position has stalled due to underrun because we haven't
5951 // given the Audio HAL enough time to update.
5952 const nsecs_t nowNs = systemTime();
5953 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
5954 return mLatchedValue;
5955 }
5956 mPreviousNs = nowNs;
5957 mLatchedValue = false;
5958 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08005959 uint64_t position = 0;
5960 struct timespec unused;
Brian Lindahl9e661ad2022-07-27 18:01:07 +02005961 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08005962 if (ret == NO_ERROR) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02005963 if (position != mPreviousPosition) {
5964 mPreviousPosition = position;
5965 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08005966 }
5967 }
Brian Lindahl9e661ad2022-07-27 18:01:07 +02005968 return mLatchedValue;
5969}
5970
5971void AudioFlinger::PlaybackThread::IsTimestampAdvancing::clear()
5972{
5973 mLatchedValue = true;
5974 mPreviousPosition = 0;
5975 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08005976}
5977
Andy Hung1bc088a2018-02-09 15:57:31 -08005978// isTrackAllowed_l() must be called with ThreadBase::mLock held
5979bool AudioFlinger::MixerThread::isTrackAllowed_l(
5980 audio_channel_mask_t channelMask, audio_format_t format,
5981 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005982{
Andy Hung1bc088a2018-02-09 15:57:31 -08005983 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5984 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005985 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005986 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005987 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005988 ALOGW("%s: invalid format: %#x", __func__, format);
5989 return false;
5990 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005991 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005992 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5993 return false;
5994 }
5995 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005996}
5997
Eric Laurent10351942014-05-08 18:49:52 -07005998// checkForNewParameter_l() must be called with ThreadBase::mLock held
5999bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
6000 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006001{
Eric Laurent81784c32012-11-19 14:55:58 -08006002 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006003 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006004
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006005 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006006
Eric Laurent10351942014-05-08 18:49:52 -07006007 AudioParameter param = AudioParameter(keyValuePair);
6008 int value;
6009 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6010 reconfig = true;
6011 }
6012 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07006013 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006014 status = BAD_VALUE;
6015 } else {
6016 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006017 reconfig = true;
6018 }
Eric Laurent10351942014-05-08 18:49:52 -07006019 }
6020 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07006021 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006022 status = BAD_VALUE;
6023 } else {
6024 // no need to save value, since it's constant
6025 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006026 }
Eric Laurent10351942014-05-08 18:49:52 -07006027 }
6028 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6029 // do not accept frame count changes if tracks are open as the track buffer
6030 // size depends on frame count and correct behavior would not be guaranteed
6031 // if frame count is changed after track creation
6032 if (!mTracks.isEmpty()) {
6033 status = INVALID_OPERATION;
6034 } else {
6035 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006036 }
Eric Laurent10351942014-05-08 18:49:52 -07006037 }
6038 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006039 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006040 }
Eric Laurent81784c32012-11-19 14:55:58 -08006041
Eric Laurent10351942014-05-08 18:49:52 -07006042 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006043 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006044 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006045 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006046 if (!mStandby) {
6047 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006048 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07006049 mStandby = true;
6050 }
Eric Laurent10351942014-05-08 18:49:52 -07006051 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006052 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006053 }
Eric Laurent10351942014-05-08 18:49:52 -07006054 if (status == NO_ERROR && reconfig) {
6055 readOutputParameters_l();
6056 delete mAudioMixer;
6057 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006058 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006059 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08006060 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006061 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08006062 track->mChannelMask,
6063 track->mFormat,
6064 track->mSessionId);
6065 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006066 "%s(): AudioMixer cannot create track(%d)"
6067 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006068 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07006069 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07006070 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006071 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006072 }
Eric Laurent81784c32012-11-19 14:55:58 -08006073 }
6074
Dean Wheatley68918102021-03-19 22:09:19 +11006075 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006076}
6077
6078
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006079void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006080{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006081 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006082 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006083 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006084 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006085 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6086 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6087 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006088 if (hasFastMixer()) {
6089 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6090
6091 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6092 // while we are dumping it. It may be inconsistent, but it won't mutate!
6093 // This is a large object so we place it on the heap.
6094 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006095 const std::unique_ptr<FastMixerDumpState> copy =
6096 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006097 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006098
6099#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006100 // Similar for state queue
6101 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6102 observerCopy.dump(fd);
6103 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6104 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006105#endif
6106
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006107#ifdef AUDIO_WATCHDOG
6108 if (mAudioWatchdog != 0) {
6109 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6110 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6111 wdCopy.dump(fd);
6112 }
6113#endif
6114
6115 } else {
6116 dprintf(fd, " No FastMixer\n");
6117 }
Eric Laurent81784c32012-11-19 14:55:58 -08006118}
6119
6120uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
6121{
6122 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6123}
6124
6125uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
6126{
6127 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6128}
6129
6130void AudioFlinger::MixerThread::cacheParameters_l()
6131{
6132 PlaybackThread::cacheParameters_l();
6133
6134 // FIXME: Relaxed timing because of a certain device that can't meet latency
6135 // Should be reduced to 2x after the vendor fixes the driver issue
6136 // increase threshold again due to low power audio mode. The way this warning
6137 // threshold is calculated and its usefulness should be reconsidered anyway.
6138 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6139}
6140
6141// ----------------------------------------------------------------------------
6142
6143AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Gareth Fenn56576722022-10-05 13:42:36 -07006144 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6145 const audio_offload_info_t& offloadInfo)
jiabinc52b1ff2019-10-31 17:20:42 -07006146 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Gareth Fenn56576722022-10-05 13:42:36 -07006147 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006148{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006149 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006150}
6151
Eric Laurent81784c32012-11-19 14:55:58 -08006152AudioFlinger::DirectOutputThread::~DirectOutputThread()
6153{
6154}
6155
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006156void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006157{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006158 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006159 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6160 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6161}
6162
6163void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
6164{
6165 Mutex::Autolock _l(mLock);
6166 if (mMasterBalance != balance) {
6167 mMasterBalance.store(balance);
6168 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6169 broadcast_l();
6170 }
6171}
6172
Eric Laurent5850c4c2016-11-10 13:04:31 -08006173void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006174{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006175 float left, right;
6176
Andy Hung333ab962019-05-28 20:23:35 -07006177 // Ensure volumeshaper state always advances even when muted.
6178 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
6179 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
6180 proxy->framesReleased());
6181 mVolumeShaperActive = shaperActive;
6182
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006183 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006184 left = right = 0;
6185 } else {
6186 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006187 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006188
Glenn Kastenc56f3422014-03-21 17:53:17 -07006189 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6190 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6191 if (left > GAIN_FLOAT_UNITY) {
6192 left = GAIN_FLOAT_UNITY;
6193 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006194 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07006195 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6196 if (right > GAIN_FLOAT_UNITY) {
6197 right = GAIN_FLOAT_UNITY;
6198 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006199 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006200 }
6201
6202 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07006203 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006204 if (left != mLeftVolFloat || right != mRightVolFloat) {
6205 mLeftVolFloat = left;
6206 mRightVolFloat = right;
6207
Eric Laurentbfb1b832013-01-07 09:53:42 -08006208 // Delegate volume control to effect in track effect chain if needed
6209 // only one effect chain can be present on DirectOutputThread, so if
6210 // there is one, the track is connected to it
6211 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006212 // if effect chain exists, volume is handled by it.
6213 // Convert volumes from float to 8.24
6214 uint32_t vl = (uint32_t)(left * (1 << 24));
6215 uint32_t vr = (uint32_t)(right * (1 << 24));
6216 // Direct/Offload effect chains set output volume in setVolume_l().
6217 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6218 } else {
6219 // otherwise we directly set the volume.
6220 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006221 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006222 }
6223 }
6224}
6225
Phil Burk43b4dcc2015-06-09 16:53:44 -07006226void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
6227{
6228 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07006229 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006230
Eric Laurent0f0631e2015-07-06 18:01:25 -07006231 if (previousTrack != 0 && latestTrack != 0) {
6232 if (mType == DIRECT) {
6233 if (previousTrack.get() != latestTrack.get()) {
6234 mFlushPending = true;
6235 }
6236 } else /* mType == OFFLOAD */ {
6237 if (previousTrack->sessionId() != latestTrack->sessionId()) {
6238 mFlushPending = true;
6239 }
6240 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006241 } else if (previousTrack == 0) {
6242 // there could be an old track added back during track transition for direct
6243 // output, so always issues flush to flush data of the previous track if it
6244 // was already destroyed with HAL paused, then flush can resume the playback
6245 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006246 }
6247 PlaybackThread::onAddNewTrack_l();
6248}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006249
Eric Laurent81784c32012-11-19 14:55:58 -08006250AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
6251 Vector< sp<Track> > *tracksToRemove
6252)
6253{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006254 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006255 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006256 bool doHwPause = false;
6257 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006258
6259 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006260 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006261 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006262 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006263 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006264 continue;
6265 }
6266
Eric Laurent5850c4c2016-11-10 13:04:31 -08006267 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006268#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006269 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006270#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006271 // Only consider last track started for volume and mixer state control.
6272 // In theory an older track could underrun and restart after the new one starts
6273 // but as we only care about the transition phase between two tracks on a
6274 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006275 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006276 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006277
Kuowei Li23666472021-01-20 10:23:25 +08006278 if (track->isPausePending()) {
6279 track->pauseAck();
6280 // It is possible a track might have been flushed or stopped.
6281 // Other operations such as flush pending might occur on the next prepare.
6282 if (track->isPausing()) {
6283 track->setPaused();
6284 }
6285 // Always perform pause, as an immediate flush will change
6286 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006287 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006288 doHwPause = true;
6289 mHwPaused = true;
6290 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006291 } else if (track->isFlushPending()) {
6292 track->flushAck();
6293 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006294 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006295 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006296 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006297 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006298 if (last) {
6299 mLeftVolFloat = mRightVolFloat = -1.0;
6300 if (mHwPaused) {
6301 doHwResume = true;
6302 mHwPaused = false;
6303 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006304 }
6305 }
6306
Eric Laurent81784c32012-11-19 14:55:58 -08006307 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006308 // for all its buffers to be filled before processing it.
6309 // Allow draining the buffer in case the client
6310 // app does not call stop() and relies on underrun to stop:
6311 // hence the test on (track->mRetryCount > 1).
Andy Hung455982f2021-04-27 17:46:12 -07006312 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
6313 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6314 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006315 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006316
6317 // target retry count that we will use is based on the time we wait for retries.
6318 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6319 // the retry threshold is when we accept any size for PCM data. This is slightly
6320 // smaller than the retry count so we can push small bits of data without a glitch.
6321 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006322 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006323 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung455982f2021-04-27 17:46:12 -07006324 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006325 minFrames = mNormalFrameCount;
6326 } else {
6327 minFrames = 1;
6328 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006329
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006330 const size_t framesReady = track->framesReady();
6331 const int trackId = track->id();
6332 if (ATRACE_ENABLED()) {
6333 std::string traceName("nRdy");
6334 traceName += std::to_string(trackId);
6335 ATRACE_INT(traceName.c_str(), framesReady);
6336 }
6337 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006338 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006339 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006340 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006341
6342 if (track->mFillingUpStatus == Track::FS_FILLED) {
6343 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006344 if (last) {
6345 // make sure processVolume_l() will apply new volume even if 0
6346 mLeftVolFloat = mRightVolFloat = -1.0;
6347 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006348 if (!mHwSupportsPause) {
6349 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006350 }
6351 }
6352
6353 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006354 processVolume_l(track, last);
6355 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006356 sp<Track> previousTrack = mPreviousTrack.promote();
6357 if (previousTrack != 0) {
6358 if (track != previousTrack.get()) {
6359 // Flush any data still being written from last track
6360 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006361 // Invalidate previous track to force a seek when resuming.
6362 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006363 }
6364 }
6365 mPreviousTrack = track;
6366
Eric Laurentd595b7c2013-04-03 17:27:56 -07006367 // reset retry count
Andy Hung455982f2021-04-27 17:46:12 -07006368 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006369 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006370 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006371 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006372 doHwResume = true;
6373 mHwPaused = false;
6374 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006375 }
Eric Laurent81784c32012-11-19 14:55:58 -08006376 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006377 // clear effect chain input buffer if the last active track started underruns
6378 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006379 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006380 mEffectChains[0]->clearInputBuffer();
6381 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006382 if (track->isStopping_1()) {
6383 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07006384 if (last && mHwPaused) {
6385 doHwResume = true;
6386 mHwPaused = false;
6387 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006388 }
6389 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6390 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006391 // We have consumed all the buffers of this track.
6392 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006393 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006394 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006395 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006396 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006397 if (presComplete) {
6398 mOutput->presentationComplete();
6399 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006400 if (track->isStopping_2()) {
6401 track->mState = TrackBase::STOPPED;
6402 }
Eric Laurent81784c32012-11-19 14:55:58 -08006403 if (track->isStopped()) {
6404 track->reset();
6405 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006406 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006407 }
6408 } else {
6409 // No buffers for this track. Give it a few chances to
6410 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006411 // Only consider last track started for mixer state control
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006412 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07006413 if (!isTunerStream() // tuner streams remain active in underrun
6414 && --(track->mRetryCount) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006415 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
ziyangch8f194f12021-12-01 13:48:04 -08006416 track->mRetryCount = kMaxTrackRetriesOffload;
6417 } else {
6418 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6419 tracksToRemove->add(track);
6420 // indicate to client process that the track was disabled because of
6421 // underrun; it will then automatically call start() when data is available
6422 track->disable();
6423 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6424 // unlike mixerthread, HAL can be paused for direct output
6425 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6426 "minFrames = %u, mFormat = %#x",
6427 framesReady, minFrames, mFormat);
6428 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6429 doHwPause = true;
6430 mHwPaused = true;
6431 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006432 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006433 } else if (last) {
6434 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006435 }
6436 }
6437 }
6438 }
6439
Eric Laurentd1f69b02014-12-15 14:33:13 -08006440 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006441 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006442 for (size_t i = 0; i < mTracks.size(); i++) {
6443 if (mTracks[i]->isFlushPending()) {
6444 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006445 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006446 }
6447 }
6448 }
6449
6450 // make sure the pause/flush/resume sequence is executed in the right order.
6451 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6452 // before flush and then resume HW. This can happen in case of pause/flush/resume
6453 // if resume is received before pause is executed.
6454 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006455 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006456 status_t result = mOutput->stream->pause();
6457 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006458 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006459 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006460 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006461 flushHw_l();
6462 }
6463 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006464 status_t result = mOutput->stream->resume();
6465 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006466 }
Eric Laurent81784c32012-11-19 14:55:58 -08006467 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006468 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006469
6470 return mixerStatus;
6471}
6472
6473void AudioFlinger::DirectOutputThread::threadLoop_mix()
6474{
Eric Laurent81784c32012-11-19 14:55:58 -08006475 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006476 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006477 // output audio to hardware
6478 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006479 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006480 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006481 status_t status = mActiveTrack->getNextBuffer(&buffer);
6482 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006483 // no need to pad with 0 for compressed audio
6484 if (audio_has_proportional_frames(mFormat)) {
6485 memset(curBuf, 0, frameCount * mFrameSize);
6486 }
Eric Laurent81784c32012-11-19 14:55:58 -08006487 break;
6488 }
6489 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6490 frameCount -= buffer.frameCount;
6491 curBuf += buffer.frameCount * mFrameSize;
6492 mActiveTrack->releaseBuffer(&buffer);
6493 }
Andy Hung2098f272014-02-27 14:00:06 -08006494 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006495 mSleepTimeUs = 0;
6496 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006497 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006498}
6499
6500void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6501{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006502 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006503 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006504 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006505 return;
6506 }
Andy Hung85ba3332021-04-27 17:40:26 -07006507 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6508 mSleepTimeUs = mActiveSleepTimeUs;
6509 } else {
6510 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006511 }
Andy Hung85ba3332021-04-27 17:40:26 -07006512 // Note: In S or later, we do not write zeroes for
6513 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006514}
6515
Eric Laurentd1f69b02014-12-15 14:33:13 -08006516void AudioFlinger::DirectOutputThread::threadLoop_exit()
6517{
6518 {
6519 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006520 for (size_t i = 0; i < mTracks.size(); i++) {
6521 if (mTracks[i]->isFlushPending()) {
6522 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006523 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006524 }
6525 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006526 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006527 flushHw_l();
6528 }
6529 }
6530 PlaybackThread::threadLoop_exit();
6531}
6532
6533// must be called with thread mutex locked
6534bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6535{
6536 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006537 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006538
6539 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6540 // after a timeout and we will enter standby then.
6541 if (mTracks.size() > 0) {
6542 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006543 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6544 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006545 }
6546
Eric Laurent5cff4032015-05-26 13:49:58 -07006547 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006548}
6549
Eric Laurent10351942014-05-08 18:49:52 -07006550// checkForNewParameter_l() must be called with ThreadBase::mLock held
6551bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6552 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006553{
6554 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006555 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006556
Eric Laurent10351942014-05-08 18:49:52 -07006557 AudioParameter param = AudioParameter(keyValuePair);
6558 int value;
6559 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006560 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006561 }
Eric Laurent10351942014-05-08 18:49:52 -07006562 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6563 // do not accept frame count changes if tracks are open as the track buffer
6564 // size depends on frame count and correct behavior would not be garantied
6565 // if frame count is changed after track creation
6566 if (!mTracks.isEmpty()) {
6567 status = INVALID_OPERATION;
6568 } else {
6569 reconfig = true;
6570 }
6571 }
6572 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006573 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006574 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006575 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006576 if (!mStandby) {
6577 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006578 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07006579 mStandby = true;
6580 }
Eric Laurent10351942014-05-08 18:49:52 -07006581 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006582 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006583 }
6584 if (status == NO_ERROR && reconfig) {
6585 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006586 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006587 }
6588 }
6589
Dean Wheatley68918102021-03-19 22:09:19 +11006590 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006591}
6592
6593uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6594{
6595 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006596 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006597 time = PlaybackThread::activeSleepTimeUs();
6598 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006599 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006600 }
6601 return time;
6602}
6603
6604uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6605{
6606 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006607 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006608 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6609 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006610 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006611 }
6612 return time;
6613}
6614
6615uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6616{
6617 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006618 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006619 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6620 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006621 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006622 }
6623 return time;
6624}
6625
6626void AudioFlinger::DirectOutputThread::cacheParameters_l()
6627{
6628 PlaybackThread::cacheParameters_l();
6629
6630 // use shorter standby delay as on normal output to release
6631 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006632 // no delay on outputs with HW A/V sync
6633 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006634 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006635 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006636 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006637 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006638 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006639 }
Eric Laurent81784c32012-11-19 14:55:58 -08006640}
6641
Eric Laurente659ef42014-09-29 13:06:46 -07006642void AudioFlinger::DirectOutputThread::flushHw_l()
6643{
ziyangch8f194f12021-12-01 13:48:04 -08006644 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08006645 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006646 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006647 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006648 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006649 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006650}
6651
Andy Hung10cbff12017-02-21 17:30:14 -08006652int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6653 // If a VolumeShaper is active, we must wake up periodically to update volume.
6654 const int64_t NS_PER_MS = 1000000;
6655 return mVolumeShaperActive ?
6656 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6657}
6658
Eric Laurent81784c32012-11-19 14:55:58 -08006659// ----------------------------------------------------------------------------
6660
Eric Laurentbfb1b832013-01-07 09:53:42 -08006661AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006662 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006663 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006664 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006665 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006666 mDrainSequence(0),
6667 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006668{
6669}
6670
6671AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6672{
6673}
6674
6675void AudioFlinger::AsyncCallbackThread::onFirstRef()
6676{
6677 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6678}
6679
6680bool AudioFlinger::AsyncCallbackThread::threadLoop()
6681{
6682 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006683 uint32_t writeAckSequence;
6684 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006685 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006686
6687 {
6688 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006689 while (!((mWriteAckSequence & 1) ||
6690 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006691 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006692 exitPending())) {
6693 mWaitWorkCV.wait(mLock);
6694 }
6695
Eric Laurentbfb1b832013-01-07 09:53:42 -08006696 if (exitPending()) {
6697 break;
6698 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006699 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6700 mWriteAckSequence, mDrainSequence);
6701 writeAckSequence = mWriteAckSequence;
6702 mWriteAckSequence &= ~1;
6703 drainSequence = mDrainSequence;
6704 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006705 asyncError = mAsyncError;
6706 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006707 }
6708 {
Eric Laurent4de95592013-09-26 15:28:21 -07006709 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6710 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006711 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006712 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006713 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006714 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006715 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006716 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006717 if (asyncError) {
6718 playbackThread->onAsyncError();
6719 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006720 }
6721 }
6722 }
6723 return false;
6724}
6725
6726void AudioFlinger::AsyncCallbackThread::exit()
6727{
6728 ALOGV("AsyncCallbackThread::exit");
6729 Mutex::Autolock _l(mLock);
6730 requestExit();
6731 mWaitWorkCV.broadcast();
6732}
6733
Eric Laurent3b4529e2013-09-05 18:09:19 -07006734void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006735{
6736 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006737 // bit 0 is cleared
6738 mWriteAckSequence = sequence << 1;
6739}
6740
6741void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6742{
6743 Mutex::Autolock _l(mLock);
6744 // ignore unexpected callbacks
6745 if (mWriteAckSequence & 2) {
6746 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006747 mWaitWorkCV.signal();
6748 }
6749}
6750
Eric Laurent3b4529e2013-09-05 18:09:19 -07006751void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006752{
6753 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006754 // bit 0 is cleared
6755 mDrainSequence = sequence << 1;
6756}
6757
6758void AudioFlinger::AsyncCallbackThread::resetDraining()
6759{
6760 Mutex::Autolock _l(mLock);
6761 // ignore unexpected callbacks
6762 if (mDrainSequence & 2) {
6763 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006764 mWaitWorkCV.signal();
6765 }
6766}
6767
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006768void AudioFlinger::AsyncCallbackThread::setAsyncError()
6769{
6770 Mutex::Autolock _l(mLock);
6771 mAsyncError = true;
6772 mWaitWorkCV.signal();
6773}
6774
Eric Laurentbfb1b832013-01-07 09:53:42 -08006775
6776// ----------------------------------------------------------------------------
6777AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Gareth Fenn56576722022-10-05 13:42:36 -07006778 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6779 const audio_offload_info_t& offloadInfo)
6780 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08006781 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006782{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006783 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006784 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006785 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006786}
6787
Eric Laurentbfb1b832013-01-07 09:53:42 -08006788void AudioFlinger::OffloadThread::threadLoop_exit()
6789{
6790 if (mFlushPending || mHwPaused) {
6791 // If a flush is pending or track was paused, just discard buffered data
6792 flushHw_l();
6793 } else {
6794 mMixerStatus = MIXER_DRAIN_ALL;
6795 threadLoop_drain();
6796 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006797 if (mUseAsyncWrite) {
6798 ALOG_ASSERT(mCallbackThread != 0);
6799 mCallbackThread->exit();
6800 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006801 PlaybackThread::threadLoop_exit();
6802}
6803
6804AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6805 Vector< sp<Track> > *tracksToRemove
6806)
6807{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006808 size_t count = mActiveTracks.size();
6809
6810 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006811 bool doHwPause = false;
6812 bool doHwResume = false;
6813
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006814 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006815
Eric Laurentbfb1b832013-01-07 09:53:42 -08006816 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006817 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006818 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006819#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006820 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006821#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006822 // Only consider last track started for volume and mixer state control.
6823 // In theory an older track could underrun and restart after the new one starts
6824 // but as we only care about the transition phase between two tracks on a
6825 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006826 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006827 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006828
Haynes Mathew George7844f672014-01-15 12:32:55 -08006829 if (track->isInvalid()) {
6830 ALOGW("An invalidated track shouldn't be in active list");
6831 tracksToRemove->add(track);
6832 continue;
6833 }
6834
6835 if (track->mState == TrackBase::IDLE) {
6836 ALOGW("An idle track shouldn't be in active list");
6837 continue;
6838 }
6839
Kuowei Li23666472021-01-20 10:23:25 +08006840 if (track->isPausePending()) {
6841 track->pauseAck();
6842 // It is possible a track might have been flushed or stopped.
6843 // Other operations such as flush pending might occur on the next prepare.
6844 if (track->isPausing()) {
6845 track->setPaused();
6846 }
6847 // Always perform pause if last, as an immediate flush will change
6848 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006849 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006850 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006851 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006852 mHwPaused = true;
6853 }
6854 // If we were part way through writing the mixbuffer to
6855 // the HAL we must save this until we resume
6856 // BUG - this will be wrong if a different track is made active,
6857 // in that case we want to discard the pending data in the
6858 // mixbuffer and tell the client to present it again when the
6859 // track is resumed
6860 mPausedWriteLength = mCurrentWriteLength;
6861 mPausedBytesRemaining = mBytesRemaining;
6862 mBytesRemaining = 0; // stop writing
6863 }
6864 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006865 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006866 if (track->isStopping_1()) {
6867 track->mRetryCount = kMaxTrackStopRetriesOffload;
6868 } else {
6869 track->mRetryCount = kMaxTrackRetriesOffload;
6870 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006871 track->flushAck();
6872 if (last) {
6873 mFlushPending = true;
6874 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006875 } else if (track->isResumePending()){
6876 track->resumeAck();
6877 if (last) {
6878 if (mPausedBytesRemaining) {
6879 // Need to continue write that was interrupted
6880 mCurrentWriteLength = mPausedWriteLength;
6881 mBytesRemaining = mPausedBytesRemaining;
6882 mPausedBytesRemaining = 0;
6883 }
6884 if (mHwPaused) {
6885 doHwResume = true;
6886 mHwPaused = false;
6887 // threadLoop_mix() will handle the case that we need to
6888 // resume an interrupted write
6889 }
6890 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006891 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006892
Eric Laurent3df841a2016-07-15 15:15:40 -07006893 mLeftVolFloat = mRightVolFloat = -1.0;
6894
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006895 // Do not handle new data in this iteration even if track->framesReady()
6896 mixerStatus = MIXER_TRACKS_ENABLED;
6897 }
6898 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006899 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006900 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006901 if (track->mFillingUpStatus == Track::FS_FILLED) {
6902 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006903 if (last) {
6904 // make sure processVolume_l() will apply new volume even if 0
6905 mLeftVolFloat = mRightVolFloat = -1.0;
6906 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006907 }
6908
6909 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006910 sp<Track> previousTrack = mPreviousTrack.promote();
6911 if (previousTrack != 0) {
6912 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006913 // Flush any data still being written from last track
6914 mBytesRemaining = 0;
6915 if (mPausedBytesRemaining) {
6916 // Last track was paused so we also need to flush saved
6917 // mixbuffer state and invalidate track so that it will
6918 // re-submit that unwritten data when it is next resumed
6919 mPausedBytesRemaining = 0;
6920 // Invalidate is a bit drastic - would be more efficient
6921 // to have a flag to tell client that some of the
6922 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006923 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006924 }
6925 // flush data already sent to the DSP if changing audio session as audio
6926 // comes from a different source. Also invalidate previous track to force a
6927 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006928 if (previousTrack->sessionId() != track->sessionId()) {
6929 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006930 }
6931 }
6932 }
6933 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006934 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006935 if (track->isStopping_1()) {
6936 track->mRetryCount = kMaxTrackStopRetriesOffload;
6937 } else {
6938 track->mRetryCount = kMaxTrackRetriesOffload;
6939 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006940 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006941 mixerStatus = MIXER_TRACKS_READY;
6942 }
6943 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006944 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006945 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006946 if (--(track->mRetryCount) <= 0) {
6947 // Hardware buffer can hold a large amount of audio so we must
6948 // wait for all current track's data to drain before we say
6949 // that the track is stopped.
6950 if (mBytesRemaining == 0) {
6951 // Only start draining when all data in mixbuffer
6952 // has been written
6953 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6954 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6955 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6956 if (last && !mStandby) {
6957 // do not modify drain sequence if we are already draining. This happens
6958 // when resuming from pause after drain.
6959 if ((mDrainSequence & 1) == 0) {
6960 mSleepTimeUs = 0;
6961 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6962 mixerStatus = MIXER_DRAIN_TRACK;
6963 mDrainSequence += 2;
6964 }
6965 if (mHwPaused) {
6966 // It is possible to move from PAUSED to STOPPING_1 without
6967 // a resume so we must ensure hardware is running
6968 doHwResume = true;
6969 mHwPaused = false;
6970 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006971 }
6972 }
Eric Laurente93cc032016-05-05 10:15:10 -07006973 } else if (last) {
6974 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6975 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006976 }
6977 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006978 // Drain has completed or we are in standby, signal presentation complete
6979 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006980 track->mState = TrackBase::STOPPED;
Atneya Nair0cae0432022-05-10 18:12:12 -04006981 mOutput->presentationComplete();
6982 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08006983 track->reset();
6984 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006985 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006986 if (!mUseAsyncWrite) {
6987 // If we don't get explicit drain notification we must
6988 // register discontinuity regardless of whether this is
6989 // the previous (!last) or the upcoming (last) track
6990 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006991 mTimestampVerifier.discontinuity(
6992 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006993 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006994 }
6995 } else {
6996 // No buffers for this track. Give it a few chances to
6997 // fill a buffer, then remove it from active list.
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006998 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07006999 if (!isTunerStream() // tuner streams remain active in underrun
7000 && --(track->mRetryCount) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02007001 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hungf8044752016-07-27 14:58:11 -07007002 track->mRetryCount = kMaxTrackRetriesOffload;
7003 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007004 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7005 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007006 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007007 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007008 // it will then automatically call start() when data is available
7009 track->disable();
7010 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007011 } else if (last){
7012 mixerStatus = MIXER_TRACKS_ENABLED;
7013 }
7014 }
7015 }
7016 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007017 if (track->isReady()) { // check ready to prevent premature start.
7018 processVolume_l(track, last);
7019 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007020 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007021
Eric Laurentea0fade2013-10-04 16:23:48 -07007022 // make sure the pause/flush/resume sequence is executed in the right order.
7023 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7024 // before flush and then resume HW. This can happen in case of pause/flush/resume
7025 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007026 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007027 status_t result = mOutput->stream->pause();
7028 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007029 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007030 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007031 if (mFlushPending) {
7032 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007033 }
Eric Laurentfd477972013-10-25 18:10:40 -07007034 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007035 status_t result = mOutput->stream->resume();
7036 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007037 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007038
Eric Laurentbfb1b832013-01-07 09:53:42 -08007039 // remove all the tracks that need to be...
7040 removeTracks_l(*tracksToRemove);
7041
7042 return mixerStatus;
7043}
7044
Eric Laurentbfb1b832013-01-07 09:53:42 -08007045// must be called with thread mutex locked
7046bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
7047{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007048 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7049 mWriteAckSequence, mDrainSequence);
7050 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007051 return true;
7052 }
7053 return false;
7054}
7055
Eric Laurentbfb1b832013-01-07 09:53:42 -08007056bool AudioFlinger::OffloadThread::waitingAsyncCallback()
7057{
7058 Mutex::Autolock _l(mLock);
7059 return waitingAsyncCallback_l();
7060}
7061
7062void AudioFlinger::OffloadThread::flushHw_l()
7063{
Eric Laurente659ef42014-09-29 13:06:46 -07007064 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007065 // Flush anything still waiting in the mixbuffer
7066 mCurrentWriteLength = 0;
7067 mBytesRemaining = 0;
7068 mPausedWriteLength = 0;
7069 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007070 // reset bytes written count to reflect that DSP buffers are empty after flush.
7071 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007072
Eric Laurentbfb1b832013-01-07 09:53:42 -08007073 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007074 // discard any pending drain or write ack by incrementing sequence
7075 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7076 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007077 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007078 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7079 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007080 }
7081}
7082
Haynes Mathew George05317d22016-05-03 16:34:26 -07007083void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
7084{
7085 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007086 if (PlaybackThread::invalidateTracks_l(streamType)) {
7087 mFlushPending = true;
7088 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007089}
7090
Eric Laurentbfb1b832013-01-07 09:53:42 -08007091// ----------------------------------------------------------------------------
7092
Eric Laurent81784c32012-11-19 14:55:58 -08007093AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07007094 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07007095 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007096 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007097 mWaitTimeMs(UINT_MAX)
7098{
7099 addOutputTrack(mainThread);
7100}
7101
7102AudioFlinger::DuplicatingThread::~DuplicatingThread()
7103{
7104 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7105 mOutputTracks[i]->destroy();
7106 }
7107}
7108
7109void AudioFlinger::DuplicatingThread::threadLoop_mix()
7110{
7111 // mix buffers...
7112 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007113 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007114 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007115 if (mMixerBufferValid) {
7116 memset(mMixerBuffer, 0, mMixerBufferSize);
7117 } else {
7118 memset(mSinkBuffer, 0, mSinkBufferSize);
7119 }
Eric Laurent81784c32012-11-19 14:55:58 -08007120 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007121 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007122 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007123 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007124 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007125}
7126
7127void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
7128{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007129 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007130 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007131 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007132 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007133 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007134 }
7135 } else if (mBytesWritten != 0) {
7136 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7137 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007138 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007139 } else {
7140 // flush remaining overflow buffers in output tracks
7141 writeFrames = 0;
7142 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007143 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007144 }
7145}
7146
Eric Laurentbfb1b832013-01-07 09:53:42 -08007147ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007148{
7149 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007150 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7151
7152 // Consider the first OutputTrack for timestamp and frame counting.
7153
7154 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7155 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7156 // we always claim success.
7157 if (i == 0) {
7158 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7159 ALOGD_IF(correction != 0 && writeFrames != 0,
7160 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7161 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7162 mFramesWritten -= correction;
7163 }
7164
7165 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007166 }
Andy Hungcf10d742020-04-28 15:38:24 -07007167 if (mStandby) {
7168 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007169 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007170 mStandby = false;
7171 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007172 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007173}
7174
7175void AudioFlinger::DuplicatingThread::threadLoop_standby()
7176{
7177 // DuplicatingThread implements standby by stopping all tracks
7178 for (size_t i = 0; i < outputTracks.size(); i++) {
7179 outputTracks[i]->stop();
7180 }
7181}
7182
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007183void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08007184{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007185 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007186
7187 std::stringstream ss;
7188 const size_t numTracks = mOutputTracks.size();
7189 ss << " " << numTracks << " OutputTracks";
7190 if (numTracks > 0) {
7191 ss << ":";
7192 for (const auto &track : mOutputTracks) {
7193 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007194 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007195 if (thread.get() != nullptr) {
7196 ss << thread.get() << ", " << thread->id();
7197 } else {
7198 ss << "null";
7199 }
7200 ss << ")";
7201 }
7202 }
7203 ss << "\n";
7204 std::string result = ss.str();
7205 write(fd, result.c_str(), result.size());
7206}
7207
Eric Laurent81784c32012-11-19 14:55:58 -08007208void AudioFlinger::DuplicatingThread::saveOutputTracks()
7209{
7210 outputTracks = mOutputTracks;
7211}
7212
7213void AudioFlinger::DuplicatingThread::clearOutputTracks()
7214{
7215 outputTracks.clear();
7216}
7217
7218void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
7219{
7220 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007221 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7222 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7223 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7224 const size_t frameCount =
7225 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7226 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7227 // from different OutputTracks and their associated MixerThreads (e.g. one may
7228 // nearly empty and the other may be dropping data).
7229
Svet Ganov33761132021-05-13 22:51:08 +00007230 // TODO b/182392769: use attribution source util, move to server edge
7231 AttributionSourceState attributionSource = AttributionSourceState();
7232 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007233 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007234 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007235 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007236 attributionSource.token = sp<BBinder>::make();
Andy Hungc25b84a2015-01-14 19:04:10 -08007237 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007238 this,
7239 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007240 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007241 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007242 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007243 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007244 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7245 if (status != NO_ERROR) {
7246 ALOGE("addOutputTrack() initCheck failed %d", status);
7247 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007248 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007249 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7250 mOutputTracks.add(outputTrack);
7251 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7252 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007253}
7254
7255void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
7256{
7257 Mutex::Autolock _l(mLock);
7258 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7259 if (mOutputTracks[i]->thread() == thread) {
7260 mOutputTracks[i]->destroy();
7261 mOutputTracks.removeAt(i);
7262 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007263 if (thread->getOutput() == mOutput) {
7264 mOutput = NULL;
7265 }
Eric Laurent81784c32012-11-19 14:55:58 -08007266 return;
7267 }
7268 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007269 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007270}
7271
7272// caller must hold mLock
7273void AudioFlinger::DuplicatingThread::updateWaitTime_l()
7274{
7275 mWaitTimeMs = UINT_MAX;
7276 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7277 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
7278 if (strong != 0) {
7279 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7280 if (waitTimeMs < mWaitTimeMs) {
7281 mWaitTimeMs = waitTimeMs;
7282 }
7283 }
7284 }
7285}
7286
7287
7288bool AudioFlinger::DuplicatingThread::outputsReady(
7289 const SortedVector< sp<OutputTrack> > &outputTracks)
7290{
7291 for (size_t i = 0; i < outputTracks.size(); i++) {
7292 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
7293 if (thread == 0) {
7294 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7295 outputTracks[i].get());
7296 return false;
7297 }
7298 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
7299 // see note at standby() declaration
7300 if (playbackThread->standby() && !playbackThread->isSuspended()) {
7301 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7302 thread.get());
7303 return false;
7304 }
7305 }
7306 return true;
7307}
7308
Kevin Rocard12381092018-04-11 09:19:59 -07007309void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
7310 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007311{
Kevin Rocard12381092018-04-11 09:19:59 -07007312 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7313 outputTrack->setMetadatas(metadata.tracks);
7314 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007315}
7316
Eric Laurent81784c32012-11-19 14:55:58 -08007317uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
7318{
7319 return (mWaitTimeMs * 1000) / 2;
7320}
7321
7322void AudioFlinger::DuplicatingThread::cacheParameters_l()
7323{
7324 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7325 updateWaitTime_l();
7326
7327 MixerThread::cacheParameters_l();
7328}
7329
Eric Laurentb3f315a2021-07-13 15:09:05 +02007330// ----------------------------------------------------------------------------
7331
Eric Laurentfa0f6742021-08-17 18:39:44 +02007332AudioFlinger::SpatializerThread::SpatializerThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007333 AudioStreamOut* output,
7334 audio_io_handle_t id,
7335 bool systemReady,
7336 audio_config_base_t *mixerConfig)
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007337 : MixerThread(audioFlinger, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007338{
7339}
7340
Eric Laurent6f9534f2022-05-03 18:15:04 +02007341void AudioFlinger::SpatializerThread::onFirstRef() {
7342 PlaybackThread::onFirstRef();
7343
7344 Mutex::Autolock _l(mLock);
7345 status_t status = mOutput->stream->setLatencyModeCallback(this);
7346 if (status != INVALID_OPERATION) {
7347 updateHalSupportedLatencyModes_l();
7348 }
Andy Hung6e3a3502022-10-17 19:10:02 -07007349
Andy Hungb725c692022-12-14 14:25:49 -08007350 const pid_t tid = getTid();
7351 if (tid == -1) {
7352 // Unusual: PlaybackThread::onFirstRef() should set the threadLoop running.
7353 ALOGW("%s: Cannot update Spatializer mixer thread priority, not running", __func__);
7354 } else {
7355 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
7356 if (priorityBoost > 0) {
Andy Hung6e3a3502022-10-17 19:10:02 -07007357 stream()->setHalThreadPriority(priorityBoost);
7358 }
7359 }
Eric Laurent6f9534f2022-05-03 18:15:04 +02007360}
7361
7362status_t AudioFlinger::SpatializerThread::createAudioPatch_l(const struct audio_patch *patch,
7363 audio_patch_handle_t *handle)
7364{
7365 status_t status = MixerThread::createAudioPatch_l(patch, handle);
7366 updateHalSupportedLatencyModes_l();
7367 return status;
7368}
7369
7370void AudioFlinger::SpatializerThread::updateHalSupportedLatencyModes_l() {
7371 std::vector<audio_latency_mode_t> latencyModes;
Andy Hung5d8618d2022-11-17 17:21:45 -08007372 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
7373 if (status != NO_ERROR) {
Eric Laurent6f9534f2022-05-03 18:15:04 +02007374 latencyModes.clear();
7375 }
7376 if (latencyModes != mSupportedLatencyModes) {
Andy Hung5d8618d2022-11-17 17:21:45 -08007377 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
7378 __func__, mId, status, toString(latencyModes).c_str());
Eric Laurent6f9534f2022-05-03 18:15:04 +02007379 mSupportedLatencyModes.swap(latencyModes);
7380 sendHalLatencyModesChangedEvent_l();
7381 }
7382}
7383
7384void AudioFlinger::SpatializerThread::onHalLatencyModesChanged_l() {
7385 mAudioFlinger->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
7386}
7387
7388void AudioFlinger::SpatializerThread::setHalLatencyMode_l() {
7389 // if mSupportedLatencyModes is empty, the HAL stream does not support
7390 // latency mode control and we can exit.
7391 if (mSupportedLatencyModes.empty()) {
7392 return;
7393 }
7394 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7395 if (mSupportedLatencyModes.size() == 1) {
7396 // If the HAL only support one latency mode currently, confirm the choice
7397 latencyMode = mSupportedLatencyModes[0];
7398 } else if (mSupportedLatencyModes.size() > 1) {
7399 // Request low latency if:
7400 // - The low latency mode is requested by the spatializer controller
7401 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7402 // AND
7403 // - At least one active track is spatialized
7404 bool hasSpatializedActiveTrack = false;
7405 for (const auto& track : mActiveTracks) {
7406 if (track->isSpatialized()) {
7407 hasSpatializedActiveTrack = true;
7408 break;
7409 }
7410 }
7411 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7412 latencyMode = AUDIO_LATENCY_MODE_LOW;
7413 }
7414 }
7415
7416 if (latencyMode != mSetLatencyMode) {
7417 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung5d8618d2022-11-17 17:21:45 -08007418 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7419 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent6f9534f2022-05-03 18:15:04 +02007420 if (status == NO_ERROR) {
7421 mSetLatencyMode = latencyMode;
7422 }
7423 }
7424}
7425
7426status_t AudioFlinger::SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
7427 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7428 return BAD_VALUE;
7429 }
7430 Mutex::Autolock _l(mLock);
7431 mRequestedLatencyMode = mode;
7432 return NO_ERROR;
7433}
7434
7435status_t AudioFlinger::SpatializerThread::getSupportedLatencyModes(
7436 std::vector<audio_latency_mode_t>* modes) {
7437 if (modes == nullptr) {
7438 return BAD_VALUE;
7439 }
7440 Mutex::Autolock _l(mLock);
7441 *modes = mSupportedLatencyModes;
7442 return NO_ERROR;
7443}
7444
Eric Laurent49879b72022-12-20 20:20:23 +01007445status_t AudioFlinger::PlaybackThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurent01eb1642022-12-16 11:45:07 +01007446 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
Eric Laurent49879b72022-12-20 20:20:23 +01007447 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
Eric Laurent01eb1642022-12-16 11:45:07 +01007448 return INVALID_OPERATION;
7449 }
7450 mBluetoothLatencyModesEnabled.store(enabled);
7451 return NO_ERROR;
7452}
7453
Eric Laurentfa0f6742021-08-17 18:39:44 +02007454void AudioFlinger::SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007455{
7456 bool hasVirtualizer = false;
7457 bool hasDownMixer = false;
7458 sp<EffectHandle> finalDownMixer;
7459 {
7460 Mutex::Autolock _l(mLock);
7461 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
7462 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007463 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007464 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7465 }
7466
7467 finalDownMixer = mFinalDownMixer;
7468 mFinalDownMixer.clear();
7469 }
7470
7471 if (hasVirtualizer) {
7472 if (finalDownMixer != nullptr) {
7473 int32_t ret;
7474 finalDownMixer->disable(&ret);
7475 }
7476 finalDownMixer.clear();
7477 } else if (!hasDownMixer) {
7478 std::vector<effect_descriptor_t> descriptors;
7479 status_t status = mAudioFlinger->mEffectsFactoryHal->getDescriptors(
7480 EFFECT_UIID_DOWNMIX, &descriptors);
7481 if (status != NO_ERROR) {
7482 return;
7483 }
7484 ALOG_ASSERT(!descriptors.empty(),
7485 "%s getDescriptors() returned no error but empty list", __func__);
7486
7487 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7488 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007489 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007490
7491 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7492 ALOGW("%s error creating downmixer %d", __func__, status);
7493 finalDownMixer.clear();
7494 } else {
7495 int32_t ret;
7496 finalDownMixer->enable(&ret);
7497 }
7498 }
7499
7500 {
7501 Mutex::Autolock _l(mLock);
7502 mFinalDownMixer = finalDownMixer;
7503 }
7504}
7505
Eric Laurent6f9534f2022-05-03 18:15:04 +02007506void AudioFlinger::SpatializerThread::onRecommendedLatencyModeChanged(
7507 std::vector<audio_latency_mode_t> modes) {
7508 Mutex::Autolock _l(mLock);
7509 if (modes != mSupportedLatencyModes) {
Andy Hung991405a2022-11-18 19:40:00 -08007510 ALOGD("%s: thread(%d) supported latency modes: %s",
7511 __func__, mId, toString(modes).c_str());
Eric Laurent6f9534f2022-05-03 18:15:04 +02007512 mSupportedLatencyModes.swap(modes);
7513 sendHalLatencyModesChangedEvent_l();
7514 }
7515}
Eric Laurent6acd1d42017-01-04 14:23:29 -08007516
Eric Laurent81784c32012-11-19 14:55:58 -08007517// ----------------------------------------------------------------------------
7518// Record
7519// ----------------------------------------------------------------------------
7520
7521AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
7522 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007523 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007524 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007525 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07007526 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007527 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007528 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007529 mActiveTracks(&this->mLocalLog),
7530 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007531 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007532 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007533 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7534 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007535 // mFastCapture below
7536 , mFastCaptureFutex(0)
7537 // mInputSource
7538 // mPipeSink
7539 // mPipeSource
7540 , mPipeFramesP2(0)
7541 // mPipeMemory
7542 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007543 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007544 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007545{
Glenn Kastend7dca052015-03-05 16:05:54 -08007546 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7547 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007548
George Burgess IVa8f90c12020-05-14 11:27:19 -07007549 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007550 mIsMsdDevice = strcmp(
7551 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7552 }
7553
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007554 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007555
Andy Hungc8fddf32018-08-08 18:32:37 -07007556 // TODO: We may also match on address as well as device type for
7557 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007558 // TODO: This property should be ensure that only contains one single device type.
7559 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7560 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007561 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7562 : AUDIO_DEVICE_NONE));
7563
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007564 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007565 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007566 size_t numCounterOffers = 0;
7567 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007568#if !LOG_NDEBUG
7569 ssize_t index =
7570#else
7571 (void)
7572#endif
7573 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007574 ALOG_ASSERT(index == 0);
7575
7576 // initialize fast capture depending on configuration
7577 bool initFastCapture;
7578 switch (kUseFastCapture) {
7579 case FastCapture_Never:
7580 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007581 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007582 break;
7583 case FastCapture_Always:
7584 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007585 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007586 break;
7587 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007588 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
7589 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7590 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d "
7591 "mIsMsdDevice = %d", this, (long long)mFrameCount, mSampleRate,
7592 kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007593 break;
7594 // case FastCapture_Dynamic:
7595 }
7596
7597 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007598 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007599 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007600 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7601 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007602 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007603 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007604 const sp<MemoryDealer> roHeap(readOnlyHeap());
7605 sp<IMemory> pipeMemory;
7606 if ((roHeap == 0) ||
7607 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007608 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007609 ALOGE("not enough memory for pipe buffer size=%zu; "
7610 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7611 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7612 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007613 goto failed;
7614 }
7615 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7616 memset(pipeBuffer, 0, pipeSize);
7617 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7618 const NBAIO_Format offers[1] = {format};
7619 size_t numCounterOffers = 0;
7620 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7621 ALOG_ASSERT(index == 0);
7622 mPipeSink = pipe;
7623 PipeReader *pipeReader = new PipeReader(*pipe);
7624 numCounterOffers = 0;
7625 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7626 ALOG_ASSERT(index == 0);
7627 mPipeSource = pipeReader;
7628 mPipeFramesP2 = pipeFramesP2;
7629 mPipeMemory = pipeMemory;
7630
7631 // create fast capture
7632 mFastCapture = new FastCapture();
7633 FastCaptureStateQueue *sq = mFastCapture->sq();
7634#ifdef STATE_QUEUE_DUMP
7635 // FIXME
7636#endif
7637 FastCaptureState *state = sq->begin();
7638 state->mCblk = NULL;
7639 state->mInputSource = mInputSource.get();
7640 state->mInputSourceGen++;
7641 state->mPipeSink = pipe;
7642 state->mPipeSinkGen++;
7643 state->mFrameCount = mFrameCount;
7644 state->mCommand = FastCaptureState::COLD_IDLE;
7645 // already done in constructor initialization list
7646 //mFastCaptureFutex = 0;
7647 state->mColdFutexAddr = &mFastCaptureFutex;
7648 state->mColdGen++;
7649 state->mDumpState = &mFastCaptureDumpState;
7650#ifdef TEE_SINK
7651 // FIXME
7652#endif
7653 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7654 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7655 sq->end();
7656 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7657
7658 // start the fast capture
7659 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7660 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007661 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007662 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007663#ifdef AUDIO_WATCHDOG
7664 // FIXME
7665#endif
7666
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007667 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007668 }
Andy Hung8946a282018-04-19 20:04:56 -07007669#ifdef TEE_SINK
7670 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7671 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7672#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007673failed: ;
7674
7675 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007676}
7677
Eric Laurent81784c32012-11-19 14:55:58 -08007678AudioFlinger::RecordThread::~RecordThread()
7679{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007680 if (mFastCapture != 0) {
7681 FastCaptureStateQueue *sq = mFastCapture->sq();
7682 FastCaptureState *state = sq->begin();
7683 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7684 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7685 if (old == -1) {
7686 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7687 }
7688 }
7689 state->mCommand = FastCaptureState::EXIT;
7690 sq->end();
7691 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7692 mFastCapture->join();
7693 mFastCapture.clear();
7694 }
7695 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007696 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007697 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007698}
7699
7700void AudioFlinger::RecordThread::onFirstRef()
7701{
Glenn Kastend7dca052015-03-05 16:05:54 -08007702 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007703}
7704
Eric Laurent555530a2017-02-07 18:17:24 -08007705void AudioFlinger::RecordThread::preExit()
7706{
7707 ALOGV(" preExit()");
7708 Mutex::Autolock _l(mLock);
7709 for (size_t i = 0; i < mTracks.size(); i++) {
7710 sp<RecordTrack> track = mTracks[i];
7711 track->invalidate();
7712 }
7713 mActiveTracks.clear();
7714 mStartStopCond.broadcast();
7715}
7716
Eric Laurent81784c32012-11-19 14:55:58 -08007717bool AudioFlinger::RecordThread::threadLoop()
7718{
Eric Laurent81784c32012-11-19 14:55:58 -08007719 nsecs_t lastWarning = 0;
7720
7721 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007722
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007723reacquire_wakelock:
7724 sp<RecordTrack> activeTrack;
7725 {
7726 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007727 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007728 }
7729
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007730 // used to request a deferred sleep, to be executed later while mutex is unlocked
7731 uint32_t sleepUs = 0;
7732
Andy Hung446f4df2019-02-21 12:26:41 -08007733 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7734
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007735 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007736 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007737 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007738
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007739 // activeTracks accumulates a copy of a subset of mActiveTracks
7740 Vector< sp<RecordTrack> > activeTracks;
7741
Glenn Kasten735f45f2014-08-18 15:51:59 -07007742 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007743 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007744
Glenn Kasten735f45f2014-08-18 15:51:59 -07007745 // reference to a fast track which is about to be removed
7746 sp<RecordTrack> fastTrackToRemove;
7747
Eric Laurent33403f02020-05-29 18:35:06 -07007748 bool silenceFastCapture = false;
7749
Eric Laurent81784c32012-11-19 14:55:58 -08007750 { // scope for mLock
7751 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007752
Eric Laurent021cf962014-05-13 10:18:14 -07007753 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007754
Eric Laurent000a4192014-01-29 15:17:32 -08007755 // check exitPending here because checkForNewParameters_l() and
7756 // checkForNewParameters_l() can temporarily release mLock
7757 if (exitPending()) {
7758 break;
7759 }
7760
Eric Laurent5c25d562016-07-13 17:17:45 -07007761 // sleep with mutex unlocked
7762 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007763 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007764 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7765 ATRACE_END();
7766 sleepUs = 0;
7767 continue;
7768 }
7769
Glenn Kasten2b806402013-11-20 16:37:38 -08007770 // if no active track(s), then standby and release wakelock
7771 size_t size = mActiveTracks.size();
7772 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007773 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007774 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007775 releaseWakeLock_l();
7776 ALOGV("RecordThread: loop stopping");
7777 // go to sleep
7778 mWaitWorkCV.wait(mLock);
7779 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007780 goto reacquire_wakelock;
7781 }
7782
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007783 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007784 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007785 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007786
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007787 activeTrack = mActiveTracks[i];
7788 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007789 if (activeTrack->isFastTrack()) {
7790 ALOG_ASSERT(fastTrackToRemove == 0);
7791 fastTrackToRemove = activeTrack;
7792 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007793 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007794 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007795 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007796 continue;
7797 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007798
7799 TrackBase::track_state activeTrackState = activeTrack->mState;
7800 switch (activeTrackState) {
7801
7802 case TrackBase::PAUSING:
7803 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007804 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007805 doBroadcast = true;
7806 size--;
7807 continue;
7808
7809 case TrackBase::STARTING_1:
7810 sleepUs = 10000;
7811 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007812 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007813 continue;
7814
7815 case TrackBase::STARTING_2:
7816 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007817 if (mStandby) {
7818 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007819 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007820 mStandby = false;
7821 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007822 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007823 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007824 break;
7825
7826 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007827 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007828 break;
7829
Andy Hungce685402018-10-05 17:23:27 -07007830 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7831 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7832 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007833 default:
Andy Hungce685402018-10-05 17:23:27 -07007834 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7835 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007836 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007837
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007838 if (activeTrack->isFastTrack()) {
7839 ALOG_ASSERT(!mFastTrackAvail);
7840 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007841 // if the active fast track is silenced either:
7842 // 1) silence the whole capture from fast capture buffer if this is
7843 // the only active track
7844 // 2) invalidate this track: this will cause the client to reconnect and possibly
7845 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007846 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07007847 if (activeTrack->isSilenced()) {
7848 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007849 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07007850 } else {
7851 silenceFastCapture = true;
7852 }
7853 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007854 // Invalidate fast tracks if access to audio history is required as this is not
7855 // possible with fast tracks. Once the fast track has been invalidated, no new
7856 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
7857 if (mMaxSharedAudioHistoryMs != 0) {
7858 invalidate = true;
7859 }
7860 if (invalidate) {
7861 activeTrack->invalidate();
7862 ALOG_ASSERT(fastTrackToRemove == 0);
7863 fastTrackToRemove = activeTrack;
7864 removeTrack_l(activeTrack);
7865 mActiveTracks.remove(activeTrack);
7866 size--;
7867 continue;
7868 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007869 fastTrack = activeTrack;
7870 }
Eric Laurent33403f02020-05-29 18:35:06 -07007871
7872 activeTracks.add(activeTrack);
7873 i++;
7874
Glenn Kasten9e982352013-08-14 14:39:50 -07007875 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007876
Andy Hungdae27702016-10-31 14:01:16 -07007877 mActiveTracks.updatePowerState(this);
7878
Kevin Rocard069c2712018-03-29 19:09:14 -07007879 updateMetadata_l();
7880
Eric Laurent5c25d562016-07-13 17:17:45 -07007881 if (allStopped) {
7882 standbyIfNotAlreadyInStandby();
7883 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007884 if (doBroadcast) {
7885 mStartStopCond.broadcast();
7886 }
7887
7888 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007889 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007890 if (sleepUs == 0) {
7891 sleepUs = kRecordThreadSleepUs;
7892 }
7893 continue;
7894 }
7895 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007896
Eric Laurent81784c32012-11-19 14:55:58 -08007897 lockEffectChains_l(effectChains);
7898 }
7899
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007900 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007901
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007902 size_t size = effectChains.size();
7903 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007904 // thread mutex is not locked, but effect chain is locked
7905 effectChains[i]->process_l();
7906 }
7907
Glenn Kasten735f45f2014-08-18 15:51:59 -07007908 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007909 if (mFastCapture != 0) {
7910 FastCaptureStateQueue *sq = mFastCapture->sq();
7911 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007912 bool didModify = false;
7913 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007914 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7915 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7916 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7917 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7918 if (old == -1) {
7919 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7920 }
7921 }
7922 state->mCommand = FastCaptureState::READ_WRITE;
7923#if 0 // FIXME
7924 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007925 FastThreadDumpState::kSamplingNforLowRamDevice :
7926 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007927#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007928 didModify = true;
7929 }
7930 audio_track_cblk_t *cblkOld = state->mCblk;
7931 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7932 if (cblkNew != cblkOld) {
7933 state->mCblk = cblkNew;
7934 // block until acked if removing a fast track
7935 if (cblkOld != NULL) {
7936 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7937 }
7938 didModify = true;
7939 }
jiabin01c8f562018-07-19 17:47:28 -07007940 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7941 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7942 if (state->mFastPatchRecordBufferProvider != abp) {
7943 state->mFastPatchRecordBufferProvider = abp;
7944 state->mFastPatchRecordFormat = fastTrack == 0 ?
7945 AUDIO_FORMAT_INVALID : fastTrack->format();
7946 didModify = true;
7947 }
Eric Laurent33403f02020-05-29 18:35:06 -07007948 if (state->mSilenceCapture != silenceFastCapture) {
7949 state->mSilenceCapture = silenceFastCapture;
7950 didModify = true;
7951 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007952 sq->end(didModify);
7953 if (didModify) {
7954 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007955#if 0
7956 if (kUseFastCapture == FastCapture_Dynamic) {
7957 mNormalSource = mPipeSource;
7958 }
7959#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007960 }
7961 }
7962
Glenn Kasten735f45f2014-08-18 15:51:59 -07007963 // now run the fast track destructor with thread mutex unlocked
7964 fastTrackToRemove.clear();
7965
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007966 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7967 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7968 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7969 // If destination is non-contiguous, first read past the nominal end of buffer, then
7970 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007971
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007972 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007973 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007974 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007975
7976 // If an NBAIO source is present, use it to read the normal capture's data
7977 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007978 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007979
7980 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7981 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7982 // we immediately retry the read() to get data and prevent another overflow.
7983 for (int retries = 0; retries <= 2; ++retries) {
7984 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7985 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7986 framesToRead);
7987 if (framesRead != OVERRUN) break;
7988 }
7989
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007990 const ssize_t availableToRead = mPipeSource->availableToRead();
7991 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00007992 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07007993 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007994 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7995 "more frames to read than fifo size, %zd > %zu",
7996 availableToRead, mPipeFramesP2);
7997 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7998 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7999 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8000 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008001 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8002 }
8003 if (framesRead < 0) {
8004 status_t status = (status_t) framesRead;
8005 switch (status) {
8006 case OVERRUN:
8007 ALOGW("overrun on read from pipe");
8008 framesRead = 0;
8009 break;
8010 case NEGOTIATE:
8011 ALOGE("re-negotiation is needed");
8012 framesRead = -1; // Will cause an attempt to recover.
8013 break;
8014 default:
8015 ALOGE("unknown error %d on read from pipe", status);
8016 break;
8017 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008018 }
8019 // otherwise use the HAL / AudioStreamIn directly
8020 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008021 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008022 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008023 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008024 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008025 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008026 if (result < 0) {
8027 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008028 } else {
8029 framesRead = bytesRead / mFrameSize;
8030 }
8031 }
8032
Andy Hung446f4df2019-02-21 12:26:41 -08008033 const int64_t lastIoEndNs = systemTime(); // end IO timing
8034
Andy Hung3f0c9022016-01-15 17:49:46 -08008035 // Update server timestamp with server stats
8036 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008037 if (framesRead >= 0) {
8038 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8039 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8040 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008041
8042 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008043 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008044 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008045 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008046 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8047 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8048 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008049 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008050 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8051
8052 mTimestampVerifier.add(position, time, mSampleRate);
8053
8054 // Correct timestamps
8055 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008056 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008057 id(), (long long)time, (long long)position);
8058 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8059 position = correctedTimestamp.mFrames;
8060 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008061 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008062 id(), (long long)time, (long long)position);
8063 }
8064
Andy Hung3f0c9022016-01-15 17:49:46 -08008065 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8066 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8067 // Note: In general record buffers should tend to be empty in
8068 // a properly running pipeline.
8069 //
8070 // Also, it is not advantageous to call get_presentation_position during the read
8071 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008072 } else {
8073 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008074 }
8075 }
Andy Hunge6c37112019-02-26 17:38:10 -08008076
8077 // From the timestamp, input read latency is negative output write latency.
8078 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
8079 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
8080 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8081 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8082 mLatencyMs.add(latencyMs);
8083 }
8084
Andy Hung3f0c9022016-01-15 17:49:46 -08008085 // Use this to track timestamp information
8086 // ALOGD("%s", mTimestamp.toString().c_str());
8087
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008088 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008089 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008090 // Force input into standby so that it tries to recover at next read attempt
8091 inputStandBy();
8092 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008093 }
8094 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008095 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008096 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008097 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008098 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008099
Andy Hung8946a282018-04-19 20:04:56 -07008100#ifdef TEE_SINK
8101 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8102#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008103 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008104 {
8105 size_t part1 = mRsmpInFramesP2 - rear;
8106 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008107 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008108 (framesRead - part1) * mFrameSize);
8109 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008110 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008111 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008112
8113 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008114
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008115 // loop over each active track
8116 for (size_t i = 0; i < size; i++) {
8117 activeTrack = activeTracks[i];
8118
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008119 // skip fast tracks, as those are handled directly by FastCapture
8120 if (activeTrack->isFastTrack()) {
8121 continue;
8122 }
8123
Andy Hung73c02e42015-03-29 01:13:58 -07008124 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008125 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8126
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008127 enum {
8128 OVERRUN_UNKNOWN,
8129 OVERRUN_TRUE,
8130 OVERRUN_FALSE
8131 } overrun = OVERRUN_UNKNOWN;
8132
8133 // loop over getNextBuffer to handle circular sink
8134 for (;;) {
8135
8136 activeTrack->mSink.frameCount = ~0;
8137 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
8138 size_t framesOut = activeTrack->mSink.frameCount;
8139 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8140
Andy Hung73c02e42015-03-29 01:13:58 -07008141 // check available frames and handle overrun conditions
8142 // if the record track isn't draining fast enough.
8143 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008144 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07008145 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
8146 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008147 overrun = OVERRUN_TRUE;
8148 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008149 if (framesOut == 0 || framesIn == 0) {
8150 break;
8151 }
8152
Andy Hung6770c6f2015-04-07 13:43:36 -07008153 // Don't allow framesOut to be larger than what is possible with resampling
8154 // from framesIn.
8155 // This isn't strictly necessary but helps limit buffer resizing in
8156 // RecordBufferConverter. TODO: remove when no longer needed.
8157 framesOut = min(framesOut,
8158 destinationFramesPossible(
8159 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008160
8161 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008162 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008163 // straight from RecordThread buffer to RecordTrack buffer.
8164 AudioBufferProvider::Buffer buffer;
8165 buffer.frameCount = framesOut;
8166 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
8167 if (status == OK && buffer.frameCount != 0) {
8168 ALOGV_IF(buffer.frameCount != framesOut,
8169 "%s() read less than expected (%zu vs %zu)",
8170 __func__, buffer.frameCount, framesOut);
8171 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008172 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008173 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
8174 } else {
8175 framesOut = 0;
8176 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
8177 __func__, status, buffer.frameCount);
8178 }
8179 } else {
8180 // process frames from the RecordThread buffer provider to the RecordTrack
8181 // buffer
8182 framesOut = activeTrack->mRecordBufferConverter->convert(
8183 activeTrack->mSink.raw,
8184 activeTrack->mResamplerBufferProvider,
8185 framesOut);
8186 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008187
8188 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8189 overrun = OVERRUN_FALSE;
8190 }
8191
8192 if (activeTrack->mFramesToDrop == 0) {
8193 if (framesOut > 0) {
8194 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008195 // Sanitize before releasing if the track has no access to the source data
8196 // An idle UID receives silence from non virtual devices until active
8197 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07008198 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008199 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008200 activeTrack->releaseBuffer(&activeTrack->mSink);
8201 }
8202 } else {
8203 // FIXME could do a partial drop of framesOut
8204 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07008205 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008206 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008207 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008208 }
8209 } else {
8210 activeTrack->mFramesToDrop += framesOut;
8211 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
8212 activeTrack->mSyncStartEvent->isCancelled()) {
8213 ALOGW("Synced record %s, session %d, trigger session %d",
8214 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
8215 activeTrack->sessionId(),
8216 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08008217 activeTrack->mSyncStartEvent->triggerSession() :
8218 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008219 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008220 }
8221 }
8222 }
8223
8224 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008225 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008226 }
8227 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008228
8229 switch (overrun) {
8230 case OVERRUN_TRUE:
8231 // client isn't retrieving buffers fast enough
8232 if (!activeTrack->setOverflow()) {
8233 nsecs_t now = systemTime();
8234 // FIXME should lastWarning per track?
8235 if ((now - lastWarning) > kWarningThrottleNs) {
8236 ALOGW("RecordThread: buffer overflow");
8237 lastWarning = now;
8238 }
8239 }
8240 break;
8241 case OVERRUN_FALSE:
8242 activeTrack->clearOverflow();
8243 break;
8244 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008245 break;
8246 }
8247
Andy Hung3f0c9022016-01-15 17:49:46 -08008248 // update frame information and push timestamp out
8249 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08008250 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008251 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8252 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008253 }
8254
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008255unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008256 // enable changes in effect chain
8257 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008258 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008259 if (audio_has_proportional_frames(mFormat)
8260 && loopCount == lastLoopCountRead + 1) {
8261 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8262 const double jitterMs =
8263 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8264 {framesRead, readPeriodNs},
8265 {0, 0} /* lastTimestamp */, mSampleRate);
8266 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8267
8268 Mutex::Autolock _l(mLock);
8269 mIoJitterMs.add(jitterMs);
8270 mProcessTimeMs.add(processMs);
8271 }
8272 // update timing info.
8273 mLastIoBeginNs = lastIoBeginNs;
8274 mLastIoEndNs = lastIoEndNs;
8275 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008276 }
8277
Glenn Kasten93e471f2013-08-19 08:40:07 -07008278 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008279
8280 {
8281 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008282 for (size_t i = 0; i < mTracks.size(); i++) {
8283 sp<RecordTrack> track = mTracks[i];
8284 track->invalidate();
8285 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008286 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008287 mStartStopCond.broadcast();
8288 }
8289
8290 releaseWakeLock();
8291
8292 ALOGV("RecordThread %p exiting", this);
8293 return false;
8294}
8295
Glenn Kasten93e471f2013-08-19 08:40:07 -07008296void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008297{
8298 if (!mStandby) {
8299 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008300 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008301 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008302 mStandby = true;
8303 }
8304}
8305
8306void AudioFlinger::RecordThread::inputStandBy()
8307{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008308 // Idle the fast capture if it's currently running
8309 if (mFastCapture != 0) {
8310 FastCaptureStateQueue *sq = mFastCapture->sq();
8311 FastCaptureState *state = sq->begin();
8312 if (!(state->mCommand & FastCaptureState::IDLE)) {
8313 state->mCommand = FastCaptureState::COLD_IDLE;
8314 state->mColdFutexAddr = &mFastCaptureFutex;
8315 state->mColdGen++;
8316 mFastCaptureFutex = 0;
8317 sq->end();
8318 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8319 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8320#if 0
8321 if (kUseFastCapture == FastCapture_Dynamic) {
8322 // FIXME
8323 }
8324#endif
8325#ifdef AUDIO_WATCHDOG
8326 // FIXME
8327#endif
8328 } else {
8329 sq->end(false /*didModify*/);
8330 }
8331 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008332 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008333 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008334
8335 // If going into standby, flush the pipe source.
8336 if (mPipeSource.get() != nullptr) {
8337 const ssize_t flushed = mPipeSource->flush();
8338 if (flushed > 0) {
8339 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8340 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8341 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8342 }
8343 }
Eric Laurent81784c32012-11-19 14:55:58 -08008344}
8345
Glenn Kasten05997e22014-03-13 15:08:33 -07008346// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07008347sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08008348 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008349 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008350 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008351 audio_format_t format,
8352 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008353 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008354 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008355 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008356 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008357 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008358 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008359 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008360 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008361 audio_port_handle_t portId,
8362 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008363{
Glenn Kasten74935e42013-12-19 08:56:45 -08008364 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008365 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008366 sp<RecordTrack> track;
8367 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008368 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008369 audio_input_flags_t requestedFlags = *flags;
8370 uint32_t sampleRate;
Eric Laurent6e6aedd2022-10-21 11:36:32 +02008371 AttributionSourceState checkedAttributionSource = AudioFlinger::checkAttributionSourcePackage(
8372 attributionSource);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008373
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 Laurent6e6aedd2022-10-21 11:36:32 +02008387 if (!captureHotwordAllowed(checkedAttributionSource)) {
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 Laurent6e6aedd2022-10-21 11:36:32 +02008508 && mSharedAudioPackageName == checkedAttributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008509 && mSharedAudioSessionId == sessionId
Eric Laurent6e6aedd2022-10-21 11:36:32 +02008510 && captureHotwordAllowed(checkedAttributionSource)) {
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 Laurent6e6aedd2022-10-21 11:36:32 +02008517 checkedAttributionSource, *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(
8726 std::vector<media::MicrophoneInfo>* activeMicrophones)
8727{
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;
8817 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01008818 // Do not forward PatchRecord metadata to audio HAL
8819 if (track->isPatchTrack()) {
8820 continue;
8821 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008822 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01008823 record_track_metadata_v7_t trackMetadata;
8824 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07008825 .source = track->attributes().source,
8826 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +01008827 };
8828 trackMetadata.channel_mask = track->channelMask(),
8829 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8830
8831 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07008832 }
8833 mInput->stream->updateSinkMetadata(metadata);
8834}
8835
Eric Laurent81784c32012-11-19 14:55:58 -08008836// destroyTrack_l() must be called with ThreadBase::mLock held
8837void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8838{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008839 track->terminate();
8840 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008841
Eric Laurent81784c32012-11-19 14:55:58 -08008842 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008843 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008844 removeTrack_l(track);
8845 }
8846}
8847
8848void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8849{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008850 String8 result;
8851 track->appendDump(result, false /* active */);
8852 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8853
Eric Laurent81784c32012-11-19 14:55:58 -08008854 mTracks.remove(track);
8855 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008856 if (track->isFastTrack()) {
8857 ALOG_ASSERT(!mFastTrackAvail);
8858 mFastTrackAvail = true;
8859 }
Eric Laurent81784c32012-11-19 14:55:58 -08008860}
8861
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008862void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008863{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008864 AudioStreamIn *input = mInput;
8865 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8866 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008867 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008868 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008869 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008870 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008871 }
Andy Hungbfa64962017-06-12 14:43:19 -07008872
8873 if (input != nullptr) {
8874 dprintf(fd, " Hal stream dump:\n");
8875 (void)input->stream->dump(fd);
8876 }
8877
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008878 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008879 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008880
Glenn Kasten2f90c512015-12-02 11:40:09 -08008881 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8882 // while we are dumping it. It may be inconsistent, but it won't mutate!
8883 // This is a large object so we place it on the heap.
8884 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008885 const std::unique_ptr<FastCaptureDumpState> copy =
8886 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008887 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008888}
8889
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008890void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008891{
Eric Laurent81784c32012-11-19 14:55:58 -08008892 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008893 size_t numtracks = mTracks.size();
8894 size_t numactive = mActiveTracks.size();
8895 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008896 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008897 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008898 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008899 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008900 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008901 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008902 for (size_t i = 0; i < numtracks ; ++i) {
8903 sp<RecordTrack> track = mTracks[i];
8904 if (track != 0) {
8905 bool active = mActiveTracks.indexOf(track) >= 0;
8906 if (active) {
8907 numactiveseen++;
8908 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008909 result.append(prefix);
8910 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008911 }
Eric Laurent81784c32012-11-19 14:55:58 -08008912 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008913 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008914 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008915 }
8916
Marco Nelissenb2208842014-02-07 14:00:50 -08008917 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008918 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008919 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008920 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008921 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008922 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008923 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008924 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008925 result.append(prefix);
8926 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008927 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008928 }
Eric Laurent81784c32012-11-19 14:55:58 -08008929
8930 }
8931 write(fd, result.string(), result.size());
8932}
8933
Eric Laurent5ada82e2019-08-29 17:53:54 -07008934void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008935{
8936 Mutex::Autolock _l(mLock);
8937 for (size_t i = 0; i < mTracks.size() ; i++) {
8938 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008939 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008940 track->setSilenced(silenced);
8941 }
8942 }
8943}
Andy Hung73c02e42015-03-29 01:13:58 -07008944
8945void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8946{
8947 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8948 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008949 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008950 const int32_t rear = recordThread->mRsmpInRear;
8951 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008952 if (mRecordTrack->startFrames() >= 0) {
8953 int32_t startFrames = mRecordTrack->startFrames();
8954 // Accept a recent wraparound of mRsmpInRear
8955 if (startFrames <= rear) {
8956 deltaFrames = rear - startFrames;
8957 } else {
8958 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008959 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008960 // start frame cannot be further in the past than start of resampling buffer
8961 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8962 deltaFrames = recordThread->mRsmpInFrames;
8963 }
8964 }
8965 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008966}
8967
8968void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8969 size_t *framesAvailable, bool *hasOverrun)
8970{
8971 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8972 RecordThread *recordThread = (RecordThread *) threadBase.get();
8973 const int32_t rear = recordThread->mRsmpInRear;
8974 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008975 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008976
8977 size_t framesIn;
8978 bool overrun = false;
8979 if (filled < 0) {
8980 // should not happen, but treat like a massive overrun and re-sync
8981 framesIn = 0;
8982 mRsmpInFront = rear;
8983 overrun = true;
8984 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8985 framesIn = (size_t) filled;
8986 } else {
8987 // client is not keeping up with server, but give it latest data
8988 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008989 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8990 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008991 overrun = true;
8992 }
8993 if (framesAvailable != NULL) {
8994 *framesAvailable = framesIn;
8995 }
8996 if (hasOverrun != NULL) {
8997 *hasOverrun = overrun;
8998 }
8999}
9000
Eric Laurent81784c32012-11-19 14:55:58 -08009001// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009002status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009003 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009004{
Andy Hung73c02e42015-03-29 01:13:58 -07009005 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009006 if (threadBase == 0) {
9007 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009008 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009009 return NOT_ENOUGH_DATA;
9010 }
9011 RecordThread *recordThread = (RecordThread *) threadBase.get();
9012 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009013 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009014 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009015 // FIXME should not be P2 (don't want to increase latency)
9016 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009017 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009018 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009019
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009020 front &= recordThread->mRsmpInFramesP2 - 1;
9021 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009022 if (part1 > (size_t) filled) {
9023 part1 = filled;
9024 }
9025 size_t ask = buffer->frameCount;
9026 ALOG_ASSERT(ask > 0);
9027 if (part1 > ask) {
9028 part1 = ask;
9029 }
9030 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009031 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009032 buffer->raw = NULL;
9033 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009034 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009035 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009036 }
9037
Andy Hung57446612015-04-19 23:56:46 -07009038 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009039 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009040 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009041 return NO_ERROR;
9042}
9043
9044// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009045void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
9046 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009047{
Hongwei Wang95e37682019-04-12 11:13:36 -07009048 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009049 if (stepCount == 0) {
9050 return;
9051 }
Andy Hung73c02e42015-03-29 01:13:58 -07009052 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
9053 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009054 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009055 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009056 buffer->frameCount = 0;
9057}
9058
Eric Laurentd8365c52017-07-16 15:27:05 -07009059void AudioFlinger::RecordThread::checkBtNrec()
9060{
9061 Mutex::Autolock _l(mLock);
9062 checkBtNrec_l();
9063}
9064
9065void AudioFlinger::RecordThread::checkBtNrec_l()
9066{
9067 // disable AEC and NS if the device is a BT SCO headset supporting those
9068 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009069 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07009070 mAudioFlinger->btNrecIsOff();
9071 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9072 for (size_t i = 0; i < mEffectChains.size(); i++) {
9073 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9074 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9075 }
9076 }
9077}
9078
Andy Hung97a893e2015-03-29 01:03:07 -07009079
Eric Laurent10351942014-05-08 18:49:52 -07009080bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
9081 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009082{
9083 bool reconfig = false;
9084
Eric Laurent10351942014-05-08 18:49:52 -07009085 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009086
Eric Laurent10351942014-05-08 18:49:52 -07009087 audio_format_t reqFormat = mFormat;
9088 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009089 // TODO this may change if we want to support capture from HDMI PCM multi channel (e.g on TVs).
Eric Laurent10351942014-05-08 18:49:52 -07009090 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
9091
9092 AudioParameter param = AudioParameter(keyValuePair);
9093 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009094
9095 // scope for AutoPark extends to end of method
9096 AutoPark<FastCapture> park(mFastCapture);
9097
Eric Laurent10351942014-05-08 18:49:52 -07009098 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9099 // channel count change can be requested. Do we mandate the first client defines the
9100 // HAL sampling rate and channel count or do we allow changes on the fly?
9101 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9102 samplingRate = value;
9103 reconfig = true;
9104 }
9105 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009106 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009107 status = BAD_VALUE;
9108 } else {
9109 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009110 reconfig = true;
9111 }
Eric Laurent10351942014-05-08 18:49:52 -07009112 }
9113 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9114 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009115 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009116 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009117 status = BAD_VALUE;
9118 } else {
9119 channelMask = mask;
9120 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009121 }
Eric Laurent10351942014-05-08 18:49:52 -07009122 }
9123 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9124 // do not accept frame count changes if tracks are open as the track buffer
9125 // size depends on frame count and correct behavior would not be guaranteed
9126 // if frame count is changed after track creation
9127 if (mActiveTracks.size() > 0) {
9128 status = INVALID_OPERATION;
9129 } else {
9130 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009131 }
Eric Laurent10351942014-05-08 18:49:52 -07009132 }
9133 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009134 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009135 }
9136 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9137 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009138 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009139 }
Glenn Kastene198c362013-08-13 09:13:36 -07009140
Eric Laurent10351942014-05-08 18:49:52 -07009141 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009142 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009143 if (status == INVALID_OPERATION) {
9144 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009145 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009146 }
9147 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009148 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009149 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9150 if (mInput->stream->getAudioProperties(&config) == OK &&
9151 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9152 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009153 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009154 status = NO_ERROR;
9155 }
Eric Laurent81784c32012-11-19 14:55:58 -08009156 }
Eric Laurent10351942014-05-08 18:49:52 -07009157 if (status == NO_ERROR) {
9158 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009159 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009160 }
9161 }
Eric Laurent81784c32012-11-19 14:55:58 -08009162 }
Eric Laurent10351942014-05-08 18:49:52 -07009163
Eric Laurent81784c32012-11-19 14:55:58 -08009164 return reconfig;
9165}
9166
9167String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
9168{
Eric Laurent81784c32012-11-19 14:55:58 -08009169 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009170 if (initCheck() == NO_ERROR) {
9171 String8 out_s8;
9172 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9173 return out_s8;
9174 }
Eric Laurent81784c32012-11-19 14:55:58 -08009175 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009176 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08009177}
9178
Mikhail Naganov88536df2021-07-26 17:30:29 -07009179void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009180 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009181 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009182 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009183 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009184 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009185 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009186 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9187 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009188 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009189 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009190 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009191 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009192 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009193 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009194 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009195 break;
9196 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07009197 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009198}
9199
Glenn Kastendeca2ae2014-02-07 10:25:56 -08009200void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009201{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009202 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9203 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009204 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009205 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9206 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009207 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9208 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009209 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009210 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009211 ALOGI("HAL format %#x is not linear pcm", mFormat);
9212 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009213 result = mInput->stream->getFrameSize(&mFrameSize);
9214 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009215 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9216 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009217 result = mInput->stream->getBufferSize(&mBufferSize);
9218 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009219 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009220 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9221 "mBufferSize=%zu, mFrameCount=%zu",
9222 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009223
Eric Laurentec376dc2021-04-08 20:41:22 +02009224 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9225 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009226 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009227
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009228 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9229 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009230
9231 audio_input_flags_t flags = mInput->flags;
9232 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9233 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9234 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9235 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9236 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9237 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9238 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9239 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9240 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009241}
9242
Glenn Kasten5f972c02014-01-13 09:59:31 -08009243uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08009244{
9245 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009246 uint32_t result;
9247 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9248 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009249 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009250 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009251}
9252
Glenn Kastend848eb42016-03-08 13:42:11 -08009253KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009254{
Glenn Kastend848eb42016-03-08 13:42:11 -08009255 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009256 Mutex::Autolock _l(mLock);
9257 for (size_t j = 0; j < mTracks.size(); ++j) {
9258 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009259 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009260 if (ids.indexOfKey(sessionId) < 0) {
9261 ids.add(sessionId, true);
9262 }
9263 }
9264 return ids;
9265}
9266
9267AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
9268{
9269 Mutex::Autolock _l(mLock);
9270 AudioStreamIn *input = mInput;
9271 mInput = NULL;
9272 return input;
9273}
9274
9275// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009276sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009277{
9278 if (mInput == NULL) {
9279 return NULL;
9280 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009281 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009282}
9283
9284status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
9285{
Eric Laurent81784c32012-11-19 14:55:58 -08009286 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009287 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009288 chain->setInBuffer(NULL);
9289 chain->setOutBuffer(NULL);
9290
9291 checkSuspendOnAddEffectChain_l(chain);
9292
Eric Laurent1b928682014-10-02 19:41:47 -07009293 // make sure enabled pre processing effects state is communicated to the HAL as we
9294 // just moved them to a new input stream.
9295 chain->syncHalEffectsState();
9296
Eric Laurent81784c32012-11-19 14:55:58 -08009297 mEffectChains.add(chain);
9298
9299 return NO_ERROR;
9300}
9301
9302size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
9303{
9304 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009305
9306 for (size_t i = 0; i < mEffectChains.size(); i++) {
9307 if (chain == mEffectChains[i]) {
9308 mEffectChains.removeAt(i);
9309 break;
9310 }
Eric Laurent81784c32012-11-19 14:55:58 -08009311 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009312 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009313}
9314
Eric Laurent1c333e22014-05-20 10:48:17 -07009315status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
9316 audio_patch_handle_t *handle)
9317{
9318 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009319
9320 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009321 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009322 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009323 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009324 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009325 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009326 }
9327
Eric Laurentd8365c52017-07-16 15:27:05 -07009328 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009329
9330 // store new source and send to effects
9331 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9332 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009333 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009334 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009335 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009336 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009337
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009338 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009339 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9340 status = hwDevice->createAudioPatch(patch->num_sources,
9341 patch->sources,
9342 patch->num_sinks,
9343 patch->sinks,
9344 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009345 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009346 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9347 patch->sinks[0].ext.mix.usecase.source,
9348 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009349 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009350 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009351
jiabinc52b1ff2019-10-31 17:20:42 -07009352 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009353 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009354 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009355 }
Eric Laurent296fb132015-05-01 11:38:42 -07009356
Andy Hungc2b11cb2020-04-22 09:04:01 -07009357 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009358 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009359 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009360 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009361 // also dispatch to active AudioRecords
9362 for (const auto &track : mActiveTracks) {
9363 track->logEndInterval();
9364 track->logBeginInterval(pathSourcesAsString);
9365 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009366 return status;
9367}
9368
9369status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9370{
9371 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009372
jiabinc52b1ff2019-10-31 17:20:42 -07009373 mPatch = audio_patch{};
9374 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009375
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009376 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009377 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9378 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009379 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009380 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009381 }
9382 return status;
9383}
9384
jiabinc52b1ff2019-10-31 17:20:42 -07009385void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
9386{
wendy lin56aa82b2020-12-02 15:19:55 +08009387 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009388 mOutDevices = outDevices;
9389 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9390 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009391 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009392 }
9393}
9394
Eric Laurentec376dc2021-04-08 20:41:22 +02009395int32_t AudioFlinger::RecordThread::getOldestFront_l()
9396{
9397 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009398 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009399 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009400 int32_t oldestFront = mRsmpInRear;
9401 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009402 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009403 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9404 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009405 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009406 if (filled > maxFilled) {
9407 oldestFront = front;
9408 maxFilled = filled;
9409 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009410 }
Eric Laurent92d0a322021-07-16 15:32:33 +02009411 if (maxFilled > mRsmpInFrames) {
9412 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9413 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009414 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009415}
9416
9417void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
9418{
9419 if (offset == 0) {
9420 return;
9421 }
9422 for (size_t i = 0; i < mTracks.size(); i++) {
9423 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9424 front = audio_utils::safe_sub_overflow(front, offset);
9425 mTracks[i]->mResamplerBufferProvider->setFront(front);
9426 }
9427}
9428
9429void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
9430{
9431 // This is the formula for calculating the temporary buffer size.
9432 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9433 // 1 full output buffer, regardless of the alignment of the available input.
9434 // The value is somewhat arbitrary, and could probably be even larger.
9435 // A larger value should allow more old data to be read after a track calls start(),
9436 // without increasing latency.
9437 //
9438 // Note this is independent of the maximum downsampling ratio permitted for capture.
9439 size_t minRsmpInFrames = mFrameCount * 7;
9440
9441 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9442 // capture history available to another client using the same session ID:
9443 // dimension the resampler input buffer accordingly.
9444
9445 // Get oldest client read position: getOldestFront_l() must be called before altering
9446 // mRsmpInRear, or mRsmpInFrames
9447 int32_t previousFront = getOldestFront_l();
9448 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9449 int32_t previousRear = mRsmpInRear;
9450 mRsmpInRear = 0;
9451
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009452 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
9453 && maxSharedAudioHistoryMs <= AudioFlinger::kMaxSharedAudioHistoryMs,
9454 "resizeInputBuffer_l() called with invalid max shared history %d",
9455 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009456 if (maxSharedAudioHistoryMs != 0) {
9457 // resizeInputBuffer_l should never be called with a non zero shared history if the
9458 // buffer was not already allocated
9459 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9460 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9461 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9462 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009463 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009464 return;
9465 }
9466 mRsmpInFrames = rsmpInFrames;
9467 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009468 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009469 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9470 // initialized
9471 if (mRsmpInFrames < minRsmpInFrames) {
9472 mRsmpInFrames = minRsmpInFrames;
9473 }
9474 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9475
9476 // TODO optimize audio capture buffer sizes ...
9477 // Here we calculate the size of the sliding buffer used as a source
9478 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9479 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9480 // be better to have it derived from the pipe depth in the long term.
9481 // The current value is higher than necessary. However it should not add to latency.
9482
9483 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9484 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9485
9486 void *rsmpInBuffer;
9487 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9488 // if posix_memalign fails, will segv here.
9489 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9490
9491 // Copy audio history if any from old buffer before freeing it
9492 if (previousRear != 0) {
9493 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9494 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9495
9496 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9497 previousFront &= previousRsmpInFramesP2 - 1;
9498 size_t part1 = previousRsmpInFramesP2 - previousFront;
9499 if (part1 > (size_t) unread) {
9500 part1 = unread;
9501 }
9502 if (part1 != 0) {
9503 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9504 part1 * mFrameSize);
9505 mRsmpInRear = part1;
9506 part1 = unread - part1;
9507 if (part1 != 0) {
9508 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9509 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9510 mRsmpInRear += part1;
9511 }
9512 }
9513 // Update front for all clients according to new rear
9514 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9515 } else {
9516 mRsmpInRear = 0;
9517 }
9518 free(mRsmpInBuffer);
9519 mRsmpInBuffer = rsmpInBuffer;
9520}
9521
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009522void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009523{
9524 Mutex::Autolock _l(mLock);
9525 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009526 if (record->getSource()) {
9527 mSource = record->getSource();
9528 }
Eric Laurent83b88082014-06-20 18:31:16 -07009529}
9530
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009531void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009532{
9533 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009534 if (mSource == record->getSource()) {
9535 mSource = mInput;
9536 }
Eric Laurent83b88082014-06-20 18:31:16 -07009537 destroyTrack_l(record);
9538}
9539
Mikhail Naganovdc769682018-05-04 15:34:08 -07009540void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07009541{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009542 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009543 config->role = AUDIO_PORT_ROLE_SINK;
9544 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9545 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009546 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9547 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9548 config->flags.input = mInput->flags;
9549 }
Eric Laurent83b88082014-06-20 18:31:16 -07009550}
Eric Laurent1c333e22014-05-20 10:48:17 -07009551
Eric Laurent6acd1d42017-01-04 14:23:29 -08009552// ----------------------------------------------------------------------------
9553// Mmap
9554// ----------------------------------------------------------------------------
9555
9556AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
9557 : mThread(thread)
9558{
Phil Burk9fabbf82017-08-03 12:02:00 -07009559 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009560}
9561
9562AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9563{
Phil Burk9fabbf82017-08-03 12:02:00 -07009564 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009565}
9566
9567status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9568 struct audio_mmap_buffer_info *info)
9569{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009570 return mThread->createMmapBuffer(minSizeFrames, info);
9571}
9572
9573status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9574{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009575 return mThread->getMmapPosition(position);
9576}
9577
jiabinb7d8c5a2020-08-26 17:24:52 -07009578status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9579 int64_t *timeNanos) {
9580 return mThread->getExternalPosition(position, timeNanos);
9581}
9582
Eric Laurenta54f1282017-07-01 19:39:32 -07009583status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009584 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009585
9586{
jiabind1f1cb62020-03-24 11:57:57 -07009587 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009588}
9589
9590status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9591{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009592 return mThread->stop(handle);
9593}
9594
Eric Laurent18b57012017-02-13 16:23:52 -08009595status_t AudioFlinger::MmapThreadHandle::standby()
9596{
Eric Laurent18b57012017-02-13 16:23:52 -08009597 return mThread->standby();
9598}
9599
Eric Laurent6acd1d42017-01-04 14:23:29 -08009600
9601AudioFlinger::MmapThread::MmapThread(
9602 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07009603 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009604 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009605 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009606 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009607 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009608 mActiveTracks(&this->mLocalLog),
9609 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9610 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009611{
Eric Laurent18b57012017-02-13 16:23:52 -08009612 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009613 readHalParameters_l();
9614}
9615
9616AudioFlinger::MmapThread::~MmapThread()
9617{
9618}
9619
9620void AudioFlinger::MmapThread::onFirstRef()
9621{
9622 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9623}
9624
9625void AudioFlinger::MmapThread::disconnect()
9626{
Eric Laurent331679c2018-04-16 17:03:16 -07009627 ActiveTracks<MmapTrack> activeTracks;
9628 {
9629 Mutex::Autolock _l(mLock);
9630 for (const sp<MmapTrack> &t : mActiveTracks) {
9631 activeTracks.add(t);
9632 }
9633 }
9634 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009635 stop(t->portId());
9636 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009637 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009638 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009639 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009640 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009641 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009642 }
9643}
9644
9645
9646void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9647 audio_stream_type_t streamType __unused,
9648 audio_session_t sessionId,
9649 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009650 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009651 audio_port_handle_t portId)
9652{
9653 mAttr = *attr;
9654 mSessionId = sessionId;
9655 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009656 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009657 mPortId = portId;
9658}
9659
9660status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9661 struct audio_mmap_buffer_info *info)
9662{
9663 if (mHalStream == 0) {
9664 return NO_INIT;
9665 }
Eric Laurent18b57012017-02-13 16:23:52 -08009666 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009667 return mHalStream->createMmapBuffer(minSizeFrames, info);
9668}
9669
9670status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9671{
9672 if (mHalStream == 0) {
9673 return NO_INIT;
9674 }
9675 return mHalStream->getMmapPosition(position);
9676}
9677
Eric Laurent331679c2018-04-16 17:03:16 -07009678status_t AudioFlinger::MmapThread::exitStandby()
9679{
9680 status_t ret = mHalStream->start();
9681 if (ret != NO_ERROR) {
9682 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9683 return ret;
9684 }
Andy Hungcf10d742020-04-28 15:38:24 -07009685 if (mStandby) {
9686 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009687 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07009688 mStandby = false;
9689 }
Eric Laurent331679c2018-04-16 17:03:16 -07009690 return NO_ERROR;
9691}
9692
Eric Laurenta54f1282017-07-01 19:39:32 -07009693status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009694 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009695 audio_port_handle_t *handle)
9696{
Eric Laurenta54f1282017-07-01 19:39:32 -07009697 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009698 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009699 if (mHalStream == 0) {
9700 return NO_INIT;
9701 }
9702
9703 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009704
Eric Laurenta54f1282017-07-01 19:39:32 -07009705 if (*handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009706 // For the first track, reuse portId and session allocated when the stream was opened.
9707 ret = exitStandby();
9708 if (ret == NO_ERROR) {
9709 acquireWakeLock();
9710 }
9711 return ret;
Eric Laurenta54f1282017-07-01 19:39:32 -07009712 }
9713
9714 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9715
9716 audio_io_handle_t io = mId;
9717 if (isOutput()) {
9718 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9719 config.sample_rate = mSampleRate;
9720 config.channel_mask = mChannelMask;
9721 config.format = mFormat;
9722 audio_stream_type_t stream = streamType();
9723 audio_output_flags_t flags =
9724 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009725 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009726 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02009727 bool isSpatialized;
Eric Laurenta54f1282017-07-01 19:39:32 -07009728 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9729 mSessionId,
9730 &stream,
Svet Ganov33761132021-05-13 22:51:08 +00009731 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009732 &config,
9733 flags,
9734 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009735 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02009736 &secondaryOutputs,
9737 &isSpatialized);
Kevin Rocard153f92d2018-12-18 18:33:28 -08009738 ALOGD_IF(!secondaryOutputs.empty(),
9739 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009740 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009741 audio_config_base_t config;
9742 config.sample_rate = mSampleRate;
9743 config.channel_mask = mChannelMask;
9744 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009745 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009746 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009747 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009748 mSessionId,
Svet Ganov33761132021-05-13 22:51:08 +00009749 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009750 &config,
9751 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9752 &deviceId,
9753 &portId);
9754 }
9755 // APM should not chose a different input or output stream for the same set of attributes
9756 // and audo configuration
9757 if (ret != NO_ERROR || io != mId) {
9758 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9759 __FUNCTION__, ret, io, mId);
9760 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009761 }
9762
9763 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009764 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009765 } else {
jiabincfc10a42022-06-15 19:26:01 +00009766 {
9767 // Add the track record before starting input so that the silent status for the
9768 // client can be cached.
9769 Mutex::Autolock _l(mLock);
9770 setClientSilencedState_l(portId, false /*silenced*/);
9771 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08009772 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009773 }
9774
Eric Laurent331679c2018-04-16 17:03:16 -07009775 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009776 // abort if start is rejected by audio policy manager
9777 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009778 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009779 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009780 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009781 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009782 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009783 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009784 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009785 }
Eric Laurent331679c2018-04-16 17:03:16 -07009786 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009787 } else {
9788 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009789 }
jiabincfc10a42022-06-15 19:26:01 +00009790 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009791 return PERMISSION_DENIED;
9792 }
9793
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009794 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009795 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +00009796 mChannelMask, mSessionId, isOutput(),
9797 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009798 IPCThreadState::self()->getCallingPid(), portId);
jiabincfc10a42022-06-15 19:26:01 +00009799 if (!isOutput()) {
9800 track->setSilenced_l(isClientSilenced_l(portId));
9801 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009802
Eric Laurent4eb58f12018-12-07 16:41:02 -08009803 if (isOutput()) {
9804 // force volume update when a new track is added
9805 mHalVolFloat = -1.0f;
9806 } else if (!track->isSilenced_l()) {
9807 for (const sp<MmapTrack> &t : mActiveTracks) {
Svet Ganov33761132021-05-13 22:51:08 +00009808 if (t->isSilenced_l() && t->uid() != client.attributionSource.uid)
Eric Laurent4eb58f12018-12-07 16:41:02 -08009809 t->invalidate();
9810 }
9811 }
9812
9813
Eric Laurent6acd1d42017-01-04 14:23:29 -08009814 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009815 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009816 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02009817 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009818 chain->incTrackCnt();
9819 chain->incActiveTrackCnt();
9820 }
9821
Andy Hungc2b11cb2020-04-22 09:04:01 -07009822 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009823 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009824 broadcast_l();
9825
Eric Laurenta54f1282017-07-01 19:39:32 -07009826 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009827
9828 return NO_ERROR;
9829}
9830
9831status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9832{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009833 ALOGV("%s handle %d", __FUNCTION__, handle);
9834
9835 if (mHalStream == 0) {
9836 return NO_INIT;
9837 }
9838
Eric Laurenta54f1282017-07-01 19:39:32 -07009839 if (handle == mPortId) {
9840 mHalStream->stop();
Phil Burk98ab4082020-09-25 21:46:34 +00009841 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009842 return NO_ERROR;
9843 }
9844
Eric Laurent331679c2018-04-16 17:03:16 -07009845 Mutex::Autolock _l(mLock);
9846
Eric Laurent6acd1d42017-01-04 14:23:29 -08009847 sp<MmapTrack> track;
9848 for (const sp<MmapTrack> &t : mActiveTracks) {
9849 if (handle == t->portId()) {
9850 track = t;
9851 break;
9852 }
9853 }
9854 if (track == 0) {
9855 return BAD_VALUE;
9856 }
9857
9858 mActiveTracks.remove(track);
jiabincfc10a42022-06-15 19:26:01 +00009859 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009860
Eric Laurent331679c2018-04-16 17:03:16 -07009861 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009862 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009863 AudioSystem::stopOutput(track->portId());
9864 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009865 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009866 AudioSystem::stopInput(track->portId());
9867 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009868 }
Eric Laurent331679c2018-04-16 17:03:16 -07009869 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009870
9871 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9872 if (chain != 0) {
9873 chain->decActiveTrackCnt();
9874 chain->decTrackCnt();
9875 }
9876
9877 broadcast_l();
9878
Eric Laurent6acd1d42017-01-04 14:23:29 -08009879 return NO_ERROR;
9880}
9881
Eric Laurent18b57012017-02-13 16:23:52 -08009882status_t AudioFlinger::MmapThread::standby()
9883{
9884 ALOGV("%s", __FUNCTION__);
9885
9886 if (mHalStream == 0) {
9887 return NO_INIT;
9888 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009889 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009890 return INVALID_OPERATION;
9891 }
9892 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009893 if (!mStandby) {
9894 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009895 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07009896 mStandby = true;
9897 }
Eric Laurent18b57012017-02-13 16:23:52 -08009898 releaseWakeLock();
9899 return NO_ERROR;
9900}
9901
Eric Laurent6acd1d42017-01-04 14:23:29 -08009902
9903void AudioFlinger::MmapThread::readHalParameters_l()
9904{
9905 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9906 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9907 mFormat = mHALFormat;
9908 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9909 result = mHalStream->getFrameSize(&mFrameSize);
9910 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009911 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9912 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009913 result = mHalStream->getBufferSize(&mBufferSize);
9914 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9915 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009916
Andy Hungcf10d742020-04-28 15:38:24 -07009917 // TODO: make a readHalParameters call?
9918 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009919 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9920 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9921 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9922 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9923 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9924 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9925 /*
9926 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9927 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9928 (int32_t)mHapticChannelMask)
9929 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9930 (int32_t)mHapticChannelCount)
9931 */
9932 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9933 formatToString(mHALFormat).c_str())
9934 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9935 (int32_t)mFrameCount) // sic - added HAL
9936 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009937}
9938
9939bool AudioFlinger::MmapThread::threadLoop()
9940{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009941 checkSilentMode_l();
9942
9943 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9944
9945 while (!exitPending())
9946 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009947 Vector< sp<EffectChain> > effectChains;
9948
Andy Hung13850be2019-03-14 11:33:09 -07009949 { // under Thread lock
9950 Mutex::Autolock _l(mLock);
9951
Eric Laurent6acd1d42017-01-04 14:23:29 -08009952 if (mSignalPending) {
9953 // A signal was raised while we were unlocked
9954 mSignalPending = false;
9955 } else {
9956 if (mConfigEvents.isEmpty()) {
9957 // we're about to wait, flush the binder command buffer
9958 IPCThreadState::self()->flushCommands();
9959
9960 if (exitPending()) {
9961 break;
9962 }
9963
Eric Laurent6acd1d42017-01-04 14:23:29 -08009964 // wait until we have something to do...
9965 ALOGV("%s going to sleep", myName.string());
9966 mWaitWorkCV.wait(mLock);
9967 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009968
9969 checkSilentMode_l();
9970
9971 continue;
9972 }
9973 }
9974
9975 processConfigEvents_l();
9976
9977 processVolume_l();
9978
9979 checkInvalidTracks_l();
9980
9981 mActiveTracks.updatePowerState(this);
9982
Kevin Rocard069c2712018-03-29 19:09:14 -07009983 updateMetadata_l();
9984
Eric Laurent6acd1d42017-01-04 14:23:29 -08009985 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009986 } // release Thread lock
9987
Eric Laurent6acd1d42017-01-04 14:23:29 -08009988 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009989 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009990 }
Andy Hung13850be2019-03-14 11:33:09 -07009991
9992 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009993 unlockEffectChains(effectChains);
9994 // Effect chains will be actually deleted here if they were removed from
9995 // mEffectChains list during mixing or effects processing
9996 }
9997
9998 threadLoop_exit();
9999
10000 if (!mStandby) {
10001 threadLoop_standby();
10002 mStandby = true;
10003 }
10004
Eric Laurent6acd1d42017-01-04 14:23:29 -080010005 ALOGV("Thread %p type %d exiting", this, mType);
10006 return false;
10007}
10008
10009// checkForNewParameter_l() must be called with ThreadBase::mLock held
10010bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
10011 status_t& status)
10012{
10013 AudioParameter param = AudioParameter(keyValuePair);
10014 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010015 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010016 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010017 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010018 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010019 if (sendToHal) {
10020 status = mHalStream->setParameters(keyValuePair);
10021 } else {
10022 status = NO_ERROR;
10023 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010024
10025 return false;
10026}
10027
10028String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
10029{
10030 Mutex::Autolock _l(mLock);
10031 String8 out_s8;
10032 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10033 return out_s8;
10034 }
10035 return String8();
10036}
10037
Mikhail Naganov88536df2021-07-26 17:30:29 -070010038void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010039 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010040 sp<AudioIoDescriptor> desc;
10041 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010042 switch (event) {
10043 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010044 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010045 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010046 isInput = true;
10047 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010048 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010049 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010050 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010051 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10052 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010053 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010054 case AUDIO_INPUT_CLOSED:
10055 case AUDIO_OUTPUT_CLOSED:
10056 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010057 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010058 break;
10059 }
10060 mAudioFlinger->ioConfigChanged(event, desc, pid);
10061}
10062
10063status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
10064 audio_patch_handle_t *handle)
10065{
10066 status_t status = NO_ERROR;
10067
10068 // store new device and send to effects
10069 audio_devices_t type = AUDIO_DEVICE_NONE;
10070 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010071 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10072 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10073 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010074 if (isOutput()) {
10075 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010076 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10077 && !mAudioHwDev->supportsAudioPatches(),
10078 "Enumerated device type(%#x) must not be used "
10079 "as it does not support audio patches",
10080 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010081 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -070010082 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
10083 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010084 }
10085 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010086 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010087 } else {
10088 type = patch->sources[0].ext.device.type;
10089 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010090 numDevices = mPatch.num_sources;
10091 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010092 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010093 }
10094
10095 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010096 if (isOutput()) {
10097 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10098 } else {
10099 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10100 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010101 }
10102
jiabinc52b1ff2019-10-31 17:20:42 -070010103 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010104 // store new source and send to effects
10105 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10106 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10107 for (size_t i = 0; i < mEffectChains.size(); i++) {
10108 mEffectChains[i]->setAudioSource_l(mAudioSource);
10109 }
10110 }
10111 }
10112
10113 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010114 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10115 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010116 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010117 audio_port_config port;
10118 std::optional<audio_source_t> source;
10119 if (isOutput()) {
10120 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010121 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010122 port = patch->sources[0];
10123 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010124 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010125 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010126 *handle = AUDIO_PATCH_HANDLE_NONE;
10127 }
10128
jiabinc52b1ff2019-10-31 17:20:42 -070010129 if (numDevices == 0 || mDeviceId != deviceId) {
10130 if (isOutput()) {
10131 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10132 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010133 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010134 } else {
10135 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10136 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10137 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010138 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010139 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010140 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010141 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -070010142 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010143 }
jiabinc52b1ff2019-10-31 17:20:42 -070010144 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010145 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010146 }
10147 return status;
10148}
10149
10150status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
10151{
10152 status_t status = NO_ERROR;
10153
jiabinc52b1ff2019-10-31 17:20:42 -070010154 mPatch = audio_patch{};
10155 mOutDeviceTypeAddrs.clear();
10156 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010157
10158 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10159 supportsAudioPatches : false;
10160
10161 if (supportsAudioPatches) {
10162 status = mHalDevice->releaseAudioPatch(handle);
10163 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010164 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010165 }
10166 return status;
10167}
10168
Mikhail Naganovdc769682018-05-04 15:34:08 -070010169void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010170{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010171 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010172 if (isOutput()) {
10173 config->role = AUDIO_PORT_ROLE_SOURCE;
10174 config->ext.mix.hw_module = mAudioHwDev->handle();
10175 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10176 } else {
10177 config->role = AUDIO_PORT_ROLE_SINK;
10178 config->ext.mix.hw_module = mAudioHwDev->handle();
10179 config->ext.mix.usecase.source = mAudioSource;
10180 }
10181}
10182
10183status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
10184{
10185 audio_session_t session = chain->sessionId();
10186
10187 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10188 // Attach all tracks with same session ID to this chain.
10189 // indicate all active tracks in the chain
10190 for (const sp<MmapTrack> &track : mActiveTracks) {
10191 if (session == track->sessionId()) {
10192 chain->incTrackCnt();
10193 chain->incActiveTrackCnt();
10194 }
10195 }
10196
10197 chain->setThread(this);
10198 chain->setInBuffer(nullptr);
10199 chain->setOutBuffer(nullptr);
10200 chain->syncHalEffectsState();
10201
10202 mEffectChains.add(chain);
10203 checkSuspendOnAddEffectChain_l(chain);
10204 return NO_ERROR;
10205}
10206
10207size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
10208{
10209 audio_session_t session = chain->sessionId();
10210
10211 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10212
10213 for (size_t i = 0; i < mEffectChains.size(); i++) {
10214 if (chain == mEffectChains[i]) {
10215 mEffectChains.removeAt(i);
10216 // detach all active tracks from the chain
10217 // detach all tracks with same session ID from this chain
10218 for (const sp<MmapTrack> &track : mActiveTracks) {
10219 if (session == track->sessionId()) {
10220 chain->decActiveTrackCnt();
10221 chain->decTrackCnt();
10222 }
10223 }
10224 break;
10225 }
10226 }
10227 return mEffectChains.size();
10228}
10229
Eric Laurent6acd1d42017-01-04 14:23:29 -080010230void AudioFlinger::MmapThread::threadLoop_standby()
10231{
10232 mHalStream->standby();
10233}
10234
10235void AudioFlinger::MmapThread::threadLoop_exit()
10236{
Phil Burk7dce7282017-09-27 13:51:41 -070010237 // Do not call callback->onTearDown() because it is redundant for thread exit
10238 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010239}
10240
10241status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
10242{
10243 return BAD_VALUE;
10244}
10245
10246bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
10247{
10248 return false;
10249}
10250
10251status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
10252 const effect_descriptor_t *desc, audio_session_t sessionId)
10253{
10254 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010255 if (audio_is_global_session(sessionId)) {
10256 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010257 desc->name, mThreadName);
10258 return BAD_VALUE;
10259 }
10260
10261 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10262 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10263 desc->name);
10264 return BAD_VALUE;
10265 }
10266 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010267 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10268 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010269 return BAD_VALUE;
10270 }
10271
10272 // Only allow effects without processing load or latency
10273 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10274 return BAD_VALUE;
10275 }
10276
jiabineb3bda02020-06-30 14:07:03 -070010277 if (EffectModule::isHapticGenerator(&desc->type)) {
10278 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10279 return BAD_VALUE;
10280 }
10281
Eric Laurent6acd1d42017-01-04 14:23:29 -080010282 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010283}
10284
10285void AudioFlinger::MmapThread::checkInvalidTracks_l()
10286{
10287 for (const sp<MmapTrack> &track : mActiveTracks) {
10288 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010289 sp<MmapStreamCallback> callback = mCallback.promote();
10290 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010291 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -070010292 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -070010293 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -070010294 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10295 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
10296 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010297 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010298 }
10299 }
10300}
10301
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010302void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010303{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010304 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10305 mAttr.content_type, mAttr.usage, mAttr.source);
10306 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010307 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010308 dprintf(fd, " No active clients\n");
10309 }
10310}
10311
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010312void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010313{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010314 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010315 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010316 dprintf(fd, " %zu Tracks\n", numtracks);
10317 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010318 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010319 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010320 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010321 for (size_t i = 0; i < numtracks ; ++i) {
10322 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010323 result.append(prefix);
10324 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010325 }
10326 } else {
10327 dprintf(fd, "\n");
10328 }
10329 write(fd, result.string(), result.size());
10330}
10331
10332AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
10333 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010334 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010335 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010336 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010337 mStreamVolume(1.0),
10338 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010339 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010340{
10341 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10342 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
10343 mMasterVolume = audioFlinger->masterVolume_l();
10344 mMasterMute = audioFlinger->masterMute_l();
10345 if (mAudioHwDev) {
10346 if (mAudioHwDev->canSetMasterVolume()) {
10347 mMasterVolume = 1.0;
10348 }
10349
10350 if (mAudioHwDev->canSetMasterMute()) {
10351 mMasterMute = false;
10352 }
10353 }
10354}
10355
10356void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
10357 audio_stream_type_t streamType,
10358 audio_session_t sessionId,
10359 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010360 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010361 audio_port_handle_t portId)
10362{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010363 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010364 mStreamType = streamType;
10365}
10366
10367AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
10368{
10369 Mutex::Autolock _l(mLock);
10370 AudioStreamOut *output = mOutput;
10371 mOutput = NULL;
10372 return output;
10373}
10374
10375void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
10376{
10377 Mutex::Autolock _l(mLock);
10378 // Don't apply master volume in SW if our HAL can do it for us.
10379 if (mAudioHwDev &&
10380 mAudioHwDev->canSetMasterVolume()) {
10381 mMasterVolume = 1.0;
10382 } else {
10383 mMasterVolume = value;
10384 }
10385}
10386
10387void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
10388{
10389 Mutex::Autolock _l(mLock);
10390 // Don't apply master mute in SW if our HAL can do it for us.
10391 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10392 mMasterMute = false;
10393 } else {
10394 mMasterMute = muted;
10395 }
10396}
10397
10398void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
10399{
10400 Mutex::Autolock _l(mLock);
10401 if (stream == mStreamType) {
10402 mStreamVolume = value;
10403 broadcast_l();
10404 }
10405}
10406
10407float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
10408{
10409 Mutex::Autolock _l(mLock);
10410 if (stream == mStreamType) {
10411 return mStreamVolume;
10412 }
10413 return 0.0f;
10414}
10415
10416void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
10417{
10418 Mutex::Autolock _l(mLock);
10419 if (stream == mStreamType) {
10420 mStreamMute= muted;
10421 broadcast_l();
10422 }
10423}
10424
10425void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
10426{
10427 Mutex::Autolock _l(mLock);
10428 if (streamType == mStreamType) {
10429 for (const sp<MmapTrack> &track : mActiveTracks) {
10430 track->invalidate();
10431 }
10432 broadcast_l();
10433 }
10434}
10435
10436void AudioFlinger::MmapPlaybackThread::processVolume_l()
10437{
10438 float volume;
10439
10440 if (mMasterMute || mStreamMute) {
10441 volume = 0;
10442 } else {
10443 volume = mMasterVolume * mStreamVolume;
10444 }
10445
10446 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010447
10448 // Convert volumes from float to 8.24
10449 uint32_t vol = (uint32_t)(volume * (1 << 24));
10450
10451 // Delegate volume control to effect in track effect chain if needed
10452 // only one effect chain can be present on DirectOutputThread, so if
10453 // there is one, the track is connected to it
10454 if (!mEffectChains.isEmpty()) {
10455 mEffectChains[0]->setVolume_l(&vol, &vol);
10456 volume = (float)vol / (1 << 24);
10457 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010458 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010459 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10460 mHalVolFloat = volume; // HW volume control worked, so update value.
10461 mNoCallbackWarningCount = 0;
10462 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010463 sp<MmapStreamCallback> callback = mCallback.promote();
10464 if (callback != 0) {
10465 int channelCount;
10466 if (isOutput()) {
10467 channelCount = audio_channel_count_from_out_mask(mChannelMask);
10468 } else {
10469 channelCount = audio_channel_count_from_in_mask(mChannelMask);
10470 }
10471 Vector<float> values;
10472 for (int i = 0; i < channelCount; i++) {
10473 values.add(volume);
10474 }
Phil Burk56ecf3e2018-03-12 15:38:17 -070010475 mHalVolFloat = volume; // SW volume control worked, so update value.
10476 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010477 mLock.unlock();
10478 callback->onVolumeChanged(mChannelMask, values);
10479 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010480 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010481 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10482 ALOGW("Could not set MMAP stream volume: no volume callback!");
10483 mNoCallbackWarningCount++;
10484 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010485 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010486 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010487 for (const sp<MmapTrack> &track : mActiveTracks) {
10488 track->setMetadataHasChanged();
10489 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010490 }
10491}
10492
Kevin Rocard069c2712018-03-29 19:09:14 -070010493void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
10494{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010495 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10496 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010497 }
10498 StreamOutHalInterface::SourceMetadata metadata;
10499 for (const sp<MmapTrack> &track : mActiveTracks) {
10500 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010501 playback_track_metadata_v7_t trackMetadata;
10502 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010503 .usage = track->attributes().usage,
10504 .content_type = track->attributes().content_type,
10505 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010506 };
10507 trackMetadata.channel_mask = track->channelMask(),
10508 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10509 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010510 }
10511 mOutput->stream->updateSourceMetadata(metadata);
10512}
10513
Eric Laurent6acd1d42017-01-04 14:23:29 -080010514void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
10515{
10516 if (!mMasterMute) {
10517 char value[PROPERTY_VALUE_MAX];
10518 if (property_get("ro.audio.silent", value, "0") > 0) {
10519 char *endptr;
10520 unsigned long ul = strtoul(value, &endptr, 0);
10521 if (*endptr == '\0' && ul != 0) {
10522 ALOGD("Silence is golden");
10523 // The setprop command will not allow a property to be changed after
10524 // the first time it is set, so we don't have to worry about un-muting.
10525 setMasterMute_l(true);
10526 }
10527 }
10528 }
10529}
10530
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010531void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
10532{
10533 MmapThread::toAudioPortConfig(config);
10534 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10535 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10536 config->flags.output = mOutput->flags;
10537 }
10538}
10539
jiabinb7d8c5a2020-08-26 17:24:52 -070010540status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
10541 int64_t *timeNanos)
10542{
10543 if (mOutput == nullptr) {
10544 return NO_INIT;
10545 }
10546 struct timespec timestamp;
10547 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10548 if (status == NO_ERROR) {
10549 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10550 }
10551 return status;
10552}
10553
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010554void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010555{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010556 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010557
Glenn Kastend3bb6452016-12-05 18:14:37 -080010558 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10559 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010560 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10561}
10562
10563AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10564 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010565 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010566 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010567 mInput(input)
10568{
10569 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10570 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10571}
10572
Eric Laurent331679c2018-04-16 17:03:16 -070010573status_t AudioFlinger::MmapCaptureThread::exitStandby()
10574{
Phil Burkf054fc32018-12-06 09:45:59 -080010575 {
10576 // mInput might have been cleared by clearInput()
10577 Mutex::Autolock _l(mLock);
10578 if (mInput != nullptr && mInput->stream != nullptr) {
10579 mInput->stream->setGain(1.0f);
10580 }
10581 }
Eric Laurent331679c2018-04-16 17:03:16 -070010582 return MmapThread::exitStandby();
10583}
10584
Eric Laurent6acd1d42017-01-04 14:23:29 -080010585AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10586{
10587 Mutex::Autolock _l(mLock);
10588 AudioStreamIn *input = mInput;
10589 mInput = NULL;
10590 return input;
10591}
Kevin Rocard069c2712018-03-29 19:09:14 -070010592
Eric Laurent331679c2018-04-16 17:03:16 -070010593
10594void AudioFlinger::MmapCaptureThread::processVolume_l()
10595{
10596 bool changed = false;
10597 bool silenced = false;
10598
10599 sp<MmapStreamCallback> callback = mCallback.promote();
10600 if (callback == 0) {
10601 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10602 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10603 mNoCallbackWarningCount++;
10604 }
10605 }
10606
10607 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10608 // track is silenced and unmute otherwise
10609 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10610 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10611 changed = true;
10612 silenced = mActiveTracks[i]->isSilenced_l();
10613 }
10614 }
10615
10616 if (changed) {
10617 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10618 }
10619}
10620
Kevin Rocard069c2712018-03-29 19:09:14 -070010621void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10622{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010623 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10624 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010625 }
10626 StreamInHalInterface::SinkMetadata metadata;
10627 for (const sp<MmapTrack> &track : mActiveTracks) {
10628 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010629 record_track_metadata_v7_t trackMetadata;
10630 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010631 .source = track->attributes().source,
10632 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010633 };
10634 trackMetadata.channel_mask = track->channelMask(),
10635 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10636 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010637 }
10638 mInput->stream->updateSinkMetadata(metadata);
10639}
10640
Eric Laurent5ada82e2019-08-29 17:53:54 -070010641void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010642{
10643 Mutex::Autolock _l(mLock);
10644 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010645 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010646 mActiveTracks[i]->setSilenced_l(silenced);
10647 broadcast_l();
10648 }
10649 }
jiabincfc10a42022-06-15 19:26:01 +000010650 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070010651}
10652
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010653void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10654{
10655 MmapThread::toAudioPortConfig(config);
10656 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10657 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10658 config->flags.input = mInput->flags;
10659 }
10660}
10661
jiabinb7d8c5a2020-08-26 17:24:52 -070010662status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10663 uint64_t *position, int64_t *timeNanos)
10664{
10665 if (mInput == nullptr) {
10666 return NO_INIT;
10667 }
10668 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10669}
10670
Glenn Kasten63238ef2015-03-02 15:50:29 -080010671} // namespace android