blob: 767199f0d4b5f8005ca5dd4d4b1bdfda6a1f1ff3 [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>
Eric Laurent81784c32012-11-19 14:55:58 -080068
Mikhail Naganov2996f672019-04-18 12:29:59 -070069#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080070#include <powermanager/PowerManager.h>
71
Kevin Rocard7588ff42018-01-08 11:11:30 -080072#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070073#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080074
Eric Laurent81784c32012-11-19 14:55:58 -080075#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080076#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070077#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070078#include <mediautils/SchedulingPolicyService.h>
79#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080080
Eric Laurent81784c32012-11-19 14:55:58 -080081#ifdef ADD_BATTERY_DATA
82#include <media/IMediaPlayerService.h>
83#include <media/IMediaDeathNotifier.h>
84#endif
85
Eric Laurent81784c32012-11-19 14:55:58 -080086#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070087#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080088#include <cpustats/ThreadCpuUsage.h>
89#endif
90
Glenn Kastenc05b8d72016-03-24 09:48:17 -070091#include "AutoPark.h"
92
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080093#include <pthread.h>
94#include "TypedLogger.h"
95
Eric Laurent81784c32012-11-19 14:55:58 -080096// ----------------------------------------------------------------------------
97
98// Note: the following macro is used for extremely verbose logging message. In
99// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
100// 0; but one side effect of this is to turn all LOGV's as well. Some messages
101// are so verbose that we want to suppress them even when we have ALOG_ASSERT
102// turned on. Do not uncomment the #def below unless you really know what you
103// are doing and want to see all of the extremely verbose messages.
104//#define VERY_VERY_VERBOSE_LOGGING
105#ifdef VERY_VERY_VERBOSE_LOGGING
106#define ALOGVV ALOGV
107#else
108#define ALOGVV(a...) do { } while(0)
109#endif
110
Andy Hung6770c6f2015-04-07 13:43:36 -0700111// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700112#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700113
Andy Hung6770c6f2015-04-07 13:43:36 -0700114template <typename T>
115static inline T min(const T& a, const T& b)
116{
117 return a < b ? a : b;
118}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700119
Eric Laurent81784c32012-11-19 14:55:58 -0800120namespace android {
121
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700122using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000123using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700124
Eric Laurent81784c32012-11-19 14:55:58 -0800125// retry counts for buffer fill timeout
126// 50 * ~20msecs = 1 second
127static const int8_t kMaxTrackRetries = 50;
128static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700129
Eric Laurent81784c32012-11-19 14:55:58 -0800130// allow less retry attempts on direct output thread.
131// direct outputs can be a scarce resource in audio hardware and should
132// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700133// Notes:
134// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
135// in case the data write is bursty for the AudioTrack. The application
136// should endeavor to write at least once every kMaxTrackRetriesDirectMs
137// to prevent an underrun situation. If the data is bursty, then
138// the application can also throttle the data sent to be even.
139// 2) For compressed audio data, any data present in the AudioTrack buffer
140// will be sent and reset the retry count. This delivers data as
141// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
142// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
143// of data to be available, then any remaining data is delivered.
144// This is required to ensure the last bit of data is delivered before underrun.
145//
146// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
147// or the size of the HAL period for proportional / linear PCM tracks.
148static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800149
150// don't warn about blocked writes or record buffer overflows more often than this
151static const nsecs_t kWarningThrottleNs = seconds(5);
152
153// RecordThread loop sleep time upon application overrun or audio HAL read error
154static const int kRecordThreadSleepUs = 5000;
155
Eric Laurent10351942014-05-08 18:49:52 -0700156// maximum time to wait in sendConfigEvent_l() for a status to be received
157static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800158
159// minimum sleep time for the mixer thread loop when tracks are active but in underrun
160static const uint32_t kMinThreadSleepTimeUs = 5000;
161// maximum divider applied to the active sleep time in the mixer thread loop
162static const uint32_t kMaxThreadSleepTimeShift = 2;
163
Andy Hung09a50072014-02-27 14:30:47 -0800164// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700165// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800166static const uint32_t kMinNormalSinkBufferSizeMs = 20;
167// maximum normal sink buffer size
168static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800169
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700170// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
171// FIXME This should be based on experimentally observed scheduling jitter
172static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
173
Eric Laurent972a1732013-09-04 09:42:59 -0700174// Offloaded output thread standby delay: allows track transition without going to standby
175static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
176
Eric Laurent51716182016-02-29 18:00:56 -0800177// Direct output thread minimum sleep time in idle or active(underrun) state
178static const nsecs_t kDirectMinSleepTimeUs = 10000;
179
Glenn Kasten1b291842016-07-18 14:55:21 -0700180// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
181// balance between power consumption and latency, and allows threads to be scheduled reliably
182// by the CFS scheduler.
183// FIXME Express other hardcoded references to 20ms with references to this constant and move
184// it appropriately.
185#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800186
Eric Laurent81784c32012-11-19 14:55:58 -0800187// Whether to use fast mixer
188static const enum {
189 FastMixer_Never, // never initialize or use: for debugging only
190 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
191 // normal mixer multiplier is 1
192 FastMixer_Static, // initialize if needed, then use all the time if initialized,
193 // multiplier is calculated based on min & max normal mixer buffer size
194 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
195 // multiplier is calculated based on min & max normal mixer buffer size
196 // FIXME for FastMixer_Dynamic:
197 // Supporting this option will require fixing HALs that can't handle large writes.
198 // For example, one HAL implementation returns an error from a large write,
199 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
200 // We could either fix the HAL implementations, or provide a wrapper that breaks
201 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
202} kUseFastMixer = FastMixer_Static;
203
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700204// Whether to use fast capture
205static const enum {
206 FastCapture_Never, // never initialize or use: for debugging only
207 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
208 FastCapture_Static, // initialize if needed, then use all the time if initialized
209} kUseFastCapture = FastCapture_Static;
210
Eric Laurent81784c32012-11-19 14:55:58 -0800211// Priorities for requestPriority
212static const int kPriorityAudioApp = 2;
213static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700214static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800215
Glenn Kastenea38ee72016-04-18 11:08:01 -0700216// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
217// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
218// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700219
220// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800221static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800222
Glenn Kasten03490092014-05-27 12:30:54 -0700223// The minimum and maximum allowed values
224static const int kFastTrackMultiplierMin = 1;
225static const int kFastTrackMultiplierMax = 2;
226
227// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
228static int sFastTrackMultiplier = kFastTrackMultiplier;
229
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700230// See Thread::readOnlyHeap().
231// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
232// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
233// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700234static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700235
Eric Laurent81784c32012-11-19 14:55:58 -0800236// ----------------------------------------------------------------------------
237
Andy Hungb68f5eb2019-12-03 16:49:17 -0800238// TODO: move all toString helpers to audio.h
239// under #ifdef __cplusplus #endif
240static std::string patchSinksToString(const struct audio_patch *patch)
241{
242 std::stringstream ss;
243 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700244 if (i > 0) {
245 ss << "|";
246 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800247 ss << "(" << toString(patch->sinks[i].ext.device.type)
248 << ", " << patch->sinks[i].ext.device.address << ")";
249 }
250 return ss.str();
251}
252
253static std::string patchSourcesToString(const struct audio_patch *patch)
254{
255 std::stringstream ss;
256 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700257 if (i > 0) {
258 ss << "|";
259 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800260 ss << "(" << toString(patch->sources[i].ext.device.type)
261 << ", " << patch->sources[i].ext.device.address << ")";
262 }
263 return ss.str();
264}
265
Glenn Kasten03490092014-05-27 12:30:54 -0700266static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
267
268static void sFastTrackMultiplierInit()
269{
270 char value[PROPERTY_VALUE_MAX];
271 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
272 char *endptr;
273 unsigned long ul = strtoul(value, &endptr, 0);
274 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
275 sFastTrackMultiplier = (int) ul;
276 }
277 }
278}
279
280// ----------------------------------------------------------------------------
281
Eric Laurent81784c32012-11-19 14:55:58 -0800282#ifdef ADD_BATTERY_DATA
283// To collect the amplifier usage
284static void addBatteryData(uint32_t params) {
285 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
286 if (service == NULL) {
287 // it already logged
288 return;
289 }
290
291 service->addBatteryData(params);
292}
293#endif
294
Andy Hung3f0c9022016-01-15 17:49:46 -0800295// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
296struct {
297 // call when you acquire a partial wakelock
298 void acquire(const sp<IBinder> &wakeLockToken) {
299 pthread_mutex_lock(&mLock);
300 if (wakeLockToken.get() == nullptr) {
301 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
302 } else {
303 if (mCount == 0) {
304 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
305 }
306 ++mCount;
307 }
308 pthread_mutex_unlock(&mLock);
309 }
310
311 // call when you release a partial wakelock.
312 void release(const sp<IBinder> &wakeLockToken) {
313 if (wakeLockToken.get() == nullptr) {
314 return;
315 }
316 pthread_mutex_lock(&mLock);
317 if (--mCount < 0) {
318 ALOGE("negative wakelock count");
319 mCount = 0;
320 }
321 pthread_mutex_unlock(&mLock);
322 }
323
324 // retrieves the boottime timebase offset from monotonic.
325 int64_t getBoottimeOffset() {
326 pthread_mutex_lock(&mLock);
327 int64_t boottimeOffset = mBoottimeOffset;
328 pthread_mutex_unlock(&mLock);
329 return boottimeOffset;
330 }
331
332 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
333 // and the selected timebase.
334 // Currently only TIMEBASE_BOOTTIME is allowed.
335 //
336 // This only needs to be called upon acquiring the first partial wakelock
337 // after all other partial wakelocks are released.
338 //
339 // We do an empirical measurement of the offset rather than parsing
340 // /proc/timer_list since the latter is not a formal kernel ABI.
341 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
342 int clockbase;
343 switch (timebase) {
344 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
345 clockbase = SYSTEM_TIME_BOOTTIME;
346 break;
347 default:
348 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
349 break;
350 }
351 // try three times to get the clock offset, choose the one
352 // with the minimum gap in measurements.
353 const int tries = 3;
354 nsecs_t bestGap, measured;
355 for (int i = 0; i < tries; ++i) {
356 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
357 const nsecs_t tbase = systemTime(clockbase);
358 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
359 const nsecs_t gap = tmono2 - tmono;
360 if (i == 0 || gap < bestGap) {
361 bestGap = gap;
362 measured = tbase - ((tmono + tmono2) >> 1);
363 }
364 }
365
366 // to avoid micro-adjusting, we don't change the timebase
367 // unless it is significantly different.
368 //
369 // Assumption: It probably takes more than toleranceNs to
370 // suspend and resume the device.
371 static int64_t toleranceNs = 10000; // 10 us
372 if (llabs(*offset - measured) > toleranceNs) {
373 ALOGV("Adjusting timebase offset old: %lld new: %lld",
374 (long long)*offset, (long long)measured);
375 *offset = measured;
376 }
377 }
378
379 pthread_mutex_t mLock;
380 int32_t mCount;
381 int64_t mBoottimeOffset;
382} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800383
384// ----------------------------------------------------------------------------
385// CPU Stats
386// ----------------------------------------------------------------------------
387
388class CpuStats {
389public:
390 CpuStats();
391 void sample(const String8 &title);
392#ifdef DEBUG_CPU_USAGE
393private:
394 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700395 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800396
Andy Hung16698b82018-08-01 10:48:38 -0700397 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800398
399 int mCpuNum; // thread's current CPU number
400 int mCpukHz; // frequency of thread's current CPU in kHz
401#endif
402};
403
404CpuStats::CpuStats()
405#ifdef DEBUG_CPU_USAGE
406 : mCpuNum(-1), mCpukHz(-1)
407#endif
408{
409}
410
Glenn Kasten0f11b512014-01-31 16:18:54 -0800411void CpuStats::sample(const String8 &title
412#ifndef DEBUG_CPU_USAGE
413 __unused
414#endif
415 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800416#ifdef DEBUG_CPU_USAGE
417 // get current thread's delta CPU time in wall clock ns
418 double wcNs;
419 bool valid = mCpuUsage.sampleAndEnable(wcNs);
420
421 // record sample for wall clock statistics
422 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700423 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800424 }
425
426 // get the current CPU number
427 int cpuNum = sched_getcpu();
428
429 // get the current CPU frequency in kHz
430 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
431
432 // check if either CPU number or frequency changed
433 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
434 mCpuNum = cpuNum;
435 mCpukHz = cpukHz;
436 // ignore sample for purposes of cycles
437 valid = false;
438 }
439
440 // if no change in CPU number or frequency, then record sample for cycle statistics
441 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700442 const double cycles = wcNs * cpukHz * 0.000001;
443 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800444 }
445
Eric Tan5b13ff82018-07-27 11:20:17 -0700446 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800447 // mCpuUsage.elapsed() is expensive, so don't call it every loop
448 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700449 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800450 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700451 const double perLoop = elapsed / (double) n;
452 const double perLoop100 = perLoop * 0.01;
453 const double perLoop1k = perLoop * 0.001;
454 const double mean = mWcStats.getMean();
455 const double stddev = mWcStats.getStdDev();
456 const double minimum = mWcStats.getMin();
457 const double maximum = mWcStats.getMax();
458 const double meanCycles = mHzStats.getMean();
459 const double stddevCycles = mHzStats.getStdDev();
460 const double minCycles = mHzStats.getMin();
461 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800462 mCpuUsage.resetElapsed();
463 mWcStats.reset();
464 mHzStats.reset();
465 ALOGD("CPU usage for %s over past %.1f secs\n"
466 " (%u mixer loops at %.1f mean ms per loop):\n"
467 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
468 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
469 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
470 title.string(),
471 elapsed * .000000001, n, perLoop * .000001,
472 mean * .001,
473 stddev * .001,
474 minimum * .001,
475 maximum * .001,
476 mean / perLoop100,
477 stddev / perLoop100,
478 minimum / perLoop100,
479 maximum / perLoop100,
480 meanCycles / perLoop1k,
481 stddevCycles / perLoop1k,
482 minCycles / perLoop1k,
483 maxCycles / perLoop1k);
484
485 }
486 }
487#endif
488};
489
490// ----------------------------------------------------------------------------
491// ThreadBase
492// ----------------------------------------------------------------------------
493
Glenn Kasten97b7b752014-09-28 13:04:24 -0700494// static
495const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
496{
497 switch (type) {
498 case MIXER:
499 return "MIXER";
500 case DIRECT:
501 return "DIRECT";
502 case DUPLICATING:
503 return "DUPLICATING";
504 case RECORD:
505 return "RECORD";
506 case OFFLOAD:
507 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700508 case MMAP_PLAYBACK:
509 return "MMAP_PLAYBACK";
510 case MMAP_CAPTURE:
511 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200512 case SPATIALIZER:
513 return "SPATIALIZER";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700514 default:
515 return "unknown";
516 }
517}
518
Eric Laurent81784c32012-11-19 14:55:58 -0800519AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700520 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800521 : Thread(false /*canCallJava*/),
522 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700523 mAudioFlinger(audioFlinger),
Andy Hungcf10d742020-04-28 15:38:24 -0700524 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
525 isOut),
526 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700527 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800528 // are set by PlaybackThread::readOutputParameters_l() or
529 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700530 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700531 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700532 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800533 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700534 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800535 mSystemReady(systemReady),
536 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800537{
Andy Hungcf10d742020-04-28 15:38:24 -0700538 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700539 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800540}
541
542AudioFlinger::ThreadBase::~ThreadBase()
543{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700544 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700545 mConfigEvents.clear();
546
Eric Laurent81784c32012-11-19 14:55:58 -0800547 // do not lock the mutex in destructor
548 releaseWakeLock_l();
549 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800550 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800551 binder->unlinkToDeath(mDeathRecipient);
552 }
Andy Hungd0979812019-02-21 15:51:44 -0800553
554 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800555}
556
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700557status_t AudioFlinger::ThreadBase::readyToRun()
558{
559 status_t status = initCheck();
560 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800561 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700562 } else {
563 ALOGE("No working audio driver found.");
564 }
565 return status;
566}
567
Eric Laurent81784c32012-11-19 14:55:58 -0800568void AudioFlinger::ThreadBase::exit()
569{
570 ALOGV("ThreadBase::exit");
571 // do any cleanup required for exit to succeed
572 preExit();
573 {
574 // This lock prevents the following race in thread (uniprocessor for illustration):
575 // if (!exitPending()) {
576 // // context switch from here to exit()
577 // // exit() calls requestExit(), what exitPending() observes
578 // // exit() calls signal(), which is dropped since no waiters
579 // // context switch back from exit() to here
580 // mWaitWorkCV.wait(...);
581 // // now thread is hung
582 // }
583 AutoMutex lock(mLock);
584 requestExit();
585 mWaitWorkCV.broadcast();
586 }
587 // When Thread::requestExitAndWait is made virtual and this method is renamed to
588 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
589 requestExitAndWait();
590}
591
592status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
593{
Eric Laurent81784c32012-11-19 14:55:58 -0800594 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
595 Mutex::Autolock _l(mLock);
596
Eric Laurent10351942014-05-08 18:49:52 -0700597 return sendSetParameterConfigEvent_l(keyValuePairs);
598}
599
600// sendConfigEvent_l() must be called with ThreadBase::mLock held
601// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
602status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
603{
604 status_t status = NO_ERROR;
605
Eric Laurent72e3f392015-05-20 14:43:50 -0700606 if (event->mRequiresSystemReady && !mSystemReady) {
607 event->mWaitStatus = false;
608 mPendingConfigEvents.add(event);
609 return status;
610 }
Eric Laurent10351942014-05-08 18:49:52 -0700611 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700612 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800613 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700614 mLock.unlock();
615 {
616 Mutex::Autolock _l(event->mLock);
617 while (event->mWaitStatus) {
618 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
619 event->mStatus = TIMED_OUT;
620 event->mWaitStatus = false;
621 }
622 }
623 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800624 }
Eric Laurent10351942014-05-08 18:49:52 -0700625 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800626 return status;
627}
628
Eric Laurent09f1ed22019-04-24 17:45:17 -0700629void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid,
630 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800631{
632 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700633 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800634}
635
636// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent09f1ed22019-04-24 17:45:17 -0700637void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid,
638 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800639{
Andy Hungd0979812019-02-21 15:51:44 -0800640 // The audio statistics history is exponentially weighted to forget events
641 // about five or more seconds in the past. In order to have
642 // crisper statistics for mediametrics, we reset the statistics on
643 // an IoConfigEvent, to reflect different properties for a new device.
644 mIoJitterMs.reset();
645 mLatencyMs.reset();
646 mProcessTimeMs.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100647 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800648
Eric Laurent09f1ed22019-04-24 17:45:17 -0700649 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700650 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800651}
652
Mikhail Naganov83f04272017-02-07 10:45:09 -0800653void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700654{
655 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800656 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700657}
658
Eric Laurent81784c32012-11-19 14:55:58 -0800659// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800660void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
661 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800662{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800663 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700664 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800665}
666
Eric Laurent10351942014-05-08 18:49:52 -0700667// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
668status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800669{
Andy Hung2ddee192015-12-18 17:34:44 -0800670 sp<ConfigEvent> configEvent;
671 AudioParameter param(keyValuePair);
672 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700673 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800674 setMasterMono_l(value != 0);
675 if (param.size() == 1) {
676 return NO_ERROR; // should be a solo parameter - we don't pass down
677 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700678 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800679 configEvent = new SetParameterConfigEvent(param.toString());
680 } else {
681 configEvent = new SetParameterConfigEvent(keyValuePair);
682 }
Eric Laurent10351942014-05-08 18:49:52 -0700683 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700684}
685
Eric Laurent1c333e22014-05-20 10:48:17 -0700686status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
687 const struct audio_patch *patch,
688 audio_patch_handle_t *handle)
689{
690 Mutex::Autolock _l(mLock);
691 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
692 status_t status = sendConfigEvent_l(configEvent);
693 if (status == NO_ERROR) {
694 CreateAudioPatchConfigEventData *data =
695 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
696 *handle = data->mHandle;
697 }
698 return status;
699}
700
701status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
702 const audio_patch_handle_t handle)
703{
704 Mutex::Autolock _l(mLock);
705 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
706 return sendConfigEvent_l(configEvent);
707}
708
jiabinc52b1ff2019-10-31 17:20:42 -0700709status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
710 const DeviceDescriptorBaseVector& outDevices)
711{
712 if (type() != RECORD) {
713 // The update out device operation is only for record thread.
714 return INVALID_OPERATION;
715 }
716 Mutex::Autolock _l(mLock);
717 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
718 return sendConfigEvent_l(configEvent);
719}
720
Eric Laurentec376dc2021-04-08 20:41:22 +0200721void AudioFlinger::ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
722{
723 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
724 sp<ConfigEvent> configEvent =
725 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
726 sendConfigEvent_l(configEvent);
727}
Eric Laurent1c333e22014-05-20 10:48:17 -0700728
Eric Laurentb3f315a2021-07-13 15:09:05 +0200729void AudioFlinger::ThreadBase::sendCheckOutputStageEffectsEvent()
730{
731 Mutex::Autolock _l(mLock);
732 sendCheckOutputStageEffectsEvent_l();
733}
734
735void AudioFlinger::ThreadBase::sendCheckOutputStageEffectsEvent_l()
736{
737 sp<ConfigEvent> configEvent =
738 (ConfigEvent *)new CheckOutputStageEffectsEvent();
739 sendConfigEvent_l(configEvent);
740}
741
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700742// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700743void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700744{
Eric Laurent10351942014-05-08 18:49:52 -0700745 bool configChanged = false;
746
Eric Laurent81784c32012-11-19 14:55:58 -0800747 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700748 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700749 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800750 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700751 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700752 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700753 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
754 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800755 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700756 true /*asynchronous*/);
757 if (err != 0) {
758 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700759 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700760 }
761 } break;
762 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700763 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700764 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700765 } break;
766 case CFG_EVENT_SET_PARAMETER: {
767 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
768 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
769 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700770 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
771 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700772 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700773 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700774 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700775 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700776 CreateAudioPatchConfigEventData *data =
777 (CreateAudioPatchConfigEventData *)event->mData.get();
778 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700779 const DeviceTypeSet newDevices = getDeviceTypes();
780 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
781 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
782 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700783 } break;
784 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700785 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700786 ReleaseAudioPatchConfigEventData *data =
787 (ReleaseAudioPatchConfigEventData *)event->mData.get();
788 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700789 const DeviceTypeSet newDevices = getDeviceTypes();
790 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
791 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
792 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
793 } break;
794 case CFG_EVENT_UPDATE_OUT_DEVICE: {
795 UpdateOutDevicesConfigEventData *data =
796 (UpdateOutDevicesConfigEventData *)event->mData.get();
797 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700798 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200799 case CFG_EVENT_RESIZE_BUFFER: {
800 ResizeBufferConfigEventData *data =
801 (ResizeBufferConfigEventData *)event->mData.get();
802 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
803 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200804
805 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
806 setCheckOutputStageEffects();
807 } break;
808
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700809 default:
Eric Laurent10351942014-05-08 18:49:52 -0700810 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700811 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800812 }
Eric Laurent10351942014-05-08 18:49:52 -0700813 {
814 Mutex::Autolock _l(event->mLock);
815 if (event->mWaitStatus) {
816 event->mWaitStatus = false;
817 event->mCond.signal();
818 }
819 }
820 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
821 }
822
823 if (configChanged) {
824 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800825 }
Eric Laurent81784c32012-11-19 14:55:58 -0800826}
827
Marco Nelissenb2208842014-02-07 14:00:50 -0800828String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
829 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700830 const audio_channel_representation_t representation =
831 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700832
833 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800834 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700835 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
836 if (output) {
837 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
838 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
839 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700840 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700841 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
842 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
843 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
844 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
845 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
846 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
847 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
848 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
849 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
850 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
851 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
852 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700853 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
854 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
855 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
856 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
857 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
858 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
859 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700860 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700861 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
862 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700863 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
864 } else {
865 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
866 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
867 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
868 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
869 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
870 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
871 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
872 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
873 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
874 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
875 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
876 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700877 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
878 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
879 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700880 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700881 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
882 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700883 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
884 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
885 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
886 }
887 const int len = s.length();
888 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700889 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700890 s.unlockBuffer(len - 2); // remove trailing ", "
891 }
892 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800893 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700894 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
895 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
896 return s;
897 default:
898 s.appendFormat("unknown mask, representation:%d bits:%#x",
899 representation, audio_channel_mask_get_bits(mask));
900 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800901 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800902}
903
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700904void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800905{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800906 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
907 this, mThreadName, getTid(), type(), threadTypeToString(type()));
908
Eric Laurent81784c32012-11-19 14:55:58 -0800909 bool locked = AudioFlinger::dumpTryLock(mLock);
910 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800911 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800912 }
913
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700914 dumpBase_l(fd, args);
915 dumpInternals_l(fd, args);
916 dumpTracks_l(fd, args);
917 dumpEffectChains_l(fd, args);
918
919 if (locked) {
920 mLock.unlock();
921 }
922
923 dprintf(fd, " Local log:\n");
924 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
925}
926
927void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
928{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700929 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700930 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700931 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700932 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700933 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700934 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700935 dprintf(fd, " Channel count: %u\n", mChannelCount);
936 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800937 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700938 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700939 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700940 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800941 size_t numConfig = mConfigEvents.size();
942 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700943 const size_t SIZE = 256;
944 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800945 for (size_t i = 0; i < numConfig; i++) {
946 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700947 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800948 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700949 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800950 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700951 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800952 }
Andy Hung293558a2017-03-21 12:19:20 -0700953 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -0700954 dprintf(fd, " Output devices: %s (%s)\n",
955 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
956 dprintf(fd, " Input device: %#x (%s)\n",
957 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800958 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800959
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700960 // Dump timestamp statistics for the Thread types that support it.
961 if (mType == RECORD
962 || mType == MIXER
963 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700964 || mType == DIRECT
965 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700966 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700967 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700968 }
969
Andy Hung446f4df2019-02-21 12:26:41 -0800970 if (mLastIoBeginNs > 0) { // MMAP may not set this
971 dprintf(fd, " Last %s occurred (msecs): %lld\n",
972 isOutput() ? "write" : "read",
973 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
974 }
975
976 if (mProcessTimeMs.getN() > 0) {
977 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
978 }
979
980 if (mIoJitterMs.getN() > 0) {
981 dprintf(fd, " Hal %s jitter ms stats: %s\n",
982 isOutput() ? "write" : "read",
983 mIoJitterMs.toString().c_str());
984 }
985
Andy Hunge6c37112019-02-26 17:38:10 -0800986 if (mLatencyMs.getN() > 0) {
987 dprintf(fd, " Threadloop %s latency stats: %s\n",
988 isOutput() ? "write" : "read",
989 mLatencyMs.toString().c_str());
990 }
Eric Laurent81784c32012-11-19 14:55:58 -0800991}
992
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700993void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800994{
995 const size_t SIZE = 256;
996 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -0800997
Marco Nelissenb2208842014-02-07 14:00:50 -0800998 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000999 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001000 write(fd, buffer, strlen(buffer));
1001
Marco Nelissenb2208842014-02-07 14:00:50 -08001002 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -08001003 sp<EffectChain> chain = mEffectChains[i];
1004 if (chain != 0) {
1005 chain->dump(fd, args);
1006 }
1007 }
1008}
1009
Andy Hungdae27702016-10-31 14:01:16 -07001010void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001011{
1012 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07001013 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001014}
1015
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001016String16 AudioFlinger::ThreadBase::getWakeLockTag()
1017{
1018 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001019 case MIXER:
1020 return String16("AudioMix");
1021 case DIRECT:
1022 return String16("AudioDirectOut");
1023 case DUPLICATING:
1024 return String16("AudioDup");
1025 case RECORD:
1026 return String16("AudioIn");
1027 case OFFLOAD:
1028 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001029 case MMAP_PLAYBACK:
1030 return String16("MmapPlayback");
1031 case MMAP_CAPTURE:
1032 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001033 case SPATIALIZER:
1034 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001035 default:
1036 ALOG_ASSERT(false);
1037 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001038 }
1039}
1040
Andy Hungdae27702016-10-31 14:01:16 -07001041void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001042{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001043 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001044 if (mPowerManager != 0) {
1045 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001046 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001047 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1048 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001049 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001050 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001051 {} /* workSource */,
1052 {} /* historyTag */);
1053 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001054 mWakeLockToken = binder;
1055 }
Chris Ye6597d732020-02-28 22:38:25 -08001056 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001057 }
Wei Jia3f273d12015-11-24 09:06:49 -08001058
Andy Hung3f0c9022016-01-15 17:49:46 -08001059 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001060 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1061 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001062}
1063
1064void AudioFlinger::ThreadBase::releaseWakeLock()
1065{
1066 Mutex::Autolock _l(mLock);
1067 releaseWakeLock_l();
1068}
1069
1070void AudioFlinger::ThreadBase::releaseWakeLock_l()
1071{
Andy Hung3f0c9022016-01-15 17:49:46 -08001072 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001073 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001074 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001075 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001076 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001077 }
1078 mWakeLockToken.clear();
1079 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001080}
1081
1082void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001083 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001084 // use checkService() to avoid blocking if power service is not up yet
1085 sp<IBinder> binder =
1086 defaultServiceManager()->checkService(String16("power"));
1087 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001088 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001089 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001090 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001091 binder->linkToDeath(mDeathRecipient);
1092 }
1093 }
1094}
1095
Andy Hungd01b0f12016-11-07 16:10:30 -08001096void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001097 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001098
1099#if !LOG_NDEBUG
1100 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001101 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001102 s << uid << " ";
1103 }
1104 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1105#endif
1106
Andy Hung438e7572015-12-14 15:51:17 -08001107 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1108 if (mSystemReady) {
1109 ALOGE("no wake lock to update, but system ready!");
1110 } else {
1111 ALOGW("no wake lock to update, system not ready yet");
1112 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001113 return;
1114 }
1115 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001116 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001117 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1118 mWakeLockToken, uidsAsInt);
1119 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001120 }
1121}
1122
Eric Laurent81784c32012-11-19 14:55:58 -08001123void AudioFlinger::ThreadBase::clearPowerManager()
1124{
1125 Mutex::Autolock _l(mLock);
1126 releaseWakeLock_l();
1127 mPowerManager.clear();
1128}
1129
jiabinc52b1ff2019-10-31 17:20:42 -07001130void AudioFlinger::ThreadBase::updateOutDevices(
1131 const DeviceDescriptorBaseVector& outDevices __unused)
1132{
1133 ALOGE("%s should only be called in RecordThread", __func__);
1134}
1135
Eric Laurentec376dc2021-04-08 20:41:22 +02001136void AudioFlinger::ThreadBase::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs __unused)
1137{
1138 ALOGE("%s should only be called in RecordThread", __func__);
1139}
1140
Glenn Kasten0f11b512014-01-31 16:18:54 -08001141void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001142{
1143 sp<ThreadBase> thread = mThread.promote();
1144 if (thread != 0) {
1145 thread->clearPowerManager();
1146 }
1147 ALOGW("power manager service died !!!");
1148}
1149
Eric Laurent81784c32012-11-19 14:55:58 -08001150void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001151 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001152{
1153 sp<EffectChain> chain = getEffectChain_l(sessionId);
1154 if (chain != 0) {
1155 if (type != NULL) {
1156 chain->setEffectSuspended_l(type, suspend);
1157 } else {
1158 chain->setEffectSuspendedAll_l(suspend);
1159 }
1160 }
1161
1162 updateSuspendedSessions_l(type, suspend, sessionId);
1163}
1164
1165void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1166{
1167 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1168 if (index < 0) {
1169 return;
1170 }
1171
1172 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1173 mSuspendedSessions.valueAt(index);
1174
1175 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001176 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001177 for (int j = 0; j < desc->mRefCount; j++) {
1178 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1179 chain->setEffectSuspendedAll_l(true);
1180 } else {
1181 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1182 desc->mType.timeLow);
1183 chain->setEffectSuspended_l(&desc->mType, true);
1184 }
1185 }
1186 }
1187}
1188
1189void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1190 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001191 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001192{
1193 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1194
1195 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1196
1197 if (suspend) {
1198 if (index >= 0) {
1199 sessionEffects = mSuspendedSessions.valueAt(index);
1200 } else {
1201 mSuspendedSessions.add(sessionId, sessionEffects);
1202 }
1203 } else {
1204 if (index < 0) {
1205 return;
1206 }
1207 sessionEffects = mSuspendedSessions.valueAt(index);
1208 }
1209
1210
1211 int key = EffectChain::kKeyForSuspendAll;
1212 if (type != NULL) {
1213 key = type->timeLow;
1214 }
1215 index = sessionEffects.indexOfKey(key);
1216
1217 sp<SuspendedSessionDesc> desc;
1218 if (suspend) {
1219 if (index >= 0) {
1220 desc = sessionEffects.valueAt(index);
1221 } else {
1222 desc = new SuspendedSessionDesc();
1223 if (type != NULL) {
1224 desc->mType = *type;
1225 }
1226 sessionEffects.add(key, desc);
1227 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1228 }
1229 desc->mRefCount++;
1230 } else {
1231 if (index < 0) {
1232 return;
1233 }
1234 desc = sessionEffects.valueAt(index);
1235 if (--desc->mRefCount == 0) {
1236 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1237 sessionEffects.removeItemsAt(index);
1238 if (sessionEffects.isEmpty()) {
1239 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1240 sessionId);
1241 mSuspendedSessions.removeItem(sessionId);
1242 }
1243 }
1244 }
1245 if (!sessionEffects.isEmpty()) {
1246 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1247 }
1248}
1249
Eric Laurent6b446ce2019-12-13 10:56:31 -08001250void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1251 audio_session_t sessionId,
1252 bool threadLocked) {
1253 if (!threadLocked) {
1254 mLock.lock();
1255 }
Eric Laurent81784c32012-11-19 14:55:58 -08001256
Eric Laurent81784c32012-11-19 14:55:58 -08001257 if (mType != RECORD) {
1258 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1259 // another session. This gives the priority to well behaved effect control panels
1260 // and applications not using global effects.
1261 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1262 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001263 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001264 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1265 }
1266 }
1267
Eric Laurent6b446ce2019-12-13 10:56:31 -08001268 if (!threadLocked) {
1269 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001270 }
1271}
1272
Eric Laurent4c415062016-06-17 16:14:16 -07001273// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1274status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1275 const effect_descriptor_t *desc, audio_session_t sessionId)
1276{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001277 // No global output effect sessions on record threads
1278 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1279 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001280 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1281 desc->name, mThreadName);
1282 return BAD_VALUE;
1283 }
1284 // only pre processing effects on record thread
1285 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1286 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1287 desc->name, mThreadName);
1288 return BAD_VALUE;
1289 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001290
1291 // always allow effects without processing load or latency
1292 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1293 return NO_ERROR;
1294 }
1295
Eric Laurent4c415062016-06-17 16:14:16 -07001296 audio_input_flags_t flags = mInput->flags;
1297 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1298 if (flags & AUDIO_INPUT_FLAG_RAW) {
1299 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1300 desc->name, mThreadName);
1301 return BAD_VALUE;
1302 }
1303 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1304 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1305 desc->name, mThreadName);
1306 return BAD_VALUE;
1307 }
1308 }
jiabineb3bda02020-06-30 14:07:03 -07001309
1310 if (EffectModule::isHapticGenerator(&desc->type)) {
1311 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1312 return BAD_VALUE;
1313 }
Eric Laurent4c415062016-06-17 16:14:16 -07001314 return NO_ERROR;
1315}
1316
1317// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1318status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1319 const effect_descriptor_t *desc, audio_session_t sessionId)
1320{
1321 // no preprocessing on playback threads
1322 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1323 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1324 " thread %s", desc->name, mThreadName);
1325 return BAD_VALUE;
1326 }
1327
Eric Laurent3e4de772017-07-16 16:55:08 -07001328 // always allow effects without processing load or latency
1329 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1330 return NO_ERROR;
1331 }
1332
jiabineb3bda02020-06-30 14:07:03 -07001333 if (EffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
1334 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1335 __func__);
1336 return BAD_VALUE;
1337 }
1338
Eric Laurent4c415062016-06-17 16:14:16 -07001339 switch (mType) {
1340 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001341#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001342 // Reject any effect on mixer multichannel sinks.
1343 // TODO: fix both format and multichannel issues with effects.
1344 if (mChannelCount != FCC_2) {
1345 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1346 " thread %s", desc->name, mChannelCount, mThreadName);
1347 return BAD_VALUE;
1348 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001349#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001350 audio_output_flags_t flags = mOutput->flags;
1351 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1352 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1353 // global effects are applied only to non fast tracks if they are SW
1354 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1355 break;
1356 }
1357 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1358 // only post processing on output stage session
1359 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1360 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1361 " on output stage session", desc->name);
1362 return BAD_VALUE;
1363 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001364 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1365 // only post processing on output stage session
1366 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1367 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1368 " on device session", desc->name);
1369 return BAD_VALUE;
1370 }
Eric Laurent4c415062016-06-17 16:14:16 -07001371 } else {
1372 // no restriction on effects applied on non fast tracks
1373 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1374 break;
1375 }
1376 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001377
Eric Laurent4c415062016-06-17 16:14:16 -07001378 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1379 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1380 desc->name);
1381 return BAD_VALUE;
1382 }
1383 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1384 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1385 " in fast mode", desc->name);
1386 return BAD_VALUE;
1387 }
1388 }
1389 } break;
1390 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001391 // nothing actionable on offload threads, if the effect:
1392 // - is offloadable: the effect can be created
1393 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1394 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001395 break;
1396 case DIRECT:
1397 // Reject any effect on Direct output threads for now, since the format of
1398 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1399 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1400 desc->name, mThreadName);
1401 return BAD_VALUE;
1402 case DUPLICATING:
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) {
1407 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1408 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1409 return BAD_VALUE;
1410 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001411#endif
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001412 if (audio_is_global_session(sessionId)) {
Eric Laurent4c415062016-06-17 16:14:16 -07001413 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1414 " thread %s", desc->name, mThreadName);
1415 return BAD_VALUE;
1416 }
1417 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1418 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1419 " DUPLICATING thread %s", desc->name, mThreadName);
1420 return BAD_VALUE;
1421 }
1422 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1423 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1424 " DUPLICATING thread %s", desc->name, mThreadName);
1425 return BAD_VALUE;
1426 }
1427 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001428 case SPATIALIZER:
Eric Laurentb3f315a2021-07-13 15:09:05 +02001429 if (!audio_is_global_session(sessionId)) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001430 ALOGW("checkEffectCompatibility_l(): non global effect %s on SPATIALIZER"
Eric Laurentb3f315a2021-07-13 15:09:05 +02001431 " thread %s", desc->name, mThreadName);
1432 return BAD_VALUE;
1433 }
1434 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001435 default:
1436 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1437 }
1438
1439 return NO_ERROR;
1440}
1441
Eric Laurent81784c32012-11-19 14:55:58 -08001442// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1443sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1444 const sp<AudioFlinger::Client>& client,
1445 const sp<IEffectClient>& effectClient,
1446 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001447 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001448 effect_descriptor_t *desc,
1449 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001450 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001451 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001452 bool probe,
1453 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001454{
1455 sp<EffectModule> effect;
1456 sp<EffectHandle> handle;
1457 status_t lStatus;
1458 sp<EffectChain> chain;
1459 bool chainCreated = false;
1460 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001461 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001462
1463 lStatus = initCheck();
1464 if (lStatus != NO_ERROR) {
1465 ALOGW("createEffect_l() Audio driver not initialized.");
1466 goto Exit;
1467 }
1468
Eric Laurent81784c32012-11-19 14:55:58 -08001469 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1470
1471 { // scope for mLock
1472 Mutex::Autolock _l(mLock);
1473
Eric Laurent4c415062016-06-17 16:14:16 -07001474 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001475 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001476 goto Exit;
1477 }
1478
Eric Laurent81784c32012-11-19 14:55:58 -08001479 // check for existing effect chain with the requested audio session
1480 chain = getEffectChain_l(sessionId);
1481 if (chain == 0) {
1482 // create a new chain for this session
1483 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1484 chain = new EffectChain(this, sessionId);
1485 addEffectChain_l(chain);
1486 chain->setStrategy(getStrategyForSession_l(sessionId));
1487 chainCreated = true;
1488 } else {
1489 effect = chain->getEffectFromDesc_l(desc);
1490 }
1491
1492 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1493
1494 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001495 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001496 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001497 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001498 if (lStatus != NO_ERROR) {
1499 goto Exit;
1500 }
1501 effectCreated = true;
1502
jiabinc52b1ff2019-10-31 17:20:42 -07001503 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001504 effect->setDevices(outDeviceTypeAddrs());
1505 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001506 effect->setMode(mAudioFlinger->getMode());
1507 effect->setAudioSource(mAudioSource);
1508 }
jiabin1319f5a2021-03-30 22:21:24 +00001509 if (effect->isHapticGenerator()) {
1510 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1511 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001512 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
1513 std::move(mAudioFlinger->getDefaultVibratorInfo_l());
1514 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001515 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001516 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001517 }
1518 }
Eric Laurent81784c32012-11-19 14:55:58 -08001519 // create effect handle and connect it to effect module
Eric Laurentde8caf42021-08-11 17:19:25 +02001520 handle = new EffectHandle(effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001521 lStatus = handle->initCheck();
1522 if (lStatus == OK) {
1523 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001524 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001525 }
Eric Laurent81784c32012-11-19 14:55:58 -08001526 if (enabled != NULL) {
1527 *enabled = (int)effect->isEnabled();
1528 }
1529 }
1530
1531Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001532 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001533 Mutex::Autolock _l(mLock);
1534 if (effectCreated) {
1535 chain->removeEffect_l(effect);
1536 }
Eric Laurent81784c32012-11-19 14:55:58 -08001537 if (chainCreated) {
1538 removeEffectChain_l(chain);
1539 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001540 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001541 }
1542
Glenn Kasten9156ef32013-08-06 15:39:08 -07001543 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001544 return handle;
1545}
1546
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001547void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1548 bool unpinIfLast)
1549{
1550 bool remove = false;
1551 sp<EffectModule> effect;
1552 {
1553 Mutex::Autolock _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001554 sp<EffectBase> effectBase = handle->effect().promote();
1555 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001556 return;
1557 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001558 effect = effectBase->asEffectModule();
1559 if (effect == nullptr) {
1560 return;
1561 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001562 // restore suspended effects if the disconnected handle was enabled and the last one.
1563 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1564 if (remove) {
1565 removeEffect_l(effect, true);
1566 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001567 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001568 }
1569 if (remove) {
1570 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001571 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001572 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001573 }
1574 }
1575}
1576
Eric Laurent6b446ce2019-12-13 10:56:31 -08001577void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001578 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001579 Mutex::Autolock _l(mLock);
1580 broadcast_l();
1581 }
1582 if (!effect->isOffloadable()) {
1583 if (mType == ThreadBase::OFFLOAD) {
1584 PlaybackThread *t = (PlaybackThread *)this;
1585 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1586 }
1587 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1588 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1589 }
1590 }
1591}
1592
1593void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001594 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001595 Mutex::Autolock _l(mLock);
1596 broadcast_l();
1597 }
1598}
1599
Glenn Kastend848eb42016-03-08 13:42:11 -08001600sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1601 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001602{
1603 Mutex::Autolock _l(mLock);
1604 return getEffect_l(sessionId, effectId);
1605}
1606
Glenn Kastend848eb42016-03-08 13:42:11 -08001607sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1608 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001609{
1610 sp<EffectChain> chain = getEffectChain_l(sessionId);
1611 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1612}
1613
Eric Laurent6c796322019-04-09 14:13:17 -07001614std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1615{
1616 sp<EffectChain> chain = getEffectChain_l(sessionId);
1617 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1618}
1619
Eric Laurent81784c32012-11-19 14:55:58 -08001620// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1621// PlaybackThread::mLock held
1622status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1623{
1624 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001625 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001626 sp<EffectChain> chain = getEffectChain_l(sessionId);
1627 bool chainCreated = false;
1628
Eric Laurent5baf2af2013-09-12 17:37:00 -07001629 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001630 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001631 this, effect->desc().name, effect->desc().flags);
1632
Eric Laurent81784c32012-11-19 14:55:58 -08001633 if (chain == 0) {
1634 // create a new chain for this session
1635 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1636 chain = new EffectChain(this, sessionId);
1637 addEffectChain_l(chain);
1638 chain->setStrategy(getStrategyForSession_l(sessionId));
1639 chainCreated = true;
1640 }
1641 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1642
1643 if (chain->getEffectFromId_l(effect->id()) != 0) {
1644 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1645 this, effect->desc().name, chain.get());
1646 return BAD_VALUE;
1647 }
1648
Eric Laurent5baf2af2013-09-12 17:37:00 -07001649 effect->setOffloaded(mType == OFFLOAD, mId);
1650
Eric Laurent81784c32012-11-19 14:55:58 -08001651 status_t status = chain->addEffect_l(effect);
1652 if (status != NO_ERROR) {
1653 if (chainCreated) {
1654 removeEffectChain_l(chain);
1655 }
1656 return status;
1657 }
1658
jiabin8f278ee2019-11-11 12:16:27 -08001659 effect->setDevices(outDeviceTypeAddrs());
1660 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001661 effect->setMode(mAudioFlinger->getMode());
1662 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001663
Eric Laurent81784c32012-11-19 14:55:58 -08001664 return NO_ERROR;
1665}
1666
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001667void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001668
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001669 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001670 effect_descriptor_t desc = effect->desc();
1671 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1672 detachAuxEffect_l(effect->id());
1673 }
1674
Andy Hungfda44002021-06-03 17:23:16 -07001675 sp<EffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001676 if (chain != 0) {
1677 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001678 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001679 removeEffectChain_l(chain);
1680 }
1681 } else {
1682 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1683 }
1684}
1685
1686void AudioFlinger::ThreadBase::lockEffectChains_l(
1687 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1688{
1689 effectChains = mEffectChains;
1690 for (size_t i = 0; i < mEffectChains.size(); i++) {
1691 mEffectChains[i]->lock();
1692 }
1693}
1694
1695void AudioFlinger::ThreadBase::unlockEffectChains(
1696 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1697{
1698 for (size_t i = 0; i < effectChains.size(); i++) {
1699 effectChains[i]->unlock();
1700 }
1701}
1702
Glenn Kastend848eb42016-03-08 13:42:11 -08001703sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001704{
1705 Mutex::Autolock _l(mLock);
1706 return getEffectChain_l(sessionId);
1707}
1708
Glenn Kastend848eb42016-03-08 13:42:11 -08001709sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1710 const
Eric Laurent81784c32012-11-19 14:55:58 -08001711{
1712 size_t size = mEffectChains.size();
1713 for (size_t i = 0; i < size; i++) {
1714 if (mEffectChains[i]->sessionId() == sessionId) {
1715 return mEffectChains[i];
1716 }
1717 }
1718 return 0;
1719}
1720
1721void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1722{
1723 Mutex::Autolock _l(mLock);
1724 size_t size = mEffectChains.size();
1725 for (size_t i = 0; i < size; i++) {
1726 mEffectChains[i]->setMode_l(mode);
1727 }
1728}
1729
Mikhail Naganovdc769682018-05-04 15:34:08 -07001730void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001731{
1732 config->type = AUDIO_PORT_TYPE_MIX;
1733 config->ext.mix.handle = mId;
1734 config->sample_rate = mSampleRate;
1735 config->format = mFormat;
1736 config->channel_mask = mChannelMask;
1737 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1738 AUDIO_PORT_CONFIG_FORMAT;
1739}
1740
Eric Laurent72e3f392015-05-20 14:43:50 -07001741void AudioFlinger::ThreadBase::systemReady()
1742{
1743 Mutex::Autolock _l(mLock);
1744 if (mSystemReady) {
1745 return;
1746 }
1747 mSystemReady = true;
1748
1749 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1750 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1751 }
1752 mPendingConfigEvents.clear();
1753}
1754
Andy Hungdae27702016-10-31 14:01:16 -07001755template <typename T>
1756ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1757 ssize_t index = mActiveTracks.indexOf(track);
1758 if (index >= 0) {
1759 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1760 return index;
1761 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001762 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001763 mActiveTracksGeneration++;
1764 mLatestActiveTrack = track;
1765 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001766 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001767 return mActiveTracks.add(track);
1768}
1769
1770template <typename T>
1771ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1772 ssize_t index = mActiveTracks.remove(track);
1773 if (index < 0) {
1774 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1775 return index;
1776 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001777 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001778 mActiveTracksGeneration++;
1779 --mBatteryCounter[track->uid()].second;
1780 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001781 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001782#ifdef TEE_SINK
1783 track->dumpTee(-1 /* fd */, "_REMOVE");
1784#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001785 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001786 return index;
1787}
1788
1789template <typename T>
1790void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1791 for (const sp<T> &track : mActiveTracks) {
1792 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001793 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001794 }
1795 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001796 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001797 mActiveTracks.clear();
1798 mLatestActiveTrack.clear();
1799 mBatteryCounter.clear();
1800}
1801
1802template <typename T>
1803void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1804 sp<ThreadBase> thread, bool force) {
1805 // Updates ActiveTracks client uids to the thread wakelock.
1806 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1807 thread->updateWakeLockUids_l(getWakeLockUids());
1808 mLastActiveTracksGeneration = mActiveTracksGeneration;
1809 }
1810
1811 // Updates BatteryNotifier uids
1812 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1813 const uid_t uid = it->first;
1814 ssize_t &previous = it->second.first;
1815 ssize_t &current = it->second.second;
1816 if (current > 0) {
1817 if (previous == 0) {
1818 BatteryNotifier::getInstance().noteStartAudio(uid);
1819 }
1820 previous = current;
1821 ++it;
1822 } else if (current == 0) {
1823 if (previous > 0) {
1824 BatteryNotifier::getInstance().noteStopAudio(uid);
1825 }
1826 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1827 } else /* (current < 0) */ {
1828 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1829 }
1830 }
1831}
Eric Laurent83b88082014-06-20 18:31:16 -07001832
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001833template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001834bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001835 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001836 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001837
1838 for (const sp<T> &track : mActiveTracks) {
1839 // Do not short-circuit as all hasChanged states must be reset
1840 // as all the metadata are going to be sent
1841 hasChanged |= track->readAndClearHasChanged();
1842 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001843 return hasChanged;
1844}
1845
1846template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001847void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1848 const char *funcName, const sp<T> &track) const {
1849 if (mLocalLog != nullptr) {
1850 String8 result;
1851 track->appendDump(result, false /* active */);
1852 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1853 }
1854}
1855
Eric Laurent6acd1d42017-01-04 14:23:29 -08001856void AudioFlinger::ThreadBase::broadcast_l()
1857{
1858 // Thread could be blocked waiting for async
1859 // so signal it to handle state changes immediately
1860 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1861 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1862 mSignalPending = true;
1863 mWaitWorkCV.broadcast();
1864}
1865
Andy Hungd0979812019-02-21 15:51:44 -08001866// Call only from threadLoop() or when it is idle.
1867// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1868void AudioFlinger::ThreadBase::sendStatistics(bool force)
1869{
1870 // Do not log if we have no stats.
1871 // We choose the timestamp verifier because it is the most likely item to be present.
1872 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1873 if (nstats == 0) {
1874 return;
1875 }
1876
1877 // Don't log more frequently than once per 12 hours.
1878 // We use BOOTTIME to include suspend time.
1879 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1880 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1881 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1882 return;
1883 }
1884
1885 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1886 mLastRecordedTimeNs = timeNs;
1887
Ray Essickf27e9872019-12-07 06:28:46 -08001888 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001889
1890#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1891
1892 // thread configuration
1893 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1894 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1895 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1896 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1897 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1898 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1899 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001900 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1901 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001902
1903 // thread statistics
1904 if (mIoJitterMs.getN() > 0) {
1905 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1906 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1907 }
1908 if (mProcessTimeMs.getN() > 0) {
1909 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1910 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1911 }
1912 const auto tsjitter = mTimestampVerifier.getJitterMs();
1913 if (tsjitter.getN() > 0) {
1914 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1915 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1916 }
1917 if (mLatencyMs.getN() > 0) {
1918 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1919 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1920 }
1921
1922 item->selfrecord();
1923}
1924
Eric Laurentd66d7a12021-07-13 13:35:32 +02001925product_strategy_t AudioFlinger::ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
1926{
1927 if (!mAudioFlinger->isAudioPolicyReady()) {
1928 return PRODUCT_STRATEGY_NONE;
1929 }
1930 return AudioSystem::getStrategyForStream(stream);
1931}
1932
Eric Laurent81784c32012-11-19 14:55:58 -08001933// ----------------------------------------------------------------------------
1934// Playback
1935// ----------------------------------------------------------------------------
1936
1937AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1938 AudioStreamOut* output,
1939 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001940 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02001941 bool systemReady,
1942 audio_config_base_t *mixerConfig)
Andy Hungcf10d742020-04-28 15:38:24 -07001943 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08001944 mNormalFrameCount(0), mSinkBuffer(NULL),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001945 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08001946 mMixerBuffer(NULL),
1947 mMixerBufferSize(0),
1948 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1949 mMixerBufferValid(false),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001950 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08001951 mEffectBuffer(NULL),
1952 mEffectBufferSize(0),
1953 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1954 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001955 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001956 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001957 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001958 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001959 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001960 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001961 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001962 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001963 mMixerStatus(MIXER_IDLE),
1964 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001965 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001966 mBytesRemaining(0),
1967 mCurrentWriteLength(0),
1968 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001969 mWriteAckSequence(0),
1970 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001971 mScreenState(AudioFlinger::mScreenState),
1972 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001973 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001974 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01001975 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
1976 mDownStreamPatch{}
Eric Laurent81784c32012-11-19 14:55:58 -08001977{
Glenn Kastend7dca052015-03-05 16:05:54 -08001978 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1979 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001980
1981 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1982 // it would be safer to explicitly pass initial masterVolume/masterMute as
1983 // parameter.
1984 //
1985 // If the HAL we are using has support for master volume or master mute,
1986 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1987 // and the mute set to false).
1988 mMasterVolume = audioFlinger->masterVolume_l();
1989 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08001990 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08001991 if (mOutput->audioHwDev->canSetMasterVolume()) {
1992 mMasterVolume = 1.0;
1993 }
1994
1995 if (mOutput->audioHwDev->canSetMasterMute()) {
1996 mMasterMute = false;
1997 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001998 mIsMsdDevice = strcmp(
1999 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002000 }
2001
Eric Laurentf1f22e72021-07-13 14:04:14 +02002002 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2003 mMixerChannelMask = mixerConfig->channel_mask;
2004 }
2005
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002006 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002007
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002008 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002009 && mMixerChannelMask != mChannelMask) {
2010 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2011 mChannelMask, mMixerChannelMask);
2012 }
2013
Andy Hungc8fddf32018-08-08 18:32:37 -07002014 // TODO: We may also match on address as well as device type for
2015 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002016 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002017 // TODO: This property should be ensure that only contains one single device type.
2018 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2019 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002020 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2021 : AUDIO_DEVICE_NONE));
2022 }
2023
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002024 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2025 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002026 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08002027 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
2028 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002029 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002030 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2031 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002032 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2033 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002034}
2035
2036AudioFlinger::PlaybackThread::~PlaybackThread()
2037{
Glenn Kasten9e58b552013-01-18 15:09:48 -08002038 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002039 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002040 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002041 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002042}
2043
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002044// Thread virtuals
2045
2046void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002047{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002048 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002049 ALOGE("The stream is not open yet"); // This should not happen.
2050 } else {
2051 // setEventCallback will need a strong pointer as a parameter. Calling it
2052 // here instead of constructor of PlaybackThread so that the onFirstRef
2053 // callback would not be made on an incompletely constructed object.
2054 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002055 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002056 }
2057 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002058 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08002059}
2060
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002061// ThreadBase virtuals
2062void AudioFlinger::PlaybackThread::preExit()
2063{
2064 ALOGV(" preExit()");
2065 // FIXME this is using hard-coded strings but in the future, this functionality will be
2066 // converted to use audio HAL extensions required to support tunneling
2067 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
2068 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
2069}
2070
2071void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002072{
Eric Laurent81784c32012-11-19 14:55:58 -08002073 String8 result;
2074
Marco Nelissenb2208842014-02-07 14:00:50 -08002075 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002076 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2077 const stream_type_t *st = &mStreamTypes[i];
2078 if (i > 0) {
2079 result.appendFormat(", ");
2080 }
2081 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2082 if (st->mute) {
2083 result.append("M");
2084 }
2085 }
2086 result.append("\n");
2087 write(fd, result.string(), result.length());
2088 result.clear();
2089
Eric Laurent81784c32012-11-19 14:55:58 -08002090 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2091 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002092 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002093 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002094
2095 size_t numtracks = mTracks.size();
2096 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002097 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002098 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002099 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002100 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002101 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002102 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002103 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002104 for (size_t i = 0; i < numtracks; ++i) {
2105 sp<Track> track = mTracks[i];
2106 if (track != 0) {
2107 bool active = mActiveTracks.indexOf(track) >= 0;
2108 if (active) {
2109 numactiveseen++;
2110 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002111 result.append(prefix);
2112 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002113 }
2114 }
2115 } else {
2116 result.append("\n");
2117 }
2118 if (numactiveseen != numactive) {
2119 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002120 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002121 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002122 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002123 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002124 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002125 sp<Track> track = mActiveTracks[i];
2126 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002127 result.append(prefix);
2128 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002129 }
2130 }
2131 }
2132
2133 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002134}
2135
Andy Hung61589a42021-06-16 09:37:53 -07002136void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002137{
Andy Hung04cb8f72020-03-20 13:44:33 -07002138 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002139 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002140 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2141 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002142 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2143 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2144 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2145 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002146 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002147 dprintf(fd, " Total writes: %d\n", mNumWrites);
2148 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2149 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2150 dprintf(fd, " Suspend count: %d\n", mSuspended);
2151 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2152 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2153 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2154 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002155 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002156 AudioStreamOut *output = mOutput;
2157 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002158 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002159 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002160 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2161 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2162 if (mPipeSink.get() != nullptr) {
2163 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2164 }
2165 if (output != nullptr) {
2166 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002167 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002168 }
Eric Laurent81784c32012-11-19 14:55:58 -08002169}
2170
Eric Laurent81784c32012-11-19 14:55:58 -08002171// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2172sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2173 const sp<AudioFlinger::Client>& client,
2174 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002175 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002176 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002177 audio_format_t format,
2178 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002179 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002180 size_t *pNotificationFrameCount,
2181 uint32_t notificationsPerBuffer,
2182 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002183 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002184 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002185 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002186 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002187 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002188 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002189 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002190 audio_port_handle_t portId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002191 const sp<media::IAudioTrackCallback>& callback)
Eric Laurent81784c32012-11-19 14:55:58 -08002192{
Glenn Kasten74935e42013-12-19 08:56:45 -08002193 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002194 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002195 sp<Track> track;
2196 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002197 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002198 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002199 uint32_t sampleRate;
2200
2201 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2202 lStatus = BAD_VALUE;
2203 goto Exit;
2204 }
Eric Laurent21da6472017-11-09 16:29:26 -08002205
2206 if (*pSampleRate == 0) {
2207 *pSampleRate = mSampleRate;
2208 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002209 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002210
2211 // special case for FAST flag considered OK if fast mixer is present
2212 if (hasFastMixer()) {
2213 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2214 }
2215
2216 // Check if requested flags are compatible with output stream flags
2217 if ((*flags & outputFlags) != *flags) {
2218 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2219 *flags, outputFlags);
2220 *flags = (audio_output_flags_t)(*flags & outputFlags);
2221 }
Eric Laurent81784c32012-11-19 14:55:58 -08002222
Eric Laurent81784c32012-11-19 14:55:58 -08002223 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002224 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002225 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002226 // PCM data
2227 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002228 // TODO: extract as a data library function that checks that a computationally
2229 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002230 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002231 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2232 (channelMask == AUDIO_CHANNEL_OUT_MONO
2233 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002234 // hardware sample rate
2235 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002236 // normal mixer has an associated fast mixer
2237 hasFastMixer() &&
2238 // there are sufficient fast track slots available
2239 (mFastTrackAvailMask != 0)
2240 // FIXME test that MixerThread for this fast track has a capable output HAL
2241 // FIXME add a permission test also?
2242 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002243 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2244 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002245 // read the fast track multiplier property the first time it is needed
2246 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2247 if (ok != 0) {
2248 ALOGE("%s pthread_once failed: %d", __func__, ok);
2249 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002250 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002251 }
Eric Laurent4c415062016-06-17 16:14:16 -07002252
2253 // check compatibility with audio effects.
2254 { // scope for mLock
2255 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002256 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002257 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002258 AUDIO_SESSION_OUTPUT_STAGE,
2259 AUDIO_SESSION_OUTPUT_MIX,
2260 sessionId,
2261 }) {
2262 sp<EffectChain> chain = getEffectChain_l(session);
2263 if (chain.get() != nullptr) {
2264 audio_output_flags_t old = *flags;
2265 chain->checkOutputFlagCompatibility(flags);
2266 if (old != *flags) {
2267 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2268 (int)session, (int)old, (int)*flags);
2269 }
Eric Laurent4c415062016-06-17 16:14:16 -07002270 }
2271 }
2272 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002273 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002274 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2275 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002276 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002277 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2278 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002279 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002280 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002281 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002282 audio_is_linear_pcm(format), channelMask, sampleRate,
2283 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002284 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002285 }
2286 }
Eric Laurent21da6472017-11-09 16:29:26 -08002287
2288 if (!audio_has_proportional_frames(format)) {
2289 if (sharedBuffer != 0) {
2290 // Same comment as below about ignoring frameCount parameter for set()
2291 frameCount = sharedBuffer->size();
2292 } else if (frameCount == 0) {
2293 frameCount = mNormalFrameCount;
2294 }
2295 if (notificationFrameCount != frameCount) {
2296 notificationFrameCount = frameCount;
2297 }
2298 } else if (sharedBuffer != 0) {
2299 // FIXME: Ensure client side memory buffers need
2300 // not have additional alignment beyond sample
2301 // (e.g. 16 bit stereo accessed as 32 bit frame).
2302 size_t alignment = audio_bytes_per_sample(format);
2303 if (alignment & 1) {
2304 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2305 alignment = 1;
2306 }
2307 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2308 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2309 if (channelCount > 1) {
2310 // More than 2 channels does not require stronger alignment than stereo
2311 alignment <<= 1;
2312 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002313 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002314 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002315 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002316 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002317 goto Exit;
2318 }
Eric Laurent21da6472017-11-09 16:29:26 -08002319
2320 // When initializing a shared buffer AudioTrack via constructors,
2321 // there's no frameCount parameter.
2322 // But when initializing a shared buffer AudioTrack via set(),
2323 // there _is_ a frameCount parameter. We silently ignore it.
2324 frameCount = sharedBuffer->size() / frameSize;
2325 } else {
2326 size_t minFrameCount = 0;
2327 // For fast tracks we try to respect the application's request for notifications per buffer.
2328 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2329 if (notificationsPerBuffer > 0) {
2330 // Avoid possible arithmetic overflow during multiplication.
2331 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2332 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2333 notificationsPerBuffer, mFrameCount);
2334 } else {
2335 minFrameCount = mFrameCount * notificationsPerBuffer;
2336 }
2337 }
2338 } else {
2339 // For normal PCM streaming tracks, update minimum frame count.
2340 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2341 // cover audio hardware latency.
2342 // This is probably too conservative, but legacy application code may depend on it.
2343 // If you change this calculation, also review the start threshold which is related.
2344 uint32_t latencyMs = latency_l();
2345 if (latencyMs == 0) {
2346 ALOGE("Error when retrieving output stream latency");
2347 lStatus = UNKNOWN_ERROR;
2348 goto Exit;
2349 }
2350
2351 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2352 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2353
Eric Laurent81784c32012-11-19 14:55:58 -08002354 }
Eric Laurent21da6472017-11-09 16:29:26 -08002355 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002356 frameCount = minFrameCount;
2357 }
Eric Laurent81784c32012-11-19 14:55:58 -08002358 }
Eric Laurent21da6472017-11-09 16:29:26 -08002359
2360 // Make sure that application is notified with sufficient margin before underrun.
2361 // The client can divide the AudioTrack buffer into sub-buffers,
2362 // and expresses its desire to server as the notification frame count.
2363 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2364 size_t maxNotificationFrames;
2365 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2366 // notify every HAL buffer, regardless of the size of the track buffer
2367 maxNotificationFrames = mFrameCount;
2368 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002369 // Triple buffer the notification period for a triple buffered mixer period;
2370 // otherwise, double buffering for the notification period is fine.
2371 //
2372 // TODO: This should be moved to AudioTrack to modify the notification period
2373 // on AudioTrack::setBufferSizeInFrames() changes.
2374 const int nBuffering =
2375 (uint64_t{frameCount} * mSampleRate)
2376 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2377
Eric Laurent21da6472017-11-09 16:29:26 -08002378 maxNotificationFrames = frameCount / nBuffering;
2379 // If client requested a fast track but this was denied, then use the smaller maximum.
2380 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2381 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2382 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2383 maxNotificationFrames = maxNotificationFramesFastDenied;
2384 }
2385 }
2386 }
2387 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2388 if (notificationFrameCount == 0) {
2389 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2390 maxNotificationFrames, frameCount);
2391 } else {
2392 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2393 notificationFrameCount, maxNotificationFrames, frameCount);
2394 }
2395 notificationFrameCount = maxNotificationFrames;
2396 }
2397 }
2398
Glenn Kasten74935e42013-12-19 08:56:45 -08002399 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002400 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002401
Glenn Kastenc3df8382014-03-13 15:05:25 -07002402 switch (mType) {
2403
2404 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002405 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002406 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002407 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2408 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002409 sampleRate, format, channelMask, mOutput, mFormat);
2410 lStatus = BAD_VALUE;
2411 goto Exit;
2412 }
2413 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002414 break;
2415
2416 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002417 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002418 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2419 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002420 sampleRate, format, channelMask, mOutput, mFormat);
2421 lStatus = BAD_VALUE;
2422 goto Exit;
2423 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002424 break;
2425
2426 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002427 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002428 ALOGE("createTrack_l() Bad parameter: format %#x \""
2429 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002430 format, mOutput, mFormat);
2431 lStatus = BAD_VALUE;
2432 goto Exit;
2433 }
Andy Hungcd044842014-08-07 11:04:34 -07002434 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002435 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2436 lStatus = BAD_VALUE;
2437 goto Exit;
2438 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002439 break;
2440
Eric Laurent81784c32012-11-19 14:55:58 -08002441 }
2442
2443 lStatus = initCheck();
2444 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002445 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002446 goto Exit;
2447 }
2448
2449 { // scope for mLock
2450 Mutex::Autolock _l(mLock);
2451
2452 // all tracks in same audio session must share the same routing strategy otherwise
2453 // conflicts will happen when tracks are moved from one output to another by audio policy
2454 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002455 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002456 for (size_t i = 0; i < mTracks.size(); ++i) {
2457 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002458 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002459 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002460 if (sessionId == t->sessionId() && strategy != actual) {
2461 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2462 strategy, actual);
2463 lStatus = BAD_VALUE;
2464 goto Exit;
2465 }
2466 }
2467 }
2468
yucliuc9c49cd2020-07-13 16:25:21 -07002469 // Set DIRECT flag if current thread is DirectOutputThread. This can
2470 // happen when the playback is rerouted to direct output thread by
2471 // dynamic audio policy.
2472 // Do NOT report the flag changes back to client, since the client
2473 // doesn't explicitly request a direct flag.
2474 audio_output_flags_t trackFlags = *flags;
2475 if (mType == DIRECT) {
2476 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2477 }
2478
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002479 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002480 channelMask, frameCount,
2481 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002482 sessionId, creatorPid, attributionSource, trackFlags,
2483 TrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/, speed);
Glenn Kasten03003332013-08-06 15:40:54 -07002484
Glenn Kasten03003332013-08-06 15:40:54 -07002485 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2486 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002487 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002488 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002489 goto Exit;
2490 }
2491 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002492 {
2493 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2494 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002495 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002496 }
2497 }
Eric Laurent81784c32012-11-19 14:55:58 -08002498
2499 sp<EffectChain> chain = getEffectChain_l(sessionId);
2500 if (chain != 0) {
2501 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2502 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002503 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002504 chain->incTrackCnt();
2505 }
2506
Eric Laurent05067782016-06-01 18:27:28 -07002507 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002508 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2509 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2510 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002511 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002512 }
2513 }
2514
2515 lStatus = NO_ERROR;
2516
2517Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002518 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002519 return track;
2520}
2521
Andy Hung1bc088a2018-02-09 15:57:31 -08002522template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002523ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2524{
Andy Hungc0691382018-09-12 18:01:57 -07002525 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002526 const ssize_t index = mTracks.remove(track);
2527 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002528 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002529 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002530 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002531 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002532 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002533 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002534 }
2535 return index;
2536}
2537
Eric Laurent81784c32012-11-19 14:55:58 -08002538uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2539{
2540 return latency;
2541}
2542
2543uint32_t AudioFlinger::PlaybackThread::latency() const
2544{
2545 Mutex::Autolock _l(mLock);
2546 return latency_l();
2547}
2548uint32_t AudioFlinger::PlaybackThread::latency_l() const
2549{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002550 uint32_t latency;
2551 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2552 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002553 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002554 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002555}
2556
2557void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2558{
2559 Mutex::Autolock _l(mLock);
2560 // Don't apply master volume in SW if our HAL can do it for us.
2561 if (mOutput && mOutput->audioHwDev &&
2562 mOutput->audioHwDev->canSetMasterVolume()) {
2563 mMasterVolume = 1.0;
2564 } else {
2565 mMasterVolume = value;
2566 }
2567}
2568
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002569void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2570{
2571 mMasterBalance.store(balance);
2572}
2573
Eric Laurent81784c32012-11-19 14:55:58 -08002574void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2575{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002576 if (isDuplicating()) {
2577 return;
2578 }
Eric Laurent81784c32012-11-19 14:55:58 -08002579 Mutex::Autolock _l(mLock);
2580 // Don't apply master mute in SW if our HAL can do it for us.
2581 if (mOutput && mOutput->audioHwDev &&
2582 mOutput->audioHwDev->canSetMasterMute()) {
2583 mMasterMute = false;
2584 } else {
2585 mMasterMute = muted;
2586 }
2587}
2588
2589void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2590{
2591 Mutex::Autolock _l(mLock);
2592 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002593 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002594}
2595
2596void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2597{
2598 Mutex::Autolock _l(mLock);
2599 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002600 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002601}
2602
2603float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2604{
2605 Mutex::Autolock _l(mLock);
2606 return mStreamTypes[stream].volume;
2607}
2608
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002609void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2610{
2611 mOutput->stream->setVolume(left, right);
2612}
2613
Eric Laurent81784c32012-11-19 14:55:58 -08002614// addTrack_l() must be called with ThreadBase::mLock held
2615status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2616{
2617 status_t status = ALREADY_EXISTS;
2618
Eric Laurent81784c32012-11-19 14:55:58 -08002619 if (mActiveTracks.indexOf(track) < 0) {
2620 // the track is newly added, make sure it fills up all its
2621 // buffers before playing. This is to ensure the client will
2622 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002623 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002624 TrackBase::track_state state = track->mState;
2625 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002626 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002627 mLock.lock();
2628 // abort track was stopped/paused while we released the lock
2629 if (state != track->mState) {
2630 if (status == NO_ERROR) {
2631 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002632 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002633 mLock.lock();
2634 }
2635 return INVALID_OPERATION;
2636 }
2637 // abort if start is rejected by audio policy manager
2638 if (status != NO_ERROR) {
2639 return PERMISSION_DENIED;
2640 }
2641#ifdef ADD_BATTERY_DATA
2642 // to track the speaker usage
2643 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2644#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002645 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002646 }
2647
Eric Laurent51716182016-02-29 18:00:56 -08002648 // set retry count for buffer fill
2649 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002650 if (track->isStopping_1()) {
2651 track->mRetryCount = kMaxTrackStopRetriesOffload;
2652 } else {
2653 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2654 }
2655 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002656 } else {
2657 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002658 track->mFillingUpStatus =
2659 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002660 }
2661
jiabineb3bda02020-06-30 14:07:03 -07002662 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2663 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2664 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2665 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002666 // Unlock due to VibratorService will lock for this call and will
2667 // call Tracks.mute/unmute which also require thread's lock.
2668 mLock.unlock();
2669 const int intensity = AudioFlinger::onExternalVibrationStart(
2670 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002671 std::optional<media::AudioVibratorInfo> vibratorInfo;
2672 {
2673 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2674 // used to play this track.
2675 Mutex::Autolock _l(mAudioFlinger->mLock);
2676 vibratorInfo = std::move(mAudioFlinger->getDefaultVibratorInfo_l());
2677 }
jiabin57303cc2018-12-18 15:45:57 -08002678 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002679 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
Lais Andradebc3f37a2021-07-02 00:13:19 +01002680 if (vibratorInfo) {
2681 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2682 }
2683
jiabin57303cc2018-12-18 15:45:57 -08002684 // Haptic playback should be enabled by vibrator service.
2685 if (track->getHapticPlaybackEnabled()) {
2686 // Disable haptic playback of all active track to ensure only
2687 // one track playing haptic if current track should play haptic.
2688 for (const auto &t : mActiveTracks) {
2689 t->setHapticPlaybackEnabled(false);
2690 }
jiabin245cdd92018-12-07 17:55:15 -08002691 }
jiabine70bc7f2020-06-30 22:07:55 -07002692
2693 // Set haptic intensity for effect
2694 if (chain != nullptr) {
2695 chain->setHapticIntensity_l(track->id(), intensity);
2696 }
jiabin245cdd92018-12-07 17:55:15 -08002697 }
2698
Eric Laurent81784c32012-11-19 14:55:58 -08002699 track->mResetDone = false;
Andy Hung59de4262021-06-14 10:53:54 -07002700 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002701 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002702 if (chain != 0) {
2703 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2704 track->sessionId());
2705 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002706 }
2707
Andy Hungc2b11cb2020-04-22 09:04:01 -07002708 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002709 status = NO_ERROR;
2710 }
2711
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002712 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002713 return status;
2714}
2715
Eric Laurentbfb1b832013-01-07 09:53:42 -08002716bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002717{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002718 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002719 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002720 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2721 track->mState = TrackBase::STOPPED;
2722 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002723 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002724 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002725 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002726 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002727
2728 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002729}
2730
2731void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2732{
2733 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002734
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002735 String8 result;
2736 track->appendDump(result, false /* active */);
2737 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002738
Eric Laurent81784c32012-11-19 14:55:58 -08002739 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002740 {
2741 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2742 mAudioTrackCallbacks.erase(track);
2743 }
Eric Laurent81784c32012-11-19 14:55:58 -08002744 if (track->isFastTrack()) {
2745 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002746 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002747 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2748 mFastTrackAvailMask |= 1 << index;
2749 // redundant as track is about to be destroyed, for dumpsys only
2750 track->mFastIndex = -1;
2751 }
2752 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2753 if (chain != 0) {
2754 chain->decTrackCnt();
2755 }
2756}
2757
2758String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2759{
Eric Laurent81784c32012-11-19 14:55:58 -08002760 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002761 String8 out_s8;
2762 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2763 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002764 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002765 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002766}
2767
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002768status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2769 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002770 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002771 return NO_INIT;
2772 }
2773 return mOutput->stream->selectPresentation(presentationId, programId);
2774}
2775
Eric Laurent09f1ed22019-04-24 17:45:17 -07002776void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
2777 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002778 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2779 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002780
Eric Laurent73e26b62015-04-27 16:55:58 -07002781 desc->mIoHandle = mId;
Eric Laurent74c38dc2020-12-23 18:19:44 +01002782 struct audio_patch patch = mPatch;
2783 if (isMsdDevice()) {
2784 patch = mDownStreamPatch;
2785 }
Eric Laurent81784c32012-11-19 14:55:58 -08002786
2787 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002788 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002789 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002790 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent74c38dc2020-12-23 18:19:44 +01002791 desc->mPatch = patch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002792 desc->mChannelMask = mChannelMask;
2793 desc->mSamplingRate = mSampleRate;
2794 desc->mFormat = mFormat;
2795 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002796 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002797 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002798 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002799 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002800 case AUDIO_CLIENT_STARTED:
Eric Laurent74c38dc2020-12-23 18:19:44 +01002801 desc->mPatch = patch;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002802 desc->mPortId = portId;
2803 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002804 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002805 default:
2806 break;
2807 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002808 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002809}
2810
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002811void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002812{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002813 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002814}
2815
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002816void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002817{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002818 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002819}
2820
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002821void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002822{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002823 mCallbackThread->setAsyncError();
2824}
2825
jiabinf6eb4c32020-02-25 14:06:25 -08002826void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2827 const std::basic_string<uint8_t>& metadataBs)
2828{
2829 std::thread([this, metadataBs]() {
2830 audio_utils::metadata::Data metadata =
2831 audio_utils::metadata::dataFromByteString(metadataBs);
2832 if (metadata.empty()) {
2833 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2834 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2835 (int)metadataBs.size());
2836 return;
2837 }
2838
2839 audio_utils::metadata::ByteString metaDataStr =
2840 audio_utils::metadata::byteStringFromData(metadata);
2841 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2842 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002843 for (const auto& callbackPair : mAudioTrackCallbacks) {
2844 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002845 }
2846 }).detach();
2847}
2848
Eric Laurent3b4529e2013-09-05 18:09:19 -07002849void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002850{
2851 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002852 // reject out of sequence requests
2853 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2854 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002855 mWaitWorkCV.signal();
2856 }
2857}
2858
Eric Laurent3b4529e2013-09-05 18:09:19 -07002859void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002860{
2861 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002862 // reject out of sequence requests
2863 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002864 // Register discontinuity when HW drain is completed because that can cause
2865 // the timestamp frame position to reset to 0 for direct and offload threads.
2866 // (Out of sequence requests are ignored, since the discontinuity would be handled
2867 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002868 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002869 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002870 mWaitWorkCV.signal();
2871 }
2872}
2873
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002874void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002875{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002876 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002877 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2878 mSampleRate = audioConfig.sample_rate;
2879 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002880 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002881 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002882 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002883 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07002884 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2885 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002886 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02002887
2888 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
2889 mMixerChannelMask = mChannelMask;
2890 }
2891
Andy Hunge5412692014-05-16 11:25:07 -07002892 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002893 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002894
Eric Laurentf1f22e72021-07-13 14:04:14 +02002895 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
2896
Phil Burkca5e6142015-07-14 09:42:29 -07002897 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002898 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002899 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002900 // Get format from the shim, which will be different than the HAL format
2901 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002902 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002903 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002904 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002905 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002906 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07002907 LOG_FATAL("HAL format %#x not supported for mixed output",
2908 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002909 }
Phil Burk062e67a2015-02-11 13:40:50 -08002910 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002911 result = mOutput->stream->getBufferSize(&mBufferSize);
2912 LOG_ALWAYS_FATAL_IF(result != OK,
2913 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002914 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02002915 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002916 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002917 mFrameCount);
2918 }
2919
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002920 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2921 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002922 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002923 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002924 }
2925 }
2926
Eric Laurentd1f69b02014-12-15 14:33:13 -08002927 mHwSupportsPause = false;
2928 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002929 bool supportsPause = false, supportsResume = false;
2930 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2931 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002932 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002933 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002934 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002935 } else if (supportsResume) {
2936 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002937 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002938 }
2939 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002940 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2941 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2942 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002943
Andy Hungfbfc3952015-01-15 13:33:51 -08002944 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2945 // For best precision, we use float instead of the associated output
2946 // device format (typically PCM 16 bit).
2947
2948 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2949 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2950 mBufferSize = mFrameSize * mFrameCount;
2951
2952 // TODO: We currently use the associated output device channel mask and sample rate.
2953 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2954 // (if a valid mask) to avoid premature downmix.
2955 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2956 // instead of the output device sample rate to avoid loss of high frequency information.
2957 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2958 }
2959
Andy Hung09a50072014-02-27 14:30:47 -08002960 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002961 double multiplier = 1.0;
2962 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2963 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002964 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2965 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002966
Eric Laurent81784c32012-11-19 14:55:58 -08002967 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2968 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2969 maxNormalFrameCount = maxNormalFrameCount & ~15;
2970 if (maxNormalFrameCount < minNormalFrameCount) {
2971 maxNormalFrameCount = minNormalFrameCount;
2972 }
2973 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2974 if (multiplier <= 1.0) {
2975 multiplier = 1.0;
2976 } else if (multiplier <= 2.0) {
2977 if (2 * mFrameCount <= maxNormalFrameCount) {
2978 multiplier = 2.0;
2979 } else {
2980 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2981 }
2982 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002983 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002984 }
2985 }
2986 mNormalFrameCount = multiplier * mFrameCount;
2987 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02002988 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07002989 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2990 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002991 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002992 mNormalFrameCount);
2993
Andy Hung08fb1742015-05-31 23:22:10 -07002994 // Check if we want to throttle the processing to no more than 2x normal rate
2995 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002996 mThreadThrottleTimeMs = 0;
2997 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002998 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2999
Andy Hung010a1a12014-03-13 13:57:33 -07003000 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3001 // Originally this was int16_t[] array, need to remove legacy implications.
3002 free(mSinkBuffer);
3003 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07003004 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3005 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3006 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003007 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003008
Andy Hung69aed5f2014-02-25 17:24:40 -08003009 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3010 // drives the output.
3011 free(mMixerBuffer);
3012 mMixerBuffer = NULL;
3013 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003014 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003015 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003016 * audio_bytes_per_sample(mMixerBufferFormat);
3017 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3018 }
Andy Hung98ef9782014-03-04 14:46:50 -08003019 free(mEffectBuffer);
3020 mEffectBuffer = NULL;
3021 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07003022 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003023 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003024 * audio_bytes_per_sample(mEffectBufferFormat);
3025 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3026 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003027
Mikhail Naganov55773032020-10-01 15:08:13 -07003028 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3029 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003030 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3031 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003032 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003033
Eric Laurent81784c32012-11-19 14:55:58 -08003034 // force reconfiguration of effect chains and engines to take new buffer size and audio
3035 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003036 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003037 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3038 // matter.
3039 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
3040 Vector< sp<EffectChain> > effectChains = mEffectChains;
3041 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07003042 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
3043 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003044 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003045
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003046 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003047 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003048 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3049 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3050 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3051 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3052 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3053 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3054 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3055 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3056 (int32_t)mHapticChannelMask)
3057 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3058 (int32_t)mHapticChannelCount)
3059 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3060 formatToString(mHALFormat).c_str())
3061 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3062 (int32_t)mFrameCount) // sic - added HAL
3063 ;
3064 uint32_t latencyMs;
3065 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3066 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3067 }
3068 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003069}
3070
Kevin Rocard069c2712018-03-29 19:09:14 -07003071void AudioFlinger::PlaybackThread::updateMetadata_l()
3072{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003073 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Kevin Rocard12381092018-04-11 09:19:59 -07003074 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003075 }
3076 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003077 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07003078 for (const sp<Track> &track : mActiveTracks) {
3079 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01003080 // Do not forward metadata for PatchTrack with unspecified stream type
3081 if (track->streamType() != AUDIO_STREAM_PATCH) {
3082 track->copyMetadataTo(backInserter);
3083 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003084 }
Kevin Rocard12381092018-04-11 09:19:59 -07003085 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00003086}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003087
Kevin Rocard12381092018-04-11 09:19:59 -07003088void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
3089 const StreamOutHalInterface::SourceMetadata& metadata)
3090{
3091 mOutput->stream->updateSourceMetadata(metadata);
3092};
3093
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003094status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08003095{
3096 if (halFrames == NULL || dspFrames == NULL) {
3097 return BAD_VALUE;
3098 }
3099 Mutex::Autolock _l(mLock);
3100 if (initCheck() != NO_ERROR) {
3101 return INVALID_OPERATION;
3102 }
Andy Hung818e7a32016-02-16 18:08:07 -08003103 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003104 *halFrames = framesWritten;
3105
3106 if (isSuspended()) {
3107 // return an estimation of rendered frames when the output is suspended
3108 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003109 *dspFrames = (uint32_t)
3110 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003111 return NO_ERROR;
3112 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003113 status_t status;
3114 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003115 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003116 *dspFrames = (size_t)frames;
3117 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003118 }
3119}
3120
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003121product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003122{
3123 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3124 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3125 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003126 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003127 }
3128 for (size_t i = 0; i < mTracks.size(); i++) {
3129 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003130 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003131 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003132 }
3133 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003134 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003135}
3136
3137
Phil Burk062e67a2015-02-11 13:40:50 -08003138AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003139{
3140 Mutex::Autolock _l(mLock);
3141 return mOutput;
3142}
3143
Phil Burk062e67a2015-02-11 13:40:50 -08003144AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003145{
3146 Mutex::Autolock _l(mLock);
3147 AudioStreamOut *output = mOutput;
3148 mOutput = NULL;
3149 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3150 // must push a NULL and wait for ack
3151 mOutputSink.clear();
3152 mPipeSink.clear();
3153 mNormalSink.clear();
3154 return output;
3155}
3156
3157// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003158sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003159{
3160 if (mOutput == NULL) {
3161 return NULL;
3162 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003163 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003164}
3165
3166uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3167{
3168 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3169}
3170
3171status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3172{
3173 if (!isValidSyncEvent(event)) {
3174 return BAD_VALUE;
3175 }
3176
3177 Mutex::Autolock _l(mLock);
3178
3179 for (size_t i = 0; i < mTracks.size(); ++i) {
3180 sp<Track> track = mTracks[i];
3181 if (event->triggerSession() == track->sessionId()) {
3182 (void) track->setSyncEvent(event);
3183 return NO_ERROR;
3184 }
3185 }
3186
3187 return NAME_NOT_FOUND;
3188}
3189
3190bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3191{
3192 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3193}
3194
3195void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3196 const Vector< sp<Track> >& tracksToRemove)
3197{
Andy Hungfe726a62018-09-27 15:17:25 -07003198 // Miscellaneous track cleanup when removed from the active list,
3199 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003200#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003201 for (const auto& track : tracksToRemove) {
3202 if (track->isExternalTrack()) {
3203 // to track the speaker usage
3204 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003205 }
3206 }
Andy Hungfe726a62018-09-27 15:17:25 -07003207#else
3208 (void)tracksToRemove; // suppress unused warning
3209#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003210}
3211
3212void AudioFlinger::PlaybackThread::checkSilentMode_l()
3213{
3214 if (!mMasterMute) {
3215 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003216 if (mOutDeviceTypeAddrs.empty()) {
3217 ALOGD("ro.audio.silent is ignored since no output device is set");
3218 return;
3219 }
jiabinc52b1ff2019-10-31 17:20:42 -07003220 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003221 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3222 return;
3223 }
Eric Laurent81784c32012-11-19 14:55:58 -08003224 if (property_get("ro.audio.silent", value, "0") > 0) {
3225 char *endptr;
3226 unsigned long ul = strtoul(value, &endptr, 0);
3227 if (*endptr == '\0' && ul != 0) {
3228 ALOGD("Silence is golden");
3229 // The setprop command will not allow a property to be changed after
3230 // the first time it is set, so we don't have to worry about un-muting.
3231 setMasterMute_l(true);
3232 }
3233 }
3234 }
3235}
3236
3237// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003238ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003239{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003240 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003241 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003242 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003243 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003244
3245 // If an NBAIO sink is present, use it to write the normal mixer's submix
3246 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003247
Andy Hung010a1a12014-03-13 13:57:33 -07003248 const size_t count = mBytesRemaining / mFrameSize;
3249
Simon Wilson2d590962012-11-29 15:18:50 -08003250 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003251 // update the setpoint when AudioFlinger::mScreenState changes
3252 uint32_t screenState = AudioFlinger::mScreenState;
3253 if (screenState != mScreenState) {
3254 mScreenState = screenState;
3255 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3256 if (pipe != NULL) {
3257 pipe->setAvgFrames((mScreenState & 1) ?
3258 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3259 }
3260 }
Andy Hung010a1a12014-03-13 13:57:33 -07003261 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003262 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003263 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003264 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003265#ifdef TEE_SINK
3266 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3267#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003268 } else {
3269 bytesWritten = framesWritten;
3270 }
3271 // otherwise use the HAL / AudioStreamOut directly
3272 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003273 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003274
Eric Laurentbfb1b832013-01-07 09:53:42 -08003275 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003276 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3277 mWriteAckSequence += 2;
3278 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003279 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003280 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003281 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003282 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003283 // FIXME We should have an implementation of timestamps for direct output threads.
3284 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003285 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003286 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003287
Eric Laurentbfb1b832013-01-07 09:53:42 -08003288 if (mUseAsyncWrite &&
3289 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3290 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003291 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003292 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003293 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003294 }
Eric Laurent81784c32012-11-19 14:55:58 -08003295 }
3296
Eric Laurent81784c32012-11-19 14:55:58 -08003297 mNumWrites++;
3298 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003299 if (mStandby) {
3300 mThreadMetrics.logBeginInterval();
3301 mStandby = false;
3302 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003303 return bytesWritten;
3304}
3305
3306void AudioFlinger::PlaybackThread::threadLoop_drain()
3307{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003308 bool supportsDrain = false;
3309 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003310 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3311 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003312 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3313 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003314 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003315 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003316 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003317 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003318 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003319 }
3320}
3321
3322void AudioFlinger::PlaybackThread::threadLoop_exit()
3323{
Eric Laurent275e8e92014-11-30 15:14:47 -08003324 {
3325 Mutex::Autolock _l(mLock);
3326 for (size_t i = 0; i < mTracks.size(); i++) {
3327 sp<Track> track = mTracks[i];
3328 track->invalidate();
3329 }
Andy Hungdae27702016-10-31 14:01:16 -07003330 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3331 // After we exit there are no more track changes sent to BatteryNotifier
3332 // because that requires an active threadLoop.
3333 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3334 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003335 }
Eric Laurent81784c32012-11-19 14:55:58 -08003336}
3337
3338/*
3339The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003340 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003341 - mActiveSleepTimeUs from activeSleepTimeUs()
3342 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003343 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3344 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003345 - maxPeriod from frame count and sample rate (MIXER only)
3346
3347The parameters that affect these derived values are:
3348 - frame count
3349 - frame size
3350 - sample rate
3351 - device type: A2DP or not
3352 - device latency
3353 - format: PCM or not
3354 - active sleep time
3355 - idle sleep time
3356*/
3357
3358void AudioFlinger::PlaybackThread::cacheParameters_l()
3359{
Andy Hung25c2dac2014-02-27 14:56:00 -08003360 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003361 mActiveSleepTimeUs = activeSleepTimeUs();
3362 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003363
3364 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3365 // truncating audio when going to standby.
3366 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003367 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003368 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3369 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3370 }
3371 }
Eric Laurent81784c32012-11-19 14:55:58 -08003372}
3373
Eric Laurent13084622016-05-17 10:51:49 -07003374bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003375{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003376 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003377 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003378 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003379 size_t size = mTracks.size();
3380 for (size_t i = 0; i < size; i++) {
3381 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003382 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003383 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003384 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003385 }
3386 }
Eric Laurent13084622016-05-17 10:51:49 -07003387 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003388}
3389
Haynes Mathew George05317d22016-05-03 16:34:26 -07003390void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3391{
3392 Mutex::Autolock _l(mLock);
3393 invalidateTracks_l(streamType);
3394}
3395
jiabinf042b9b2021-05-07 23:46:28 +00003396// getTrackById_l must be called with holding thread lock
3397AudioFlinger::PlaybackThread::Track* AudioFlinger::PlaybackThread::getTrackById_l(
3398 audio_port_handle_t trackPortId) {
3399 for (size_t i = 0; i < mTracks.size(); i++) {
3400 if (mTracks[i]->portId() == trackPortId) {
3401 return mTracks[i].get();
3402 }
3403 }
3404 return nullptr;
3405}
3406
Eric Laurent81784c32012-11-19 14:55:58 -08003407status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3408{
Glenn Kastend848eb42016-03-08 13:42:11 -08003409 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003410 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003411 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003412 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3413 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3414 &halInBuffer);
3415 if (result != OK) return result;
3416 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003417 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003418 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003419 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003420 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003421 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003422 if (mType != DIRECT) {
Eric Laurentf1f22e72021-07-13 14:04:14 +02003423 size_t numSamples = mNormalFrameCount
3424 * (audio_channel_count_from_out_mask(mMixerChannelMask) + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003425 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003426 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003427 &halInBuffer);
3428 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003429#ifdef FLOAT_EFFECT_CHAIN
3430 buffer = halInBuffer->audioBuffer()->f32;
3431#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003432 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003433#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003434 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3435 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003436 }
3437
3438 // Attach all tracks with same session ID to this chain.
3439 for (size_t i = 0; i < mTracks.size(); ++i) {
3440 sp<Track> track = mTracks[i];
3441 if (session == track->sessionId()) {
3442 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3443 buffer);
3444 track->setMainBuffer(buffer);
3445 chain->incTrackCnt();
3446 }
3447 }
3448
3449 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003450 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003451 if (session == track->sessionId()) {
3452 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3453 chain->incActiveTrackCnt();
3454 }
3455 }
3456 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003457 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003458 chain->setInBuffer(halInBuffer);
3459 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003460 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3461 // chains list in order to be processed last as it contains output device effects.
3462 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3463 // processing effects specific to an output stream before effects applied to all streams
3464 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003465 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3466 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003467 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003468 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003469 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003470 // Effect chain for other sessions are inserted at beginning of effect
3471 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003472 // sessions is not important.
3473 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003474 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3475 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003476 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003477 size_t size = mEffectChains.size();
3478 size_t i = 0;
3479 for (i = 0; i < size; i++) {
3480 if (mEffectChains[i]->sessionId() < session) {
3481 break;
3482 }
3483 }
3484 mEffectChains.insertAt(chain, i);
3485 checkSuspendOnAddEffectChain_l(chain);
3486
3487 return NO_ERROR;
3488}
3489
3490size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3491{
Glenn Kastend848eb42016-03-08 13:42:11 -08003492 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003493
3494 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3495
3496 for (size_t i = 0; i < mEffectChains.size(); i++) {
3497 if (chain == mEffectChains[i]) {
3498 mEffectChains.removeAt(i);
3499 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003500 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003501 if (session == track->sessionId()) {
3502 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3503 chain.get(), session);
3504 chain->decActiveTrackCnt();
3505 }
3506 }
3507
3508 // detach all tracks with same session ID from this chain
3509 for (size_t i = 0; i < mTracks.size(); ++i) {
3510 sp<Track> track = mTracks[i];
3511 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003512 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003513 chain->decTrackCnt();
3514 }
3515 }
3516 break;
3517 }
3518 }
3519 return mEffectChains.size();
3520}
3521
3522status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003523 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003524{
3525 Mutex::Autolock _l(mLock);
3526 return attachAuxEffect_l(track, EffectId);
3527}
3528
3529status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003530 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003531{
3532 status_t status = NO_ERROR;
3533
3534 if (EffectId == 0) {
3535 track->setAuxBuffer(0, NULL);
3536 } else {
3537 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3538 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3539 if (effect != 0) {
3540 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3541 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3542 } else {
3543 status = INVALID_OPERATION;
3544 }
3545 } else {
3546 status = BAD_VALUE;
3547 }
3548 }
3549 return status;
3550}
3551
3552void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3553{
3554 for (size_t i = 0; i < mTracks.size(); ++i) {
3555 sp<Track> track = mTracks[i];
3556 if (track->auxEffectId() == effectId) {
3557 attachAuxEffect_l(track, 0);
3558 }
3559 }
3560}
3561
3562bool AudioFlinger::PlaybackThread::threadLoop()
3563{
Glenn Kasten388d5712017-04-07 14:38:41 -07003564 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003565
Eric Laurent81784c32012-11-19 14:55:58 -08003566 Vector< sp<Track> > tracksToRemove;
3567
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003568 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003569 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003570
3571 // MIXER
3572 nsecs_t lastWarning = 0;
3573
3574 // DUPLICATING
3575 // FIXME could this be made local to while loop?
3576 writeFrames = 0;
3577
3578 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003579 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003580
3581 if (mType == MIXER) {
3582 sleepTimeShift = 0;
3583 }
3584
3585 CpuStats cpuStats;
3586 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3587
3588 acquireWakeLock();
3589
Glenn Kasteneef598c2017-04-03 14:41:13 -07003590 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3591 // thread associated with this PlaybackThread.
3592 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3593 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003594 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3595 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003596 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003597 const char *logString = NULL;
3598
rago1bb90822017-05-02 18:31:48 -07003599 // Estimated time for next buffer to be written to hal. This is used only on
3600 // suspended mode (for now) to help schedule the wait time until next iteration.
3601 nsecs_t timeLoopNextNs = 0;
3602
Eric Laurent664539d2013-09-23 18:24:31 -07003603 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003604
Andy Hung2dbffc22018-08-08 18:50:41 -07003605 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003606
Eric Laurentb3f315a2021-07-13 15:09:05 +02003607 sendCheckOutputStageEffectsEvent();
3608
Andy Hung446f4df2019-02-21 12:26:41 -08003609 // loopCount is used for statistics and diagnostics.
3610 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003611 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003612 // Log merge requests are performed during AudioFlinger binder transactions, but
3613 // that does not cover audio playback. It's requested here for that reason.
3614 mAudioFlinger->requestLogMerge();
3615
Eric Laurent81784c32012-11-19 14:55:58 -08003616 cpuStats.sample(myName);
3617
3618 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003619 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003620 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003621
Andy Hung2dbffc22018-08-08 18:50:41 -07003622 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3623 //
jiabinc52b1ff2019-10-31 17:20:42 -07003624 // Note: we access outDeviceTypes() outside of mLock.
3625 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003626 // Here, we try for the AF lock, but do not block on it as the latency
3627 // is more informational.
3628 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3629 std::vector<PatchPanel::SoftwarePatch> swPatches;
3630 double latencyMs;
3631 status_t status = INVALID_OPERATION;
3632 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3633 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3634 && swPatches.size() > 0) {
3635 status = swPatches[0].getLatencyMs_l(&latencyMs);
3636 downstreamPatchHandle = swPatches[0].getPatchHandle();
3637 }
3638 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003639 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003640 lastDownstreamPatchHandle = downstreamPatchHandle;
3641 }
3642 if (status == OK) {
3643 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003644 // latency of 5 seconds).
3645 const double minLatency = 0., maxLatency = 5000.;
3646 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003647 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003648 } else {
3649 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003650 if (latencyMs < minLatency) latencyMs = minLatency;
3651 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003652 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003653 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003654 }
3655 mAudioFlinger->mLock.unlock();
3656 }
3657 } else {
3658 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3659 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003660 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003661 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3662 }
3663 }
3664
Eric Laurentb3f315a2021-07-13 15:09:05 +02003665 if (mCheckOutputStageEffects.exchange(false)) {
3666 checkOutputStageEffects();
3667 }
3668
Eric Laurent81784c32012-11-19 14:55:58 -08003669 { // scope for mLock
3670
3671 Mutex::Autolock _l(mLock);
3672
Eric Laurent021cf962014-05-13 10:18:14 -07003673 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003674 if (mCheckOutputStageEffects.load()) {
3675 continue;
3676 }
Eric Laurent10351942014-05-08 18:49:52 -07003677
Glenn Kasteneef598c2017-04-03 14:41:13 -07003678 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003679 if (logString != NULL) {
3680 mNBLogWriter->logTimestamp();
3681 mNBLogWriter->log(logString);
3682 logString = NULL;
3683 }
3684
Dean Wheatley12473e92021-03-18 23:00:55 +11003685 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003686
Eric Laurent81784c32012-11-19 14:55:58 -08003687 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003688 if (mSignalPending) {
3689 // A signal was raised while we were unlocked
3690 mSignalPending = false;
3691 } else if (waitingAsyncCallback_l()) {
3692 if (exitPending()) {
3693 break;
3694 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003695 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003696 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003697 releaseWakeLock_l();
3698 released = true;
3699 }
Andy Hung10cbff12017-02-21 17:30:14 -08003700
3701 const int64_t waitNs = computeWaitTimeNs_l();
3702 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3703 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3704 if (status == TIMED_OUT) {
3705 mSignalPending = true; // if timeout recheck everything
3706 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003707 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003708 if (released) {
3709 acquireWakeLock_l();
3710 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003711 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3712 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003713
3714 continue;
3715 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003716 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003717 isSuspended()) {
3718 // put audio hardware into standby after short delay
3719 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003720
3721 threadLoop_standby();
3722
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003723 // This is where we go into standby
3724 if (!mStandby) {
3725 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003726 mThreadMetrics.logEndInterval();
3727 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003728 }
Andy Hungd0979812019-02-21 15:51:44 -08003729 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003730 }
3731
Eric Tan39ec8d62018-07-24 09:49:29 -07003732 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003733 // we're about to wait, flush the binder command buffer
3734 IPCThreadState::self()->flushCommands();
3735
3736 clearOutputTracks();
3737
3738 if (exitPending()) {
3739 break;
3740 }
3741
3742 releaseWakeLock_l();
3743 // wait until we have something to do...
3744 ALOGV("%s going to sleep", myName.string());
3745 mWaitWorkCV.wait(mLock);
3746 ALOGV("%s waking up", myName.string());
3747 acquireWakeLock_l();
3748
3749 mMixerStatus = MIXER_IDLE;
3750 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3751 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003752 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003753 checkSilentMode_l();
3754
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003755 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3756 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003757 if (mType == MIXER) {
3758 sleepTimeShift = 0;
3759 }
3760
3761 continue;
3762 }
3763 }
Eric Laurent81784c32012-11-19 14:55:58 -08003764 // mMixerStatusIgnoringFastTracks is also updated internally
3765 mMixerStatus = prepareTracks_l(&tracksToRemove);
3766
Andy Hungdae27702016-10-31 14:01:16 -07003767 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003768
Kevin Rocard069c2712018-03-29 19:09:14 -07003769 updateMetadata_l();
3770
Eric Laurent81784c32012-11-19 14:55:58 -08003771 // prevent any changes in effect chain list and in each effect chain
3772 // during mixing and effect process as the audio buffers could be deleted
3773 // or modified if an effect is created or deleted
3774 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003775
3776 // Determine which session to pick up haptic data.
3777 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003778 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003779 // TODO: Write haptic data directly to sink buffer when mixing.
3780 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3781 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003782 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
3783 if (effectChain != nullptr && effectChain->containsHapticGeneratingEffect_l()) {
3784 activeHapticSessionId = track->sessionId();
3785 break;
3786 }
Andy Hung6e6a2e62019-04-30 16:38:41 -07003787 if (track->getHapticPlaybackEnabled()) {
3788 activeHapticSessionId = track->sessionId();
3789 break;
3790 }
3791 }
3792 }
3793
Andy Hungc1646382019-04-30 16:12:10 -07003794 // Acquire a local copy of active tracks with lock (release w/o lock).
3795 //
3796 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3797 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3798 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3799 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003800 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003801
Eric Laurentbfb1b832013-01-07 09:53:42 -08003802 if (mBytesRemaining == 0) {
3803 mCurrentWriteLength = 0;
3804 if (mMixerStatus == MIXER_TRACKS_READY) {
3805 // threadLoop_mix() sets mCurrentWriteLength
3806 threadLoop_mix();
3807 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3808 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003809 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003810 // must be written to HAL
3811 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003812 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003813 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003814
3815 // Tally underrun frames as we are inserting 0s here.
3816 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003817 if (track->mFillingUpStatus == Track::FS_ACTIVE
3818 && !track->isStopped()
3819 && !track->isPaused()
3820 && !track->isTerminated()) {
3821 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3822 __func__, track->id(), track->getTrackStateAsString(),
3823 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003824 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3825 }
3826 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003827 }
3828 }
Andy Hung98ef9782014-03-04 14:46:50 -08003829 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003830 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003831 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3832 // or mSinkBuffer (if there are no effects).
3833 //
3834 // This is done pre-effects computation; if effects change to
3835 // support higher precision, this needs to move.
3836 //
3837 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003838 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003839 if (mMixerBufferValid) {
3840 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3841 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003842 uint32_t channelCount = mEffectBufferValid ?
3843 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
Andy Hung98ef9782014-03-04 14:46:50 -08003844
Andy Hung2ddee192015-12-18 17:34:44 -08003845 // mono blend occurs for mixer threads only (not direct or offloaded)
3846 // and is handled here if we're going directly to the sink.
3847 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003848 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3849 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003850 }
3851
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003852 if (!hasFastMixer()) {
3853 // Balance must take effect after mono conversion.
3854 // We do it here if there is no FastMixer.
3855 // mBalance detects zero balance within the class for speed (not needed here).
3856 mBalance.setBalance(mMasterBalance.load());
3857 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3858 }
3859
Andy Hung98ef9782014-03-04 14:46:50 -08003860 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurentf1f22e72021-07-13 14:04:14 +02003861 mNormalFrameCount * (channelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08003862
3863 // If we're going directly to the sink and there are haptic channels,
3864 // we should adjust channels as the sample data is partially interleaved
3865 // in this case.
3866 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3867 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3868 mChannelCount + mHapticChannelCount,
3869 audio_bytes_per_sample(format),
3870 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3871 }
Andy Hung98ef9782014-03-04 14:46:50 -08003872 }
3873
Eric Laurentbfb1b832013-01-07 09:53:42 -08003874 mBytesRemaining = mCurrentWriteLength;
3875 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003876 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3877 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3878 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3879 mBytesWritten += mBytesRemaining;
3880 mFramesWritten += framesRemaining;
3881 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003882 mBytesRemaining = 0;
3883 }
Eric Laurent81784c32012-11-19 14:55:58 -08003884
Eric Laurentbfb1b832013-01-07 09:53:42 -08003885 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003886 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003887 for (size_t i = 0; i < effectChains.size(); i ++) {
3888 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003889 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003890 if (activeHapticSessionId != AUDIO_SESSION_NONE
3891 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003892 // Haptic data is active in this case, copy it directly from
3893 // in buffer to out buffer.
3894 const size_t audioBufferSize = mNormalFrameCount
3895 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3896 memcpy_by_audio_format(
3897 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3898 EFFECT_BUFFER_FORMAT,
3899 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3900 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3901 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003902 }
Eric Laurent81784c32012-11-19 14:55:58 -08003903 }
3904 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003905 // Process effect chains for offloaded thread even if no audio
3906 // was read from audio track: process only updates effect state
3907 // and thus does have to be synchronized with audio writes but may have
3908 // to be called while waiting for async write callback
3909 if (mType == OFFLOAD) {
3910 for (size_t i = 0; i < effectChains.size(); i ++) {
3911 effectChains[i]->process_l();
3912 }
3913 }
Eric Laurent81784c32012-11-19 14:55:58 -08003914
Andy Hung98ef9782014-03-04 14:46:50 -08003915 // Only if the Effects buffer is enabled and there is data in the
3916 // Effects buffer (buffer valid), we need to
3917 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003918 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003919 if (mEffectBufferValid) {
3920 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003921
3922 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003923 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3924 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003925 }
3926
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003927 if (!hasFastMixer()) {
3928 // Balance must take effect after mono conversion.
3929 // We do it here if there is no FastMixer.
3930 // mBalance detects zero balance within the class for speed (not needed here).
3931 mBalance.setBalance(mMasterBalance.load());
3932 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3933 }
3934
Andy Hung98ef9782014-03-04 14:46:50 -08003935 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003936 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3937 // The sample data is partially interleaved when haptic channels exist,
3938 // we need to adjust channels here.
3939 if (mHapticChannelCount > 0) {
3940 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3941 mChannelCount + mHapticChannelCount,
3942 audio_bytes_per_sample(mFormat),
3943 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3944 }
Andy Hung98ef9782014-03-04 14:46:50 -08003945 }
3946
Eric Laurent81784c32012-11-19 14:55:58 -08003947 // enable changes in effect chain
3948 unlockEffectChains(effectChains);
3949
Eric Laurentbfb1b832013-01-07 09:53:42 -08003950 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003951 // mSleepTimeUs == 0 means we must write to audio hardware
3952 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003953 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003954 // writePeriodNs is updated >= 0 when ret > 0.
3955 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003956 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003957 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003958 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003959 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003960 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003961 if (ret < 0) {
3962 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003963 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003964 mBytesWritten += ret;
3965 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003966 const int64_t frames = ret / mFrameSize;
3967 mFramesWritten += frames;
3968
3969 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3970 // process information relating to write time.
3971 if (audio_has_proportional_frames(mFormat)) {
3972 // we are in a continuous mixing cycle
3973 if (mMixerStatus == MIXER_TRACKS_READY &&
3974 loopCount == lastLoopCountWritten + 1) {
3975
3976 const double jitterMs =
3977 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3978 {frames, writePeriodNs},
3979 {0, 0} /* lastTimestamp */, mSampleRate);
3980 const double processMs =
3981 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3982
3983 Mutex::Autolock _l(mLock);
3984 mIoJitterMs.add(jitterMs);
3985 mProcessTimeMs.add(processMs);
3986 }
3987
3988 // write blocked detection
3989 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3990 if (mType == MIXER && deltaWriteNs > maxPeriod) {
3991 mNumDelayedWrites++;
3992 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3993 ATRACE_NAME("underrun");
3994 ALOGW("write blocked for %lld msecs, "
3995 "%d delayed writes, thread %d",
3996 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3997 mNumDelayedWrites, mId);
3998 lastWarning = lastIoEndNs;
3999 }
4000 }
4001 }
4002 // update timing info.
4003 mLastIoBeginNs = lastIoBeginNs;
4004 mLastIoEndNs = lastIoEndNs;
4005 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004006 }
4007 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4008 (mMixerStatus == MIXER_DRAIN_ALL)) {
4009 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004010 }
Andy Hung08fb1742015-05-31 23:22:10 -07004011 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004012
4013 if (mThreadThrottle
4014 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004015 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004016 // Limit MixerThread data processing to no more than twice the
4017 // expected processing rate.
4018 //
4019 // This helps prevent underruns with NuPlayer and other applications
4020 // which may set up buffers that are close to the minimum size, or use
4021 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4022 //
4023 // The throttle smooths out sudden large data drains from the device,
4024 // e.g. when it comes out of standby, which often causes problems with
4025 // (1) mixer threads without a fast mixer (which has its own warm-up)
4026 // (2) minimum buffer sized tracks (even if the track is full,
4027 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004028 //
4029 // Total time spent in last processing cycle equals time spent in
4030 // 1. threadLoop_write, as well as time spent in
4031 // 2. threadLoop_mix (significant for heavy mixing, especially
4032 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004033
Andy Hung446f4df2019-02-21 12:26:41 -08004034 // it's OK if deltaMs is an overestimate.
4035
4036 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004037
Ivan Lozanoea04d392017-11-07 14:37:07 -08004038 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004039 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004040 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004041
Andy Hung08fb1742015-05-31 23:22:10 -07004042 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004043 // notify of throttle start on verbose log
4044 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4045 "mixer(%p) throttle begin:"
4046 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004047 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004048 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004049 // Throttle must be attributed to the previous mixer loop's write time
4050 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004051 // This also ensures proper timing statistics.
4052 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004053 } else {
4054 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4055 if (diff > 0) {
4056 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004057 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004058 ALOGD_IF(!isSingleDeviceType(
4059 outDeviceTypes(), audio_is_a2dp_out_device) &&
4060 !isSingleDeviceType(
4061 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004062 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004063 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4064 }
Andy Hung08fb1742015-05-31 23:22:10 -07004065 }
4066 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004067 }
Eric Laurent81784c32012-11-19 14:55:58 -08004068
Eric Laurentbfb1b832013-01-07 09:53:42 -08004069 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004070 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004071 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004072 // suspended requires accurate metering of sleep time.
4073 if (isSuspended()) {
4074 // advance by expected sleepTime
4075 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4076 const nsecs_t nowNs = systemTime();
4077
4078 // compute expected next time vs current time.
4079 // (negative deltas are treated as delays).
4080 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4081 if (deltaNs < -kMaxNextBufferDelayNs) {
4082 // Delays longer than the max allowed trigger a reset.
4083 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4084 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4085 timeLoopNextNs = nowNs + deltaNs;
4086 } else if (deltaNs < 0) {
4087 // Delays within the max delay allowed: zero the delta/sleepTime
4088 // to help the system catch up in the next iteration(s)
4089 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4090 deltaNs = 0;
4091 }
4092 // update sleep time (which is >= 0)
4093 mSleepTimeUs = deltaNs / 1000;
4094 }
Eric Laurente93cc032016-05-05 10:15:10 -07004095 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4096 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004097 }
Glenn Kastene7754022014-10-31 12:11:26 -07004098 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004099 }
Eric Laurent81784c32012-11-19 14:55:58 -08004100 }
4101
4102 // Finally let go of removed track(s), without the lock held
4103 // since we can't guarantee the destructors won't acquire that
4104 // same lock. This will also mutate and push a new fast mixer state.
4105 threadLoop_removeTracks(tracksToRemove);
4106 tracksToRemove.clear();
4107
4108 // FIXME I don't understand the need for this here;
4109 // it was in the original code but maybe the
4110 // assignment in saveOutputTracks() makes this unnecessary?
4111 clearOutputTracks();
4112
4113 // Effect chains will be actually deleted here if they were removed from
4114 // mEffectChains list during mixing or effects processing
4115 effectChains.clear();
4116
4117 // FIXME Note that the above .clear() is no longer necessary since effectChains
4118 // is now local to this block, but will keep it for now (at least until merge done).
4119 }
4120
Eric Laurentbfb1b832013-01-07 09:53:42 -08004121 threadLoop_exit();
4122
Eric Laurentcf817a22014-08-04 20:36:31 -07004123 if (!mStandby) {
4124 threadLoop_standby();
4125 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004126 }
4127
4128 releaseWakeLock();
4129
4130 ALOGV("Thread %p type %d exiting", this, mType);
4131 return false;
4132}
4133
Dean Wheatley12473e92021-03-18 23:00:55 +11004134void AudioFlinger::PlaybackThread::collectTimestamps_l()
4135{
4136 // Collect timestamp statistics for the Playback Thread types that support it.
4137 if (mType != MIXER
4138 && mType != DUPLICATING
4139 && mType != DIRECT
4140 && mType != OFFLOAD) {
4141 return;
4142 }
4143 if (mStandby) {
4144 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4145 return;
4146 } else if (mHwPaused) {
4147 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4148 return;
4149 }
4150
4151 // Gather the framesReleased counters for all active tracks,
4152 // and associate with the sink frames written out. We need
4153 // this to convert the sink timestamp to the track timestamp.
4154 bool kernelLocationUpdate = false;
4155 ExtendedTimestamp timestamp; // use private copy to fetch
4156
4157 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4158 // HAL may be draining some small duration buffered data for fade out.
4159 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4160 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4161 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4162 mSampleRate);
4163
4164 if (isTimestampCorrectionEnabled()) {
4165 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4166 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4167 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4168 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4169 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4170 = correctedTimestamp.mFrames;
4171 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4172 = correctedTimestamp.mTimeNs;
4173 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4174 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4175 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4176
4177 // Note: Downstream latency only added if timestamp correction enabled.
4178 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4179 const int64_t newPosition =
4180 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4181 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4182 // prevent retrograde
4183 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4184 newPosition,
4185 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4186 - mSuspendedFrames));
4187 }
4188 }
4189
4190 // We always fetch the timestamp here because often the downstream
4191 // sink will block while writing.
4192
4193 // We keep track of the last valid kernel position in case we are in underrun
4194 // and the normal mixer period is the same as the fast mixer period, or there
4195 // is some error from the HAL.
4196 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4197 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4198 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4199 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4200 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4201
4202 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4203 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4204 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4205 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4206 }
4207
4208 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4209 kernelLocationUpdate = true;
4210 } else {
4211 ALOGVV("getTimestamp error - no valid kernel position");
4212 }
4213
4214 // copy over kernel info
4215 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4216 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4217 + mSuspendedFrames; // add frames discarded when suspended
4218 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4219 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4220 } else {
4221 mTimestampVerifier.error();
4222 }
4223
4224 // mFramesWritten for non-offloaded tracks are contiguous
4225 // even after standby() is called. This is useful for the track frame
4226 // to sink frame mapping.
4227 bool serverLocationUpdate = false;
4228 if (mFramesWritten != mLastFramesWritten) {
4229 serverLocationUpdate = true;
4230 mLastFramesWritten = mFramesWritten;
4231 }
4232 // Only update timestamps if there is a meaningful change.
4233 // Either the kernel timestamp must be valid or we have written something.
4234 if (kernelLocationUpdate || serverLocationUpdate) {
4235 if (serverLocationUpdate) {
4236 // use the time before we called the HAL write - it is a bit more accurate
4237 // to when the server last read data than the current time here.
4238 //
4239 // If we haven't written anything, mLastIoBeginNs will be -1
4240 // and we use systemTime().
4241 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4242 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4243 ? systemTime() : mLastIoBeginNs;
4244 }
4245
4246 for (const sp<Track> &t : mActiveTracks) {
4247 if (!t->isFastTrack()) {
4248 t->updateTrackFrameInfo(
4249 t->mAudioTrackServerProxy->framesReleased(),
4250 mFramesWritten,
4251 mSampleRate,
4252 mTimestamp);
4253 }
4254 }
4255 }
4256
4257 if (audio_has_proportional_frames(mFormat)) {
4258 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4259 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4260 mLatencyMs.add(latencyMs);
4261 }
4262 }
4263#if 0
4264 // logFormat example
4265 if (z % 100 == 0) {
4266 timespec ts;
4267 clock_gettime(CLOCK_MONOTONIC, &ts);
4268 LOGT("This is an integer %d, this is a float %f, this is my "
4269 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4270 LOGT("A deceptive null-terminated string %\0");
4271 }
4272 ++z;
4273#endif
4274}
4275
Eric Laurentbfb1b832013-01-07 09:53:42 -08004276// removeTracks_l() must be called with ThreadBase::mLock held
4277void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4278{
Andy Hungfe726a62018-09-27 15:17:25 -07004279 for (const auto& track : tracksToRemove) {
4280 mActiveTracks.remove(track);
4281 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4282 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4283 if (chain != 0) {
4284 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4285 __func__, track->id(), chain.get(), track->sessionId());
4286 chain->decActiveTrackCnt();
4287 }
4288 // If an external client track, inform APM we're no longer active, and remove if needed.
4289 // We do this under lock so that the state is consistent if the Track is destroyed.
4290 if (track->isExternalTrack()) {
4291 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004292 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004293 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004294 }
4295 }
Andy Hungfe726a62018-09-27 15:17:25 -07004296 if (track->isTerminated()) {
4297 // remove from our tracks vector
4298 removeTrack_l(track);
4299 }
jiabineb3bda02020-06-30 14:07:03 -07004300 if (mHapticChannelCount > 0 &&
4301 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4302 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004303 mLock.unlock();
4304 // Unlock due to VibratorService will lock for this call and will
4305 // call Tracks.mute/unmute which also require thread's lock.
4306 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4307 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004308
4309 // When the track is stop, set the haptic intensity as MUTE
4310 // for the HapticGenerator effect.
4311 if (chain != nullptr) {
4312 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4313 }
jiabin245cdd92018-12-07 17:55:15 -08004314 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004315 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004316}
Eric Laurent81784c32012-11-19 14:55:58 -08004317
Eric Laurentaccc1472013-09-20 09:36:34 -07004318status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4319{
4320 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004321 ExtendedTimestamp ets;
4322 status_t status = mNormalSink->getTimestamp(ets);
4323 if (status == NO_ERROR) {
4324 status = ets.getBestTimestamp(&timestamp);
4325 }
4326 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004327 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004328 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004329 collectTimestamps_l();
4330 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4331 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004332 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004333 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4334 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4335 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4336 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4337 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004338 }
4339 return INVALID_OPERATION;
4340}
Eric Laurent1c333e22014-05-20 10:48:17 -07004341
Eric Laurenteab90452019-06-24 15:17:46 -07004342// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4343// still applied by the mixer.
4344// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4345// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4346// if more than one track are active
4347status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4348{
4349 status_t result = NO_ERROR;
4350 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4351 if (*volume != mLeftVolFloat) {
4352 result = mOutput->stream->setVolume(*volume, *volume);
4353 ALOGE_IF(result != OK,
4354 "Error when setting output stream volume: %d", result);
4355 if (result == NO_ERROR) {
4356 mLeftVolFloat = *volume;
4357 }
4358 }
4359 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4360 // remove stream volume contribution from software volume.
4361 if (mLeftVolFloat == *volume) {
4362 *volume = 1.0f;
4363 }
4364 }
4365 return result;
4366}
4367
Eric Laurent054d9d32015-04-24 08:48:48 -07004368status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4369 audio_patch_handle_t *handle)
4370{
Andy Hungf60abce2016-08-26 11:37:54 -07004371 status_t status;
4372 if (property_get_bool("af.patch_park", false /* default_value */)) {
4373 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4374 // or if HAL does not properly lock against access.
4375 AutoPark<FastMixer> park(mFastMixer);
4376 status = PlaybackThread::createAudioPatch_l(patch, handle);
4377 } else {
4378 status = PlaybackThread::createAudioPatch_l(patch, handle);
4379 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004380 return status;
4381}
4382
Eric Laurent1c333e22014-05-20 10:48:17 -07004383status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4384 audio_patch_handle_t *handle)
4385{
4386 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004387
4388 // store new device and send to effects
4389 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004390 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004391 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004392 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4393 && !mOutput->audioHwDev->supportsAudioPatches(),
4394 "Enumerated device type(%#x) must not be used "
4395 "as it does not support audio patches",
4396 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004397 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07004398 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4399 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004400 }
4401
François Gaffie0c280aa2018-07-25 10:02:15 +02004402 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004403#ifdef ADD_BATTERY_DATA
4404 // when changing the audio output device, call addBatteryData to notify
4405 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004406 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004407 uint32_t params = 0;
4408 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004409 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004410 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004411 }
4412
Eric Laurent054d9d32015-04-24 08:48:48 -07004413 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004414 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004415 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4416 }
4417
4418 if (params != 0) {
4419 addBatteryData(params);
4420 }
4421 }
4422#endif
4423
4424 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004425 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004426 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004427
jiabinc52b1ff2019-10-31 17:20:42 -07004428 // mPatch.num_sinks is not set when the thread is created so that
4429 // the first patch creation triggers an ioConfigChanged callback
4430 bool configChanged = (mPatch.num_sinks == 0) ||
4431 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004432 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004433 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004434 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004435
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004436 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004437 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4438 status = hwDevice->createAudioPatch(patch->num_sources,
4439 patch->sources,
4440 patch->num_sinks,
4441 patch->sinks,
4442 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004443 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004444 char *address;
4445 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4446 //FIXME: we only support address on first sink with HAL version < 3.0
4447 address = audio_device_address_to_parameter(
4448 patch->sinks[0].ext.device.type,
4449 patch->sinks[0].ext.device.address);
4450 } else {
4451 address = (char *)calloc(1, 1);
4452 }
4453 AudioParameter param = AudioParameter(String8(address));
4454 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004455 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004456 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004457 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004458 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004459 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004460
4461 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004462 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004463 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004464 // also dispatch to active AudioTracks for MediaMetrics
4465 for (const auto &track : mActiveTracks) {
4466 track->logEndInterval();
4467 track->logBeginInterval(patchSinksAsString);
4468 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004469
Eric Laurente8726fe2015-06-26 09:39:24 -07004470 if (configChanged) {
4471 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4472 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004473 return status;
4474}
4475
Eric Laurent054d9d32015-04-24 08:48:48 -07004476status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4477{
Andy Hungf60abce2016-08-26 11:37:54 -07004478 status_t status;
4479 if (property_get_bool("af.patch_park", false /* default_value */)) {
4480 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4481 // or if HAL does not properly lock against access.
4482 AutoPark<FastMixer> park(mFastMixer);
4483 status = PlaybackThread::releaseAudioPatch_l(handle);
4484 } else {
4485 status = PlaybackThread::releaseAudioPatch_l(handle);
4486 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004487 return status;
4488}
4489
Eric Laurent1c333e22014-05-20 10:48:17 -07004490status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4491{
4492 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004493
jiabinc52b1ff2019-10-31 17:20:42 -07004494 mPatch = audio_patch{};
4495 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004496
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004497 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004498 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4499 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004500 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004501 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004502 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004503 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004504 }
4505 return status;
4506}
4507
Eric Laurent83b88082014-06-20 18:31:16 -07004508void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4509{
4510 Mutex::Autolock _l(mLock);
4511 mTracks.add(track);
4512}
4513
4514void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4515{
4516 Mutex::Autolock _l(mLock);
4517 destroyTrack_l(track);
4518}
4519
Mikhail Naganovdc769682018-05-04 15:34:08 -07004520void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004521{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004522 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004523 config->role = AUDIO_PORT_ROLE_SOURCE;
4524 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4525 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004526 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4527 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4528 config->flags.output = mOutput->flags;
4529 }
Eric Laurent83b88082014-06-20 18:31:16 -07004530}
4531
Eric Laurent81784c32012-11-19 14:55:58 -08004532// ----------------------------------------------------------------------------
4533
4534AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004535 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
4536 : PlaybackThread(audioFlinger, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004537 // mAudioMixer below
4538 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004539 mFastMixerFutex(0),
4540 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004541 // mOutputSink below
4542 // mPipeSink below
4543 // mNormalSink below
4544{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004545 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004546 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004547 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004548 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004549 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4550 mNormalFrameCount);
4551 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4552
Andy Hungfbfc3952015-01-15 13:33:51 -08004553 if (type == DUPLICATING) {
4554 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4555 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4556 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4557 return;
4558 }
Eric Laurent81784c32012-11-19 14:55:58 -08004559 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004560 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004561 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004562 const NBAIO_Format offers[1] = {Format_from_SR_C(
4563 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004564#if !LOG_NDEBUG
4565 ssize_t index =
4566#else
4567 (void)
4568#endif
4569 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004570 ALOG_ASSERT(index == 0);
4571
4572 // initialize fast mixer depending on configuration
4573 bool initFastMixer;
4574 switch (kUseFastMixer) {
4575 case FastMixer_Never:
4576 initFastMixer = false;
4577 break;
4578 case FastMixer_Always:
4579 initFastMixer = true;
4580 break;
4581 case FastMixer_Static:
4582 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004583 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4584 // where the period is less than an experimentally determined threshold that can be
4585 // scheduled reliably with CFS. However, the BT A2DP HAL is
4586 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4587 initFastMixer = mFrameCount < mNormalFrameCount
jiabinc52b1ff2019-10-31 17:20:42 -07004588 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
Eric Laurent81784c32012-11-19 14:55:58 -08004589 break;
4590 }
Andy Hungfda69402017-02-15 14:33:12 -08004591 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4592 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4593 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004594 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004595 audio_format_t fastMixerFormat;
4596 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4597 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4598 } else {
4599 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4600 }
4601 if (mFormat != fastMixerFormat) {
4602 // change our Sink format to accept our intermediate precision
4603 mFormat = fastMixerFormat;
4604 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004605 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004606 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4607 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4608 }
Eric Laurent81784c32012-11-19 14:55:58 -08004609
4610 // create a MonoPipe to connect our submix to FastMixer
4611 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004612
Andy Hung1258c1a2014-05-23 21:22:17 -07004613 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004614 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004615 format.mFormat = fastMixerFormat;
4616 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4617
Eric Laurent81784c32012-11-19 14:55:58 -08004618 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4619 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4620 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4621 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4622 const NBAIO_Format offers[1] = {format};
4623 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004624#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004625 ssize_t index =
4626#else
4627 (void)
4628#endif
4629 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004630 ALOG_ASSERT(index == 0);
4631 monoPipe->setAvgFrames((mScreenState & 1) ?
4632 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4633 mPipeSink = monoPipe;
4634
Eric Laurent81784c32012-11-19 14:55:58 -08004635 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004636 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004637 FastMixerStateQueue *sq = mFastMixer->sq();
4638#ifdef STATE_QUEUE_DUMP
4639 sq->setObserverDump(&mStateQueueObserverDump);
4640 sq->setMutatorDump(&mStateQueueMutatorDump);
4641#endif
4642 FastMixerState *state = sq->begin();
4643 FastTrack *fastTrack = &state->mFastTracks[0];
4644 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4645 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4646 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004647 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4648 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4649 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004650 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004651 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004652 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01004653 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08004654 fastTrack->mGeneration++;
4655 state->mFastTracksGen++;
4656 state->mTrackMask = 1;
4657 // fast mixer will use the HAL output sink
4658 state->mOutputSink = mOutputSink.get();
4659 state->mOutputSinkGen++;
4660 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004661 // specify sink channel mask when haptic channel mask present as it can not
4662 // be calculated directly from channel count
4663 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004664 ? AUDIO_CHANNEL_NONE
4665 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004666 state->mCommand = FastMixerState::COLD_IDLE;
4667 // already done in constructor initialization list
4668 //mFastMixerFutex = 0;
4669 state->mColdFutexAddr = &mFastMixerFutex;
4670 state->mColdGen++;
4671 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004672 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4673 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004674 sq->end();
4675 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4676
Eric Tan0513b5d2018-09-17 10:32:48 -07004677 NBLog::thread_info_t info;
4678 info.id = mId;
4679 info.type = NBLog::FASTMIXER;
4680 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4681
Eric Laurent81784c32012-11-19 14:55:58 -08004682 // start the fast mixer
4683 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4684 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004685 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004686 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004687
4688#ifdef AUDIO_WATCHDOG
4689 // create and start the watchdog
4690 mAudioWatchdog = new AudioWatchdog();
4691 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4692 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4693 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004694 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004695#endif
Andy Hung8946a282018-04-19 20:04:56 -07004696 } else {
4697#ifdef TEE_SINK
4698 // Only use the MixerThread tee if there is no FastMixer.
4699 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4700 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4701#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004702 }
4703
4704 switch (kUseFastMixer) {
4705 case FastMixer_Never:
4706 case FastMixer_Dynamic:
4707 mNormalSink = mOutputSink;
4708 break;
4709 case FastMixer_Always:
4710 mNormalSink = mPipeSink;
4711 break;
4712 case FastMixer_Static:
4713 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4714 break;
4715 }
4716}
4717
4718AudioFlinger::MixerThread::~MixerThread()
4719{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004720 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004721 FastMixerStateQueue *sq = mFastMixer->sq();
4722 FastMixerState *state = sq->begin();
4723 if (state->mCommand == FastMixerState::COLD_IDLE) {
4724 int32_t old = android_atomic_inc(&mFastMixerFutex);
4725 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004726 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004727 }
4728 }
4729 state->mCommand = FastMixerState::EXIT;
4730 sq->end();
4731 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4732 mFastMixer->join();
4733 // Though the fast mixer thread has exited, it's state queue is still valid.
4734 // We'll use that extract the final state which contains one remaining fast track
4735 // corresponding to our sub-mix.
4736 state = sq->begin();
4737 ALOG_ASSERT(state->mTrackMask == 1);
4738 FastTrack *fastTrack = &state->mFastTracks[0];
4739 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4740 delete fastTrack->mBufferProvider;
4741 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004742 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004743#ifdef AUDIO_WATCHDOG
4744 if (mAudioWatchdog != 0) {
4745 mAudioWatchdog->requestExit();
4746 mAudioWatchdog->requestExitAndWait();
4747 mAudioWatchdog.clear();
4748 }
4749#endif
4750 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004751 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004752 delete mAudioMixer;
4753}
4754
4755
4756uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4757{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004758 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004759 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4760 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4761 }
4762 return latency;
4763}
4764
Eric Laurentbfb1b832013-01-07 09:53:42 -08004765ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004766{
4767 // FIXME we should only do one push per cycle; confirm this is true
4768 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004769 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004770 FastMixerStateQueue *sq = mFastMixer->sq();
4771 FastMixerState *state = sq->begin();
4772 if (state->mCommand != FastMixerState::MIX_WRITE &&
4773 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4774 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004775
4776 // FIXME workaround for first HAL write being CPU bound on some devices
4777 ATRACE_BEGIN("write");
4778 mOutput->write((char *)mSinkBuffer, 0);
4779 ATRACE_END();
4780
Eric Laurent81784c32012-11-19 14:55:58 -08004781 int32_t old = android_atomic_inc(&mFastMixerFutex);
4782 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004783 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004784 }
4785#ifdef AUDIO_WATCHDOG
4786 if (mAudioWatchdog != 0) {
4787 mAudioWatchdog->resume();
4788 }
4789#endif
4790 }
4791 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004792#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004793 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004794 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004795#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004796 sq->end();
4797 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4798 if (kUseFastMixer == FastMixer_Dynamic) {
4799 mNormalSink = mPipeSink;
4800 }
4801 } else {
4802 sq->end(false /*didModify*/);
4803 }
4804 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004805 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004806}
4807
4808void AudioFlinger::MixerThread::threadLoop_standby()
4809{
4810 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004811 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004812 FastMixerStateQueue *sq = mFastMixer->sq();
4813 FastMixerState *state = sq->begin();
4814 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004815 // Report any frames trapped in the Monopipe
4816 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4817 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4818 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4819 "monoPipeWritten:%lld monoPipeLeft:%lld",
4820 (long long)mFramesWritten, (long long)mSuspendedFrames,
4821 (long long)mPipeSink->framesWritten(), pipeFrames);
4822 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4823
Eric Laurent81784c32012-11-19 14:55:58 -08004824 state->mCommand = FastMixerState::COLD_IDLE;
4825 state->mColdFutexAddr = &mFastMixerFutex;
4826 state->mColdGen++;
4827 mFastMixerFutex = 0;
4828 sq->end();
4829 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4830 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4831 if (kUseFastMixer == FastMixer_Dynamic) {
4832 mNormalSink = mOutputSink;
4833 }
4834#ifdef AUDIO_WATCHDOG
4835 if (mAudioWatchdog != 0) {
4836 mAudioWatchdog->pause();
4837 }
4838#endif
4839 } else {
4840 sq->end(false /*didModify*/);
4841 }
4842 }
4843 PlaybackThread::threadLoop_standby();
4844}
4845
Eric Laurentbfb1b832013-01-07 09:53:42 -08004846bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4847{
4848 return false;
4849}
4850
4851bool AudioFlinger::PlaybackThread::shouldStandby_l()
4852{
4853 return !mStandby;
4854}
4855
4856bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4857{
4858 Mutex::Autolock _l(mLock);
4859 return waitingAsyncCallback_l();
4860}
4861
Eric Laurent81784c32012-11-19 14:55:58 -08004862// shared by MIXER and DIRECT, overridden by DUPLICATING
4863void AudioFlinger::PlaybackThread::threadLoop_standby()
4864{
4865 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004866 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004867 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004868 // discard any pending drain or write ack by incrementing sequence
4869 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4870 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004871 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004872 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4873 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004874 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004875 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004876}
4877
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004878void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4879{
4880 ALOGV("signal playback thread");
4881 broadcast_l();
4882}
4883
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004884void AudioFlinger::PlaybackThread::onAsyncError()
4885{
4886 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4887 invalidateTracks((audio_stream_type_t)i);
4888 }
4889}
4890
Eric Laurent81784c32012-11-19 14:55:58 -08004891void AudioFlinger::MixerThread::threadLoop_mix()
4892{
Eric Laurent81784c32012-11-19 14:55:58 -08004893 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004894 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004895 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004896 // increase sleep time progressively when application underrun condition clears.
4897 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4898 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4899 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004900 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004901 sleepTimeShift--;
4902 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004903 mSleepTimeUs = 0;
4904 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004905 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004906
Eric Laurent81784c32012-11-19 14:55:58 -08004907}
4908
4909void AudioFlinger::MixerThread::threadLoop_sleepTime()
4910{
4911 // If no tracks are ready, sleep once for the duration of an output
4912 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004913 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004914 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004915 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4916 // Using the Monopipe availableToWrite, we estimate the
4917 // sleep time to retry for more data (before we underrun).
4918 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4919 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4920 const size_t pipeFrames = monoPipe->maxFrames();
4921 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4922 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4923 const size_t framesDelay = std::min(
4924 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4925 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4926 pipeFrames, framesLeft, framesDelay);
4927 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4928 } else {
4929 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4930 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4931 mSleepTimeUs = kMinThreadSleepTimeUs;
4932 }
4933 // reduce sleep time in case of consecutive application underruns to avoid
4934 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4935 // duration we would end up writing less data than needed by the audio HAL if
4936 // the condition persists.
4937 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4938 sleepTimeShift++;
4939 }
Eric Laurent81784c32012-11-19 14:55:58 -08004940 }
4941 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004942 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004943 }
4944 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004945 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4946 // before effects processing or output.
4947 if (mMixerBufferValid) {
4948 memset(mMixerBuffer, 0, mMixerBufferSize);
4949 } else {
4950 memset(mSinkBuffer, 0, mSinkBufferSize);
4951 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004952 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004953 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4954 "anticipated start");
4955 }
4956 // TODO add standby time extension fct of effect tail
4957}
4958
4959// prepareTracks_l() must be called with ThreadBase::mLock held
4960AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4961 Vector< sp<Track> > *tracksToRemove)
4962{
Andy Hungc0691382018-09-12 18:01:57 -07004963 // clean up deleted track ids in AudioMixer before allocating new tracks
4964 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4965 // for each trackId, destroy it in the AudioMixer
4966 if (mAudioMixer->exists(trackId)) {
4967 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004968 }
4969 });
Andy Hungc0691382018-09-12 18:01:57 -07004970 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004971
4972 mixer_state mixerStatus = MIXER_IDLE;
4973 // find out which tracks need to be processed
4974 size_t count = mActiveTracks.size();
4975 size_t mixedTracks = 0;
4976 size_t tracksWithEffect = 0;
4977 // counts only _active_ fast tracks
4978 size_t fastTracks = 0;
4979 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4980
4981 float masterVolume = mMasterVolume;
4982 bool masterMute = mMasterMute;
4983
4984 if (masterMute) {
4985 masterVolume = 0;
4986 }
4987 // Delegate master volume control to effect in output mix effect chain if needed
4988 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4989 if (chain != 0) {
4990 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4991 chain->setVolume_l(&v, &v);
4992 masterVolume = (float)((v + (1 << 23)) >> 24);
4993 chain.clear();
4994 }
4995
4996 // prepare a new state to push
4997 FastMixerStateQueue *sq = NULL;
4998 FastMixerState *state = NULL;
4999 bool didModify = false;
5000 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005001 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005002 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005003 sq = mFastMixer->sq();
5004 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005005 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005006 }
5007
Andy Hung69aed5f2014-02-25 17:24:40 -08005008 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005009 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005010
Andy Hungbd3b2b02018-05-21 10:53:11 -07005011 // DeferredOperations handles statistics after setting mixerStatus.
5012 class DeferredOperations {
5013 public:
Andy Hungea840382020-05-05 21:50:17 -07005014 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5015 : mMixerStatus(mixerStatus)
5016 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005017
5018 // when leaving scope, tally frames properly.
5019 ~DeferredOperations() {
5020 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5021 // because that is when the underrun occurs.
5022 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005023 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005024 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005025 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005026 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005027 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005028 }
5029 }
Andy Hungea840382020-05-05 21:50:17 -07005030 // send the max underrun frames for this mixer period
5031 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005032 }
5033
5034 // tallyUnderrunFrames() is called to update the track counters
5035 // with the number of underrun frames for a particular mixer period.
5036 // We defer tallying until we know the final mixer status.
5037 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
5038 mUnderrunFrames.emplace_back(track, underrunFrames);
5039 }
5040
5041 private:
5042 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005043 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07005044 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005045 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005046 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005047
jiabin245cdd92018-12-07 17:55:15 -08005048 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005049 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07005050 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005051
5052 // this const just means the local variable doesn't change
5053 Track* const track = t.get();
5054
5055 // process fast tracks
5056 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005057 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5058 "%s(%d): FastTrack(%d) present without FastMixer",
5059 __func__, id(), track->id());
5060
jiabin245cdd92018-12-07 17:55:15 -08005061 if (track->getHapticPlaybackEnabled()) {
5062 noFastHapticTrack = false;
5063 }
Eric Laurent81784c32012-11-19 14:55:58 -08005064
5065 // It's theoretically possible (though unlikely) for a fast track to be created
5066 // and then removed within the same normal mix cycle. This is not a problem, as
5067 // the track never becomes active so it's fast mixer slot is never touched.
5068 // The converse, of removing an (active) track and then creating a new track
5069 // at the identical fast mixer slot within the same normal mix cycle,
5070 // is impossible because the slot isn't marked available until the end of each cycle.
5071 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005072 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005073 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5074 FastTrack *fastTrack = &state->mFastTracks[j];
5075
5076 // Determine whether the track is currently in underrun condition,
5077 // and whether it had a recent underrun.
5078 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5079 FastTrackUnderruns underruns = ftDump->mUnderruns;
5080 uint32_t recentFull = (underruns.mBitFields.mFull -
5081 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
5082 uint32_t recentPartial = (underruns.mBitFields.mPartial -
5083 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
5084 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
5085 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
5086 uint32_t recentUnderruns = recentPartial + recentEmpty;
5087 track->mObservedUnderruns = underruns;
5088 // don't count underruns that occur while stopping or pausing
5089 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005090 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005091 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5092 recentUnderruns > 0) {
5093 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005094 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005095 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005096 // Immediately account for FastTrack underruns.
5097 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005098
5099 // This is similar to the state machine for normal tracks,
5100 // with a few modifications for fast tracks.
5101 bool isActive = true;
5102 switch (track->mState) {
5103 case TrackBase::STOPPING_1:
5104 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005105 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005106 track->mState = TrackBase::STOPPING_2;
5107 }
5108 break;
5109 case TrackBase::PAUSING:
5110 // ramp down is not yet implemented
5111 track->setPaused();
5112 break;
5113 case TrackBase::RESUMING:
5114 // ramp up is not yet implemented
5115 track->mState = TrackBase::ACTIVE;
5116 break;
5117 case TrackBase::ACTIVE:
5118 if (recentFull > 0 || recentPartial > 0) {
5119 // track has provided at least some frames recently: reset retry count
5120 track->mRetryCount = kMaxTrackRetries;
5121 }
5122 if (recentUnderruns == 0) {
5123 // no recent underruns: stay active
5124 break;
5125 }
5126 // there has recently been an underrun of some kind
5127 if (track->sharedBuffer() == 0) {
5128 // were any of the recent underruns "empty" (no frames available)?
5129 if (recentEmpty == 0) {
5130 // no, then ignore the partial underruns as they are allowed indefinitely
5131 break;
5132 }
5133 // there has recently been an "empty" underrun: decrement the retry counter
5134 if (--(track->mRetryCount) > 0) {
5135 break;
5136 }
5137 // indicate to client process that the track was disabled because of underrun;
5138 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005139 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005140 // remove from active list, but state remains ACTIVE [confusing but true]
5141 isActive = false;
5142 break;
5143 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005144 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005145 case TrackBase::STOPPING_2:
5146 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005147 case TrackBase::STOPPED:
5148 case TrackBase::FLUSHED: // flush() while active
5149 // Check for presentation complete if track is inactive
5150 // We have consumed all the buffers of this track.
5151 // This would be incomplete if we auto-paused on underrun
5152 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005153 uint32_t latency = 0;
5154 status_t result = mOutput->stream->getLatency(&latency);
5155 ALOGE_IF(result != OK,
5156 "Error when retrieving output stream latency: %d", result);
5157 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005158 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005159 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5160 // track stays in active list until presentation is complete
5161 break;
5162 }
5163 }
5164 if (track->isStopping_2()) {
5165 track->mState = TrackBase::STOPPED;
5166 }
5167 if (track->isStopped()) {
5168 // Can't reset directly, as fast mixer is still polling this track
5169 // track->reset();
5170 // So instead mark this track as needing to be reset after push with ack
5171 resetMask |= 1 << i;
5172 }
5173 isActive = false;
5174 break;
5175 case TrackBase::IDLE:
5176 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005177 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005178 }
5179
5180 if (isActive) {
5181 // was it previously inactive?
5182 if (!(state->mTrackMask & (1 << j))) {
5183 ExtendedAudioBufferProvider *eabp = track;
5184 VolumeProvider *vp = track;
5185 fastTrack->mBufferProvider = eabp;
5186 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005187 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005188 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005189 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005190 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005191 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005192 fastTrack->mGeneration++;
5193 state->mTrackMask |= 1 << j;
5194 didModify = true;
5195 // no acknowledgement required for newly active tracks
5196 }
Kevin Rocard12381092018-04-11 09:19:59 -07005197 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005198 float volume;
5199 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5200 volume = 0.f;
5201 } else {
5202 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5203 }
5204
5205 handleVoipVolume_l(&volume);
5206
Eric Laurent81784c32012-11-19 14:55:58 -08005207 // cache the combined master volume and stream type volume for fast mixer; this
5208 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005209 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005210 proxy->framesReleased()).first;
5211 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005212 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005213 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5214 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5215 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005216
Kevin Rocard12381092018-04-11 09:19:59 -07005217 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005218 ++fastTracks;
5219 } else {
5220 // was it previously active?
5221 if (state->mTrackMask & (1 << j)) {
5222 fastTrack->mBufferProvider = NULL;
5223 fastTrack->mGeneration++;
5224 state->mTrackMask &= ~(1 << j);
5225 didModify = true;
5226 // If any fast tracks were removed, we must wait for acknowledgement
5227 // because we're about to decrement the last sp<> on those tracks.
5228 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5229 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005230 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5231 // AudioTrack may start (which may not be with a start() but with a write()
5232 // after underrun) and immediately paused or released. In that case the
5233 // FastTrack state hasn't had time to update.
5234 // TODO Remove the ALOGW when this theory is confirmed.
5235 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005236 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
5237 j, track->mState, state->mTrackMask, recentUnderruns,
5238 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005239 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005240 }
5241 tracksToRemove->add(track);
5242 // Avoids a misleading display in dumpsys
5243 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5244 }
jiabin245cdd92018-12-07 17:55:15 -08005245 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5246 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5247 didModify = true;
5248 }
Eric Laurent81784c32012-11-19 14:55:58 -08005249 continue;
5250 }
5251
5252 { // local variable scope to avoid goto warning
5253
5254 audio_track_cblk_t* cblk = track->cblk();
5255
5256 // The first time a track is added we wait
5257 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005258 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005259
5260 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005261 // use the trackId as the AudioMixer name.
5262 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005263 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005264 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005265 track->mChannelMask,
5266 track->mFormat,
5267 track->mSessionId);
5268 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005269 ALOGW("%s(): AudioMixer cannot create track(%d)"
5270 " mask %#x, format %#x, sessionId %d",
5271 __func__, trackId,
5272 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005273 tracksToRemove->add(track);
5274 track->invalidate(); // consider it dead.
5275 continue;
5276 }
5277 }
5278
Eric Laurent81784c32012-11-19 14:55:58 -08005279 // make sure that we have enough frames to mix one full buffer.
5280 // enforce this condition only once to enable draining the buffer in case the client
5281 // app does not call stop() and relies on underrun to stop:
5282 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5283 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005284 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005285 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005286 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005287
5288 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005289 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005290 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5291 // add frames already consumed but not yet released by the resampler
5292 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005293 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005294
Eric Laurent81784c32012-11-19 14:55:58 -08005295 uint32_t minFrames = 1;
5296 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5297 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005298 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005299 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005300
5301 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005302 if (ATRACE_ENABLED()) {
5303 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005304 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005305 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005306 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005307 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005308 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005309 !track->isPaused() && !track->isTerminated())
5310 {
Andy Hungc0691382018-09-12 18:01:57 -07005311 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005312
5313 mixedTracks++;
5314
Andy Hung69aed5f2014-02-25 17:24:40 -08005315 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5316 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005317 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005318 if (track->mainBuffer() != mSinkBuffer &&
5319 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005320 if (mEffectBufferEnabled) {
5321 mEffectBufferValid = true; // Later can set directly.
5322 }
Eric Laurent81784c32012-11-19 14:55:58 -08005323 chain = getEffectChain_l(track->sessionId());
5324 // Delegate volume control to effect in track effect chain if needed
5325 if (chain != 0) {
5326 tracksWithEffect++;
5327 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005328 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005329 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005330 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005331 }
5332 }
5333
5334
5335 int param = AudioMixer::VOLUME;
5336 if (track->mFillingUpStatus == Track::FS_FILLED) {
5337 // no ramp for the first volume setting
5338 track->mFillingUpStatus = Track::FS_ACTIVE;
5339 if (track->mState == TrackBase::RESUMING) {
5340 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005341 // If a new track is paused immediately after start, do not ramp on resume.
5342 if (cblk->mServer != 0) {
5343 param = AudioMixer::RAMP_VOLUME;
5344 }
Eric Laurent81784c32012-11-19 14:55:58 -08005345 }
Andy Hungc0691382018-09-12 18:01:57 -07005346 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005347 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005348 // FIXME should not make a decision based on mServer
5349 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005350 // If the track is stopped before the first frame was mixed,
5351 // do not apply ramp
5352 param = AudioMixer::RAMP_VOLUME;
5353 }
5354
5355 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005356 uint32_t vl, vr; // in U8.24 integer format
5357 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005358 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005359 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005360 // Always fetch volumeshaper volume to ensure state is updated.
5361 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5362 const float vh = track->getVolumeHandler()->getVolume(
5363 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005364
Eric Laurenteab90452019-06-24 15:17:46 -07005365 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5366 v = 0;
5367 }
5368
5369 handleVoipVolume_l(&v);
5370
5371 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005372 vl = vr = 0;
5373 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005374 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005375 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005376 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005377 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5378 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005379 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005380 if (vlf > GAIN_FLOAT_UNITY) {
5381 ALOGV("Track left volume out of range: %.3g", vlf);
5382 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005383 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005384 if (vrf > GAIN_FLOAT_UNITY) {
5385 ALOGV("Track right volume out of range: %.3g", vrf);
5386 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005387 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005388 // now apply the master volume and stream type volume and shaper volume
5389 vlf *= v * vh;
5390 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005391 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005392 // then derive vl and vr as U8.24 versions for the effect chain
5393 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5394 vl = (uint32_t) (scaleto8_24 * vlf);
5395 vr = (uint32_t) (scaleto8_24 * vrf);
5396 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005397 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005398 // send level comes from shared memory and so may be corrupt
5399 if (sendLevel > MAX_GAIN_INT) {
5400 ALOGV("Track send level out of range: %04X", sendLevel);
5401 sendLevel = MAX_GAIN_INT;
5402 }
Andy Hung6be49402014-05-30 10:42:03 -07005403 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5404 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005405 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005406
Kevin Rocard12381092018-04-11 09:19:59 -07005407 track->setFinalVolume((vrf + vlf) / 2.f);
5408
Eric Laurent81784c32012-11-19 14:55:58 -08005409 // Delegate volume control to effect in track effect chain if needed
5410 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5411 // Do not ramp volume if volume is controlled by effect
5412 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005413 // Update remaining floating point volume levels
5414 vlf = (float)vl / (1 << 24);
5415 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005416 track->mHasVolumeController = true;
5417 } else {
5418 // force no volume ramp when volume controller was just disabled or removed
5419 // from effect chain to avoid volume spike
5420 if (track->mHasVolumeController) {
5421 param = AudioMixer::VOLUME;
5422 }
5423 track->mHasVolumeController = false;
5424 }
5425
Eric Laurent81784c32012-11-19 14:55:58 -08005426 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005427 mAudioMixer->setBufferProvider(trackId, track);
5428 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005429
Andy Hungc0691382018-09-12 18:01:57 -07005430 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5431 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5432 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005433 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005434 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005435 AudioMixer::TRACK,
5436 AudioMixer::FORMAT, (void *)track->format());
5437 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005438 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005439 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005440 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07005441 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005442 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07005443 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08005444 AudioMixer::MIXER_CHANNEL_MASK,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005445 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08005446 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005447 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005448 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005449 if (reqSampleRate == 0) {
5450 reqSampleRate = mSampleRate;
5451 } else if (reqSampleRate > maxSampleRate) {
5452 reqSampleRate = maxSampleRate;
5453 }
Eric Laurent81784c32012-11-19 14:55:58 -08005454 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005455 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005456 AudioMixer::RESAMPLE,
5457 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005458 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005459
Andy Hung333ab962019-05-28 20:23:35 -07005460 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005461 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005462 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005463 AudioMixer::TIMESTRETCH,
5464 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005465 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005466
Andy Hung69aed5f2014-02-25 17:24:40 -08005467 /*
5468 * Select the appropriate output buffer for the track.
5469 *
Andy Hung98ef9782014-03-04 14:46:50 -08005470 * Tracks with effects go into their own effects chain buffer
5471 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005472 *
5473 * Other tracks can use mMixerBuffer for higher precision
5474 * channel accumulation. If this buffer is enabled
5475 * (mMixerBufferEnabled true), then selected tracks will accumulate
5476 * into it.
5477 *
5478 */
5479 if (mMixerBufferEnabled
5480 && (track->mainBuffer() == mSinkBuffer
5481 || track->mainBuffer() == mMixerBuffer)) {
5482 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005483 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005484 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08005485 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08005486 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005487 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005488 AudioMixer::TRACK,
5489 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5490 // TODO: override track->mainBuffer()?
5491 mMixerBufferValid = true;
5492 } else {
5493 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005494 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005495 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005496 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005497 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005498 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005499 AudioMixer::TRACK,
5500 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5501 }
Eric Laurent81784c32012-11-19 14:55:58 -08005502 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005503 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005504 AudioMixer::TRACK,
5505 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005506 mAudioMixer->setParameter(
5507 trackId,
5508 AudioMixer::TRACK,
5509 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005510 mAudioMixer->setParameter(
5511 trackId,
5512 AudioMixer::TRACK,
5513 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Lais Andradebc3f37a2021-07-02 00:13:19 +01005514 mAudioMixer->setParameter(
5515 trackId,
5516 AudioMixer::TRACK,
5517 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)(&(track->mHapticMaxAmplitude)));
Eric Laurent81784c32012-11-19 14:55:58 -08005518
5519 // reset retry count
5520 track->mRetryCount = kMaxTrackRetries;
5521
5522 // If one track is ready, set the mixer ready if:
5523 // - the mixer was not ready during previous round OR
5524 // - no other track is not ready
5525 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5526 mixerStatus != MIXER_TRACKS_ENABLED) {
5527 mixerStatus = MIXER_TRACKS_READY;
5528 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005529
5530 // Enable the next few lines to instrument a test for underrun log handling.
5531 // TODO: Remove when we have a better way of testing the underrun log.
5532#if 0
5533 static int i;
5534 if ((++i & 0xf) == 0) {
5535 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5536 }
5537#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005538 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005539 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005540 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005541 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5542 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005543 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005544 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005545 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005546
Eric Laurent81784c32012-11-19 14:55:58 -08005547 // clear effect chain input buffer if an active track underruns to avoid sending
5548 // previous audio buffer again to effects
5549 chain = getEffectChain_l(track->sessionId());
5550 if (chain != 0) {
5551 chain->clearInputBuffer();
5552 }
5553
Andy Hungc0691382018-09-12 18:01:57 -07005554 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005555 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5556 track->isStopped() || track->isPaused()) {
5557 // We have consumed all the buffers of this track.
5558 // Remove it from the list of active tracks.
5559 // TODO: use actual buffer filling status instead of latency when available from
5560 // audio HAL
5561 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005562 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005563 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5564 if (track->isStopped()) {
5565 track->reset();
5566 }
5567 tracksToRemove->add(track);
5568 }
5569 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005570 // No buffers for this track. Give it a few chances to
5571 // fill a buffer, then remove it from active list.
5572 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005573 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5574 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005575 tracksToRemove->add(track);
5576 // indicate to client process that the track was disabled because of underrun;
5577 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005578 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005579 // If one track is not ready, mark the mixer also not ready if:
5580 // - the mixer was ready during previous round OR
5581 // - no other track is ready
5582 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5583 mixerStatus != MIXER_TRACKS_READY) {
5584 mixerStatus = MIXER_TRACKS_ENABLED;
5585 }
5586 }
Andy Hungc0691382018-09-12 18:01:57 -07005587 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005588 }
5589
5590 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005591
5592 }
5593
jiabin245cdd92018-12-07 17:55:15 -08005594 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5595 // When there is no fast track playing haptic and FastMixer exists,
5596 // enabling the first FastTrack, which provides mixed data from normal
5597 // tracks, to play haptic data.
5598 FastTrack *fastTrack = &state->mFastTracks[0];
5599 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5600 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5601 didModify = true;
5602 }
5603 }
5604
Eric Laurent81784c32012-11-19 14:55:58 -08005605 // Push the new FastMixer state if necessary
5606 bool pauseAudioWatchdog = false;
5607 if (didModify) {
5608 state->mFastTracksGen++;
5609 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5610 if (kUseFastMixer == FastMixer_Dynamic &&
5611 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5612 state->mCommand = FastMixerState::COLD_IDLE;
5613 state->mColdFutexAddr = &mFastMixerFutex;
5614 state->mColdGen++;
5615 mFastMixerFutex = 0;
5616 if (kUseFastMixer == FastMixer_Dynamic) {
5617 mNormalSink = mOutputSink;
5618 }
5619 // If we go into cold idle, need to wait for acknowledgement
5620 // so that fast mixer stops doing I/O.
5621 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5622 pauseAudioWatchdog = true;
5623 }
Eric Laurent81784c32012-11-19 14:55:58 -08005624 }
5625 if (sq != NULL) {
5626 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005627 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5628 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5629 // when bringing the output sink into standby.)
5630 //
5631 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5632 //
5633 // This occurs with BT suspend when we idle the FastMixer with
5634 // active tracks, which may be added or removed.
5635 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005636 }
5637#ifdef AUDIO_WATCHDOG
5638 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5639 mAudioWatchdog->pause();
5640 }
5641#endif
5642
5643 // Now perform the deferred reset on fast tracks that have stopped
5644 while (resetMask != 0) {
5645 size_t i = __builtin_ctz(resetMask);
5646 ALOG_ASSERT(i < count);
5647 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005648 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005649 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5650 track->reset();
5651 }
5652
Andy Hung80d03d22018-04-10 10:32:11 -07005653 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5654 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5655 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5656 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5657 // See also the implementation of destroyTrack_l().
5658 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005659 const int trackId = track->id();
5660 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5661 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005662 }
5663 }
5664
Eric Laurent81784c32012-11-19 14:55:58 -08005665 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005666 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005667
Eric Laurentb3f315a2021-07-13 15:09:05 +02005668 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
5669 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07005670 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005671 }
5672
5673 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005674 // as long as there are effects we should clear the effects buffer, to avoid
5675 // passing a non-clean buffer to the effect chain
5676 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005677 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005678 // sink or mix buffer must be cleared if all tracks are connected to an
5679 // effect chain as in this case the mixer will not write to the sink or mix buffer
5680 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005681 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5682 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005683 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005684 if (mMixerBufferValid) {
5685 memset(mMixerBuffer, 0, mMixerBufferSize);
5686 // TODO: In testing, mSinkBuffer below need not be cleared because
5687 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5688 // after mixing.
5689 //
5690 // To enforce this guarantee:
5691 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5692 // (mixedTracks == 0 && fastTracks > 0))
5693 // must imply MIXER_TRACKS_READY.
5694 // Later, we may clear buffers regardless, and skip much of this logic.
5695 }
Andy Hung98ef9782014-03-04 14:46:50 -08005696 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005697 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005698 }
5699
5700 // if any fast tracks, then status is ready
5701 mMixerStatusIgnoringFastTracks = mixerStatus;
5702 if (fastTracks > 0) {
5703 mixerStatus = MIXER_TRACKS_READY;
5704 }
5705 return mixerStatus;
5706}
5707
Eric Laurentad7dd962016-09-22 12:38:37 -07005708// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005709uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005710{
5711 uint32_t trackCount = 0;
5712 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005713 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005714 trackCount++;
5715 }
5716 }
5717 return trackCount;
5718}
5719
Andy Hung1bc088a2018-02-09 15:57:31 -08005720// isTrackAllowed_l() must be called with ThreadBase::mLock held
5721bool AudioFlinger::MixerThread::isTrackAllowed_l(
5722 audio_channel_mask_t channelMask, audio_format_t format,
5723 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005724{
Andy Hung1bc088a2018-02-09 15:57:31 -08005725 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5726 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005727 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005728 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005729 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005730 ALOGW("%s: invalid format: %#x", __func__, format);
5731 return false;
5732 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005733 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005734 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5735 return false;
5736 }
5737 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005738}
5739
Eric Laurent10351942014-05-08 18:49:52 -07005740// checkForNewParameter_l() must be called with ThreadBase::mLock held
5741bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5742 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005743{
Eric Laurent81784c32012-11-19 14:55:58 -08005744 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07005745 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005746
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005747 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005748
Eric Laurent10351942014-05-08 18:49:52 -07005749 AudioParameter param = AudioParameter(keyValuePair);
5750 int value;
5751 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5752 reconfig = true;
5753 }
5754 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005755 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005756 status = BAD_VALUE;
5757 } else {
5758 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005759 reconfig = true;
5760 }
Eric Laurent10351942014-05-08 18:49:52 -07005761 }
5762 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005763 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005764 status = BAD_VALUE;
5765 } else {
5766 // no need to save value, since it's constant
5767 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005768 }
Eric Laurent10351942014-05-08 18:49:52 -07005769 }
5770 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5771 // do not accept frame count changes if tracks are open as the track buffer
5772 // size depends on frame count and correct behavior would not be guaranteed
5773 // if frame count is changed after track creation
5774 if (!mTracks.isEmpty()) {
5775 status = INVALID_OPERATION;
5776 } else {
5777 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005778 }
Eric Laurent10351942014-05-08 18:49:52 -07005779 }
5780 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005781 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005782 }
Eric Laurent81784c32012-11-19 14:55:58 -08005783
Eric Laurent10351942014-05-08 18:49:52 -07005784 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005785 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005786 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005787 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07005788 if (!mStandby) {
5789 mThreadMetrics.logEndInterval();
5790 mStandby = true;
5791 }
Eric Laurent10351942014-05-08 18:49:52 -07005792 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005793 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005794 }
Eric Laurent10351942014-05-08 18:49:52 -07005795 if (status == NO_ERROR && reconfig) {
5796 readOutputParameters_l();
5797 delete mAudioMixer;
5798 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005799 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005800 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005801 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005802 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005803 track->mChannelMask,
5804 track->mFormat,
5805 track->mSessionId);
5806 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005807 "%s(): AudioMixer cannot create track(%d)"
5808 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005809 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005810 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005811 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005812 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005813 }
Eric Laurent81784c32012-11-19 14:55:58 -08005814 }
5815
Dean Wheatley68918102021-03-19 22:09:19 +11005816 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08005817}
5818
5819
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005820void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005821{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005822 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005823 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005824 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005825 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005826 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5827 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5828 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005829 if (hasFastMixer()) {
5830 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5831
5832 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5833 // while we are dumping it. It may be inconsistent, but it won't mutate!
5834 // This is a large object so we place it on the heap.
5835 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005836 const std::unique_ptr<FastMixerDumpState> copy =
5837 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005838 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005839
5840#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005841 // Similar for state queue
5842 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5843 observerCopy.dump(fd);
5844 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5845 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005846#endif
5847
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005848#ifdef AUDIO_WATCHDOG
5849 if (mAudioWatchdog != 0) {
5850 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5851 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5852 wdCopy.dump(fd);
5853 }
5854#endif
5855
5856 } else {
5857 dprintf(fd, " No FastMixer\n");
5858 }
Eric Laurent81784c32012-11-19 14:55:58 -08005859}
5860
5861uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5862{
5863 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5864}
5865
5866uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5867{
5868 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5869}
5870
5871void AudioFlinger::MixerThread::cacheParameters_l()
5872{
5873 PlaybackThread::cacheParameters_l();
5874
5875 // FIXME: Relaxed timing because of a certain device that can't meet latency
5876 // Should be reduced to 2x after the vendor fixes the driver issue
5877 // increase threshold again due to low power audio mode. The way this warning
5878 // threshold is calculated and its usefulness should be reconsidered anyway.
5879 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5880}
5881
5882// ----------------------------------------------------------------------------
5883
5884AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07005885 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5886 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005887{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005888 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005889}
5890
Eric Laurent81784c32012-11-19 14:55:58 -08005891AudioFlinger::DirectOutputThread::~DirectOutputThread()
5892{
5893}
5894
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005895void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005896{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005897 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005898 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5899 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5900}
5901
5902void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5903{
5904 Mutex::Autolock _l(mLock);
5905 if (mMasterBalance != balance) {
5906 mMasterBalance.store(balance);
5907 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5908 broadcast_l();
5909 }
5910}
5911
Eric Laurent5850c4c2016-11-10 13:04:31 -08005912void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005913{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005914 float left, right;
5915
Andy Hung333ab962019-05-28 20:23:35 -07005916 // Ensure volumeshaper state always advances even when muted.
5917 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5918 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5919 proxy->framesReleased());
5920 mVolumeShaperActive = shaperActive;
5921
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005922 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005923 left = right = 0;
5924 } else {
5925 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005926 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005927
Glenn Kastenc56f3422014-03-21 17:53:17 -07005928 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5929 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5930 if (left > GAIN_FLOAT_UNITY) {
5931 left = GAIN_FLOAT_UNITY;
5932 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005933 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005934 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5935 if (right > GAIN_FLOAT_UNITY) {
5936 right = GAIN_FLOAT_UNITY;
5937 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005938 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005939 }
5940
5941 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005942 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005943 if (left != mLeftVolFloat || right != mRightVolFloat) {
5944 mLeftVolFloat = left;
5945 mRightVolFloat = right;
5946
Eric Laurentbfb1b832013-01-07 09:53:42 -08005947 // Delegate volume control to effect in track effect chain if needed
5948 // only one effect chain can be present on DirectOutputThread, so if
5949 // there is one, the track is connected to it
5950 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005951 // if effect chain exists, volume is handled by it.
5952 // Convert volumes from float to 8.24
5953 uint32_t vl = (uint32_t)(left * (1 << 24));
5954 uint32_t vr = (uint32_t)(right * (1 << 24));
5955 // Direct/Offload effect chains set output volume in setVolume_l().
5956 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5957 } else {
5958 // otherwise we directly set the volume.
5959 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005960 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005961 }
5962 }
5963}
5964
Phil Burk43b4dcc2015-06-09 16:53:44 -07005965void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5966{
5967 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005968 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005969
Eric Laurent0f0631e2015-07-06 18:01:25 -07005970 if (previousTrack != 0 && latestTrack != 0) {
5971 if (mType == DIRECT) {
5972 if (previousTrack.get() != latestTrack.get()) {
5973 mFlushPending = true;
5974 }
5975 } else /* mType == OFFLOAD */ {
5976 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5977 mFlushPending = true;
5978 }
5979 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005980 } else if (previousTrack == 0) {
5981 // there could be an old track added back during track transition for direct
5982 // output, so always issues flush to flush data of the previous track if it
5983 // was already destroyed with HAL paused, then flush can resume the playback
5984 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005985 }
5986 PlaybackThread::onAddNewTrack_l();
5987}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005988
Eric Laurent81784c32012-11-19 14:55:58 -08005989AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5990 Vector< sp<Track> > *tracksToRemove
5991)
5992{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005993 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005994 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005995 bool doHwPause = false;
5996 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005997
5998 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005999 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006000 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006001 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006002 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006003 continue;
6004 }
6005
Eric Laurent5850c4c2016-11-10 13:04:31 -08006006 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006007#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006008 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006009#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006010 // Only consider last track started for volume and mixer state control.
6011 // In theory an older track could underrun and restart after the new one starts
6012 // but as we only care about the transition phase between two tracks on a
6013 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006014 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006015 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006016
Kuowei Li23666472021-01-20 10:23:25 +08006017 if (track->isPausePending()) {
6018 track->pauseAck();
6019 // It is possible a track might have been flushed or stopped.
6020 // Other operations such as flush pending might occur on the next prepare.
6021 if (track->isPausing()) {
6022 track->setPaused();
6023 }
6024 // Always perform pause, as an immediate flush will change
6025 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006026 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006027 doHwPause = true;
6028 mHwPaused = true;
6029 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006030 } else if (track->isFlushPending()) {
6031 track->flushAck();
6032 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006033 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006034 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006035 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006036 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006037 if (last) {
6038 mLeftVolFloat = mRightVolFloat = -1.0;
6039 if (mHwPaused) {
6040 doHwResume = true;
6041 mHwPaused = false;
6042 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006043 }
6044 }
6045
Eric Laurent81784c32012-11-19 14:55:58 -08006046 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006047 // for all its buffers to be filled before processing it.
6048 // Allow draining the buffer in case the client
6049 // app does not call stop() and relies on underrun to stop:
6050 // hence the test on (track->mRetryCount > 1).
Andy Hung455982f2021-04-27 17:46:12 -07006051 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
6052 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6053 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006054 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006055
6056 // target retry count that we will use is based on the time we wait for retries.
6057 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6058 // the retry threshold is when we accept any size for PCM data. This is slightly
6059 // smaller than the retry count so we can push small bits of data without a glitch.
6060 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006061 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006062 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung455982f2021-04-27 17:46:12 -07006063 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006064 minFrames = mNormalFrameCount;
6065 } else {
6066 minFrames = 1;
6067 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006068
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006069 const size_t framesReady = track->framesReady();
6070 const int trackId = track->id();
6071 if (ATRACE_ENABLED()) {
6072 std::string traceName("nRdy");
6073 traceName += std::to_string(trackId);
6074 ATRACE_INT(traceName.c_str(), framesReady);
6075 }
6076 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006077 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006078 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006079 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006080
6081 if (track->mFillingUpStatus == Track::FS_FILLED) {
6082 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006083 if (last) {
6084 // make sure processVolume_l() will apply new volume even if 0
6085 mLeftVolFloat = mRightVolFloat = -1.0;
6086 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006087 if (!mHwSupportsPause) {
6088 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006089 }
6090 }
6091
6092 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006093 processVolume_l(track, last);
6094 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006095 sp<Track> previousTrack = mPreviousTrack.promote();
6096 if (previousTrack != 0) {
6097 if (track != previousTrack.get()) {
6098 // Flush any data still being written from last track
6099 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006100 // Invalidate previous track to force a seek when resuming.
6101 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006102 }
6103 }
6104 mPreviousTrack = track;
6105
Eric Laurentd595b7c2013-04-03 17:27:56 -07006106 // reset retry count
Andy Hung455982f2021-04-27 17:46:12 -07006107 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006108 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006109 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006110 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006111 doHwResume = true;
6112 mHwPaused = false;
6113 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006114 }
Eric Laurent81784c32012-11-19 14:55:58 -08006115 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006116 // clear effect chain input buffer if the last active track started underruns
6117 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006118 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006119 mEffectChains[0]->clearInputBuffer();
6120 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006121 if (track->isStopping_1()) {
6122 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07006123 if (last && mHwPaused) {
6124 doHwResume = true;
6125 mHwPaused = false;
6126 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006127 }
6128 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6129 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006130 // We have consumed all the buffers of this track.
6131 // Remove it from the list of active tracks.
Eric Laurentfd477972013-10-25 18:10:40 -07006132 if (mStandby || !last ||
Andy Hung59de4262021-06-14 10:53:54 -07006133 track->presentationComplete(latency_l()) ||
Jindong32dc26e2019-11-11 18:10:01 +08006134 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07006135 if (track->isStopping_2()) {
6136 track->mState = TrackBase::STOPPED;
6137 }
Eric Laurent81784c32012-11-19 14:55:58 -08006138 if (track->isStopped()) {
6139 track->reset();
6140 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006141 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006142 }
6143 } else {
6144 // No buffers for this track. Give it a few chances to
6145 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006146 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08006147 if (--(track->mRetryCount) <= 0) {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006148 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07006149 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08006150 // indicate to client process that the track was disabled because of underrun;
6151 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006152 track->disable();
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006153 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6154 // unlike mixerthread, HAL can be paused for direct output
Phil Burkca5e6142015-07-14 09:42:29 -07006155 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6156 "minFrames = %u, mFormat = %#x",
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006157 framesReady, minFrames, mFormat);
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006158 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006159 doHwPause = true;
6160 mHwPaused = true;
6161 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006162 } else if (last) {
6163 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006164 }
6165 }
6166 }
6167 }
6168
Eric Laurentd1f69b02014-12-15 14:33:13 -08006169 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006170 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006171 for (size_t i = 0; i < mTracks.size(); i++) {
6172 if (mTracks[i]->isFlushPending()) {
6173 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006174 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006175 }
6176 }
6177 }
6178
6179 // make sure the pause/flush/resume sequence is executed in the right order.
6180 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6181 // before flush and then resume HW. This can happen in case of pause/flush/resume
6182 // if resume is received before pause is executed.
6183 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006184 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006185 status_t result = mOutput->stream->pause();
6186 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006187 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006188 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006189 flushHw_l();
6190 }
6191 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006192 status_t result = mOutput->stream->resume();
6193 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006194 }
Eric Laurent81784c32012-11-19 14:55:58 -08006195 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006196 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006197
6198 return mixerStatus;
6199}
6200
6201void AudioFlinger::DirectOutputThread::threadLoop_mix()
6202{
Eric Laurent81784c32012-11-19 14:55:58 -08006203 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006204 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006205 // output audio to hardware
6206 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006207 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006208 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006209 status_t status = mActiveTrack->getNextBuffer(&buffer);
6210 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006211 // no need to pad with 0 for compressed audio
6212 if (audio_has_proportional_frames(mFormat)) {
6213 memset(curBuf, 0, frameCount * mFrameSize);
6214 }
Eric Laurent81784c32012-11-19 14:55:58 -08006215 break;
6216 }
6217 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6218 frameCount -= buffer.frameCount;
6219 curBuf += buffer.frameCount * mFrameSize;
6220 mActiveTrack->releaseBuffer(&buffer);
6221 }
Andy Hung2098f272014-02-27 14:00:06 -08006222 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006223 mSleepTimeUs = 0;
6224 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006225 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006226}
6227
6228void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6229{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006230 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006231 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006232 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006233 return;
6234 }
Andy Hung85ba3332021-04-27 17:40:26 -07006235 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6236 mSleepTimeUs = mActiveSleepTimeUs;
6237 } else {
6238 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006239 }
Andy Hung85ba3332021-04-27 17:40:26 -07006240 // Note: In S or later, we do not write zeroes for
6241 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006242}
6243
Eric Laurentd1f69b02014-12-15 14:33:13 -08006244void AudioFlinger::DirectOutputThread::threadLoop_exit()
6245{
6246 {
6247 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006248 for (size_t i = 0; i < mTracks.size(); i++) {
6249 if (mTracks[i]->isFlushPending()) {
6250 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006251 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006252 }
6253 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006254 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006255 flushHw_l();
6256 }
6257 }
6258 PlaybackThread::threadLoop_exit();
6259}
6260
6261// must be called with thread mutex locked
6262bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6263{
6264 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006265 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006266
6267 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6268 // after a timeout and we will enter standby then.
6269 if (mTracks.size() > 0) {
6270 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006271 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6272 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006273 }
6274
Eric Laurent5cff4032015-05-26 13:49:58 -07006275 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006276}
6277
Eric Laurent10351942014-05-08 18:49:52 -07006278// checkForNewParameter_l() must be called with ThreadBase::mLock held
6279bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6280 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006281{
6282 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006283 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006284
Eric Laurent10351942014-05-08 18:49:52 -07006285 AudioParameter param = AudioParameter(keyValuePair);
6286 int value;
6287 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006288 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006289 }
Eric Laurent10351942014-05-08 18:49:52 -07006290 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6291 // do not accept frame count changes if tracks are open as the track buffer
6292 // size depends on frame count and correct behavior would not be garantied
6293 // if frame count is changed after track creation
6294 if (!mTracks.isEmpty()) {
6295 status = INVALID_OPERATION;
6296 } else {
6297 reconfig = true;
6298 }
6299 }
6300 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006301 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006302 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006303 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006304 if (!mStandby) {
6305 mThreadMetrics.logEndInterval();
6306 mStandby = true;
6307 }
Eric Laurent10351942014-05-08 18:49:52 -07006308 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006309 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006310 }
6311 if (status == NO_ERROR && reconfig) {
6312 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006313 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006314 }
6315 }
6316
Dean Wheatley68918102021-03-19 22:09:19 +11006317 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006318}
6319
6320uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6321{
6322 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006323 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006324 time = PlaybackThread::activeSleepTimeUs();
6325 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006326 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006327 }
6328 return time;
6329}
6330
6331uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6332{
6333 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006334 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006335 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6336 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006337 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006338 }
6339 return time;
6340}
6341
6342uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6343{
6344 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006345 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006346 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6347 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006348 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006349 }
6350 return time;
6351}
6352
6353void AudioFlinger::DirectOutputThread::cacheParameters_l()
6354{
6355 PlaybackThread::cacheParameters_l();
6356
6357 // use shorter standby delay as on normal output to release
6358 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006359 // no delay on outputs with HW A/V sync
6360 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006361 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006362 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006363 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006364 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006365 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006366 }
Eric Laurent81784c32012-11-19 14:55:58 -08006367}
6368
Eric Laurente659ef42014-09-29 13:06:46 -07006369void AudioFlinger::DirectOutputThread::flushHw_l()
6370{
Phil Burk062e67a2015-02-11 13:40:50 -08006371 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006372 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006373 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006374 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006375 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006376}
6377
Andy Hung10cbff12017-02-21 17:30:14 -08006378int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6379 // If a VolumeShaper is active, we must wake up periodically to update volume.
6380 const int64_t NS_PER_MS = 1000000;
6381 return mVolumeShaperActive ?
6382 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6383}
6384
Eric Laurent81784c32012-11-19 14:55:58 -08006385// ----------------------------------------------------------------------------
6386
Eric Laurentbfb1b832013-01-07 09:53:42 -08006387AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006388 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006389 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006390 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006391 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006392 mDrainSequence(0),
6393 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006394{
6395}
6396
6397AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6398{
6399}
6400
6401void AudioFlinger::AsyncCallbackThread::onFirstRef()
6402{
6403 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6404}
6405
6406bool AudioFlinger::AsyncCallbackThread::threadLoop()
6407{
6408 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006409 uint32_t writeAckSequence;
6410 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006411 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006412
6413 {
6414 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006415 while (!((mWriteAckSequence & 1) ||
6416 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006417 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006418 exitPending())) {
6419 mWaitWorkCV.wait(mLock);
6420 }
6421
Eric Laurentbfb1b832013-01-07 09:53:42 -08006422 if (exitPending()) {
6423 break;
6424 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006425 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6426 mWriteAckSequence, mDrainSequence);
6427 writeAckSequence = mWriteAckSequence;
6428 mWriteAckSequence &= ~1;
6429 drainSequence = mDrainSequence;
6430 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006431 asyncError = mAsyncError;
6432 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006433 }
6434 {
Eric Laurent4de95592013-09-26 15:28:21 -07006435 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6436 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006437 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006438 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006439 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006440 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006441 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006442 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006443 if (asyncError) {
6444 playbackThread->onAsyncError();
6445 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006446 }
6447 }
6448 }
6449 return false;
6450}
6451
6452void AudioFlinger::AsyncCallbackThread::exit()
6453{
6454 ALOGV("AsyncCallbackThread::exit");
6455 Mutex::Autolock _l(mLock);
6456 requestExit();
6457 mWaitWorkCV.broadcast();
6458}
6459
Eric Laurent3b4529e2013-09-05 18:09:19 -07006460void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006461{
6462 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006463 // bit 0 is cleared
6464 mWriteAckSequence = sequence << 1;
6465}
6466
6467void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6468{
6469 Mutex::Autolock _l(mLock);
6470 // ignore unexpected callbacks
6471 if (mWriteAckSequence & 2) {
6472 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006473 mWaitWorkCV.signal();
6474 }
6475}
6476
Eric Laurent3b4529e2013-09-05 18:09:19 -07006477void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006478{
6479 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006480 // bit 0 is cleared
6481 mDrainSequence = sequence << 1;
6482}
6483
6484void AudioFlinger::AsyncCallbackThread::resetDraining()
6485{
6486 Mutex::Autolock _l(mLock);
6487 // ignore unexpected callbacks
6488 if (mDrainSequence & 2) {
6489 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006490 mWaitWorkCV.signal();
6491 }
6492}
6493
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006494void AudioFlinger::AsyncCallbackThread::setAsyncError()
6495{
6496 Mutex::Autolock _l(mLock);
6497 mAsyncError = true;
6498 mWaitWorkCV.signal();
6499}
6500
Eric Laurentbfb1b832013-01-07 09:53:42 -08006501
6502// ----------------------------------------------------------------------------
6503AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006504 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6505 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006506 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6507 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006508{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006509 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006510 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006511 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006512}
6513
Eric Laurentbfb1b832013-01-07 09:53:42 -08006514void AudioFlinger::OffloadThread::threadLoop_exit()
6515{
6516 if (mFlushPending || mHwPaused) {
6517 // If a flush is pending or track was paused, just discard buffered data
6518 flushHw_l();
6519 } else {
6520 mMixerStatus = MIXER_DRAIN_ALL;
6521 threadLoop_drain();
6522 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006523 if (mUseAsyncWrite) {
6524 ALOG_ASSERT(mCallbackThread != 0);
6525 mCallbackThread->exit();
6526 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006527 PlaybackThread::threadLoop_exit();
6528}
6529
6530AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6531 Vector< sp<Track> > *tracksToRemove
6532)
6533{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006534 size_t count = mActiveTracks.size();
6535
6536 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006537 bool doHwPause = false;
6538 bool doHwResume = false;
6539
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006540 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006541
Eric Laurentbfb1b832013-01-07 09:53:42 -08006542 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006543 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006544 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006545#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006546 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006547#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006548 // Only consider last track started for volume and mixer state control.
6549 // In theory an older track could underrun and restart after the new one starts
6550 // but as we only care about the transition phase between two tracks on a
6551 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006552 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006553 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006554
Haynes Mathew George7844f672014-01-15 12:32:55 -08006555 if (track->isInvalid()) {
6556 ALOGW("An invalidated track shouldn't be in active list");
6557 tracksToRemove->add(track);
6558 continue;
6559 }
6560
6561 if (track->mState == TrackBase::IDLE) {
6562 ALOGW("An idle track shouldn't be in active list");
6563 continue;
6564 }
6565
Kuowei Li23666472021-01-20 10:23:25 +08006566 if (track->isPausePending()) {
6567 track->pauseAck();
6568 // It is possible a track might have been flushed or stopped.
6569 // Other operations such as flush pending might occur on the next prepare.
6570 if (track->isPausing()) {
6571 track->setPaused();
6572 }
6573 // Always perform pause if last, as an immediate flush will change
6574 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006575 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006576 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006577 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006578 mHwPaused = true;
6579 }
6580 // If we were part way through writing the mixbuffer to
6581 // the HAL we must save this until we resume
6582 // BUG - this will be wrong if a different track is made active,
6583 // in that case we want to discard the pending data in the
6584 // mixbuffer and tell the client to present it again when the
6585 // track is resumed
6586 mPausedWriteLength = mCurrentWriteLength;
6587 mPausedBytesRemaining = mBytesRemaining;
6588 mBytesRemaining = 0; // stop writing
6589 }
6590 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006591 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006592 if (track->isStopping_1()) {
6593 track->mRetryCount = kMaxTrackStopRetriesOffload;
6594 } else {
6595 track->mRetryCount = kMaxTrackRetriesOffload;
6596 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006597 track->flushAck();
6598 if (last) {
6599 mFlushPending = true;
6600 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006601 } else if (track->isResumePending()){
6602 track->resumeAck();
6603 if (last) {
6604 if (mPausedBytesRemaining) {
6605 // Need to continue write that was interrupted
6606 mCurrentWriteLength = mPausedWriteLength;
6607 mBytesRemaining = mPausedBytesRemaining;
6608 mPausedBytesRemaining = 0;
6609 }
6610 if (mHwPaused) {
6611 doHwResume = true;
6612 mHwPaused = false;
6613 // threadLoop_mix() will handle the case that we need to
6614 // resume an interrupted write
6615 }
6616 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006617 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006618
Eric Laurent3df841a2016-07-15 15:15:40 -07006619 mLeftVolFloat = mRightVolFloat = -1.0;
6620
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006621 // Do not handle new data in this iteration even if track->framesReady()
6622 mixerStatus = MIXER_TRACKS_ENABLED;
6623 }
6624 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006625 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006626 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006627 if (track->mFillingUpStatus == Track::FS_FILLED) {
6628 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006629 if (last) {
6630 // make sure processVolume_l() will apply new volume even if 0
6631 mLeftVolFloat = mRightVolFloat = -1.0;
6632 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006633 }
6634
6635 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006636 sp<Track> previousTrack = mPreviousTrack.promote();
6637 if (previousTrack != 0) {
6638 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006639 // Flush any data still being written from last track
6640 mBytesRemaining = 0;
6641 if (mPausedBytesRemaining) {
6642 // Last track was paused so we also need to flush saved
6643 // mixbuffer state and invalidate track so that it will
6644 // re-submit that unwritten data when it is next resumed
6645 mPausedBytesRemaining = 0;
6646 // Invalidate is a bit drastic - would be more efficient
6647 // to have a flag to tell client that some of the
6648 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006649 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006650 }
6651 // flush data already sent to the DSP if changing audio session as audio
6652 // comes from a different source. Also invalidate previous track to force a
6653 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006654 if (previousTrack->sessionId() != track->sessionId()) {
6655 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006656 }
6657 }
6658 }
6659 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006660 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006661 if (track->isStopping_1()) {
6662 track->mRetryCount = kMaxTrackStopRetriesOffload;
6663 } else {
6664 track->mRetryCount = kMaxTrackRetriesOffload;
6665 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006666 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006667 mixerStatus = MIXER_TRACKS_READY;
6668 }
6669 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006670 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006671 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006672 if (--(track->mRetryCount) <= 0) {
6673 // Hardware buffer can hold a large amount of audio so we must
6674 // wait for all current track's data to drain before we say
6675 // that the track is stopped.
6676 if (mBytesRemaining == 0) {
6677 // Only start draining when all data in mixbuffer
6678 // has been written
6679 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6680 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6681 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6682 if (last && !mStandby) {
6683 // do not modify drain sequence if we are already draining. This happens
6684 // when resuming from pause after drain.
6685 if ((mDrainSequence & 1) == 0) {
6686 mSleepTimeUs = 0;
6687 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6688 mixerStatus = MIXER_DRAIN_TRACK;
6689 mDrainSequence += 2;
6690 }
6691 if (mHwPaused) {
6692 // It is possible to move from PAUSED to STOPPING_1 without
6693 // a resume so we must ensure hardware is running
6694 doHwResume = true;
6695 mHwPaused = false;
6696 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006697 }
6698 }
Eric Laurente93cc032016-05-05 10:15:10 -07006699 } else if (last) {
6700 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6701 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006702 }
6703 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006704 // Drain has completed or we are in standby, signal presentation complete
6705 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006706 track->mState = TrackBase::STOPPED;
Andy Hung59de4262021-06-14 10:53:54 -07006707 track->presentationComplete(latency_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006708 track->reset();
6709 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006710 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006711 if (!mUseAsyncWrite) {
6712 // If we don't get explicit drain notification we must
6713 // register discontinuity regardless of whether this is
6714 // the previous (!last) or the upcoming (last) track
6715 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006716 mTimestampVerifier.discontinuity(
6717 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006718 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006719 }
6720 } else {
6721 // No buffers for this track. Give it a few chances to
6722 // fill a buffer, then remove it from active list.
6723 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006724 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006725 uint64_t position = 0;
6726 struct timespec unused;
6727 // The running check restarts the retry counter at least once.
6728 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6729 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6730 running = true;
6731 mOffloadUnderrunPosition = position;
6732 }
6733 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006734 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6735 (long long)position, (long long)mOffloadUnderrunPosition);
6736 }
6737 if (running) { // still running, give us more time.
6738 track->mRetryCount = kMaxTrackRetriesOffload;
6739 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006740 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6741 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006742 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006743 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006744 // it will then automatically call start() when data is available
6745 track->disable();
6746 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006747 } else if (last){
6748 mixerStatus = MIXER_TRACKS_ENABLED;
6749 }
6750 }
6751 }
6752 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006753 if (track->isReady()) { // check ready to prevent premature start.
6754 processVolume_l(track, last);
6755 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006756 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006757
Eric Laurentea0fade2013-10-04 16:23:48 -07006758 // make sure the pause/flush/resume sequence is executed in the right order.
6759 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6760 // before flush and then resume HW. This can happen in case of pause/flush/resume
6761 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006762 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006763 status_t result = mOutput->stream->pause();
6764 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006765 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006766 if (mFlushPending) {
6767 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006768 }
Eric Laurentfd477972013-10-25 18:10:40 -07006769 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006770 status_t result = mOutput->stream->resume();
6771 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006772 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006773
Eric Laurentbfb1b832013-01-07 09:53:42 -08006774 // remove all the tracks that need to be...
6775 removeTracks_l(*tracksToRemove);
6776
6777 return mixerStatus;
6778}
6779
Eric Laurentbfb1b832013-01-07 09:53:42 -08006780// must be called with thread mutex locked
6781bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6782{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006783 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6784 mWriteAckSequence, mDrainSequence);
6785 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006786 return true;
6787 }
6788 return false;
6789}
6790
Eric Laurentbfb1b832013-01-07 09:53:42 -08006791bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6792{
6793 Mutex::Autolock _l(mLock);
6794 return waitingAsyncCallback_l();
6795}
6796
6797void AudioFlinger::OffloadThread::flushHw_l()
6798{
Eric Laurente659ef42014-09-29 13:06:46 -07006799 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006800 // Flush anything still waiting in the mixbuffer
6801 mCurrentWriteLength = 0;
6802 mBytesRemaining = 0;
6803 mPausedWriteLength = 0;
6804 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006805 // reset bytes written count to reflect that DSP buffers are empty after flush.
6806 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006807 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006808
Eric Laurentbfb1b832013-01-07 09:53:42 -08006809 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006810 // discard any pending drain or write ack by incrementing sequence
6811 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6812 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006813 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006814 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6815 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006816 }
6817}
6818
Haynes Mathew George05317d22016-05-03 16:34:26 -07006819void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6820{
6821 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006822 if (PlaybackThread::invalidateTracks_l(streamType)) {
6823 mFlushPending = true;
6824 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006825}
6826
Eric Laurentbfb1b832013-01-07 09:53:42 -08006827// ----------------------------------------------------------------------------
6828
Eric Laurent81784c32012-11-19 14:55:58 -08006829AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006830 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07006831 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006832 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006833 mWaitTimeMs(UINT_MAX)
6834{
6835 addOutputTrack(mainThread);
6836}
6837
6838AudioFlinger::DuplicatingThread::~DuplicatingThread()
6839{
6840 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6841 mOutputTracks[i]->destroy();
6842 }
6843}
6844
6845void AudioFlinger::DuplicatingThread::threadLoop_mix()
6846{
6847 // mix buffers...
6848 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006849 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006850 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006851 if (mMixerBufferValid) {
6852 memset(mMixerBuffer, 0, mMixerBufferSize);
6853 } else {
6854 memset(mSinkBuffer, 0, mSinkBufferSize);
6855 }
Eric Laurent81784c32012-11-19 14:55:58 -08006856 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006857 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006858 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006859 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006860 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006861}
6862
6863void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6864{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006865 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006866 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006867 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006868 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006869 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006870 }
6871 } else if (mBytesWritten != 0) {
6872 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6873 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006874 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006875 } else {
6876 // flush remaining overflow buffers in output tracks
6877 writeFrames = 0;
6878 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006879 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006880 }
6881}
6882
Eric Laurentbfb1b832013-01-07 09:53:42 -08006883ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006884{
6885 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006886 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6887
6888 // Consider the first OutputTrack for timestamp and frame counting.
6889
6890 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6891 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6892 // we always claim success.
6893 if (i == 0) {
6894 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6895 ALOGD_IF(correction != 0 && writeFrames != 0,
6896 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6897 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6898 mFramesWritten -= correction;
6899 }
6900
6901 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006902 }
Andy Hungcf10d742020-04-28 15:38:24 -07006903 if (mStandby) {
6904 mThreadMetrics.logBeginInterval();
6905 mStandby = false;
6906 }
Andy Hung25c2dac2014-02-27 14:56:00 -08006907 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006908}
6909
6910void AudioFlinger::DuplicatingThread::threadLoop_standby()
6911{
6912 // DuplicatingThread implements standby by stopping all tracks
6913 for (size_t i = 0; i < outputTracks.size(); i++) {
6914 outputTracks[i]->stop();
6915 }
6916}
6917
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006918void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006919{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006920 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006921
6922 std::stringstream ss;
6923 const size_t numTracks = mOutputTracks.size();
6924 ss << " " << numTracks << " OutputTracks";
6925 if (numTracks > 0) {
6926 ss << ":";
6927 for (const auto &track : mOutputTracks) {
6928 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006929 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006930 if (thread.get() != nullptr) {
6931 ss << thread.get() << ", " << thread->id();
6932 } else {
6933 ss << "null";
6934 }
6935 ss << ")";
6936 }
6937 }
6938 ss << "\n";
6939 std::string result = ss.str();
6940 write(fd, result.c_str(), result.size());
6941}
6942
Eric Laurent81784c32012-11-19 14:55:58 -08006943void AudioFlinger::DuplicatingThread::saveOutputTracks()
6944{
6945 outputTracks = mOutputTracks;
6946}
6947
6948void AudioFlinger::DuplicatingThread::clearOutputTracks()
6949{
6950 outputTracks.clear();
6951}
6952
6953void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6954{
6955 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006956 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6957 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6958 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6959 const size_t frameCount =
6960 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6961 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6962 // from different OutputTracks and their associated MixerThreads (e.g. one may
6963 // nearly empty and the other may be dropping data).
6964
Svet Ganov33761132021-05-13 22:51:08 +00006965 // TODO b/182392769: use attribution source util, move to server edge
6966 AttributionSourceState attributionSource = AttributionSourceState();
6967 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006968 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00006969 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006970 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00006971 attributionSource.token = sp<BBinder>::make();
Andy Hungc25b84a2015-01-14 19:04:10 -08006972 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006973 this,
6974 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006975 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006976 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006977 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00006978 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006979 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6980 if (status != NO_ERROR) {
6981 ALOGE("addOutputTrack() initCheck failed %d", status);
6982 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006983 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006984 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6985 mOutputTracks.add(outputTrack);
6986 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6987 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006988}
6989
6990void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6991{
6992 Mutex::Autolock _l(mLock);
6993 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6994 if (mOutputTracks[i]->thread() == thread) {
6995 mOutputTracks[i]->destroy();
6996 mOutputTracks.removeAt(i);
6997 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006998 if (thread->getOutput() == mOutput) {
6999 mOutput = NULL;
7000 }
Eric Laurent81784c32012-11-19 14:55:58 -08007001 return;
7002 }
7003 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007004 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007005}
7006
7007// caller must hold mLock
7008void AudioFlinger::DuplicatingThread::updateWaitTime_l()
7009{
7010 mWaitTimeMs = UINT_MAX;
7011 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7012 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
7013 if (strong != 0) {
7014 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7015 if (waitTimeMs < mWaitTimeMs) {
7016 mWaitTimeMs = waitTimeMs;
7017 }
7018 }
7019 }
7020}
7021
7022
7023bool AudioFlinger::DuplicatingThread::outputsReady(
7024 const SortedVector< sp<OutputTrack> > &outputTracks)
7025{
7026 for (size_t i = 0; i < outputTracks.size(); i++) {
7027 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
7028 if (thread == 0) {
7029 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7030 outputTracks[i].get());
7031 return false;
7032 }
7033 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
7034 // see note at standby() declaration
7035 if (playbackThread->standby() && !playbackThread->isSuspended()) {
7036 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7037 thread.get());
7038 return false;
7039 }
7040 }
7041 return true;
7042}
7043
Kevin Rocard12381092018-04-11 09:19:59 -07007044void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
7045 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007046{
Kevin Rocard12381092018-04-11 09:19:59 -07007047 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7048 outputTrack->setMetadatas(metadata.tracks);
7049 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007050}
7051
Eric Laurent81784c32012-11-19 14:55:58 -08007052uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
7053{
7054 return (mWaitTimeMs * 1000) / 2;
7055}
7056
7057void AudioFlinger::DuplicatingThread::cacheParameters_l()
7058{
7059 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7060 updateWaitTime_l();
7061
7062 MixerThread::cacheParameters_l();
7063}
7064
Eric Laurentb3f315a2021-07-13 15:09:05 +02007065// ----------------------------------------------------------------------------
7066
Eric Laurentfa0f6742021-08-17 18:39:44 +02007067AudioFlinger::SpatializerThread::SpatializerThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007068 AudioStreamOut* output,
7069 audio_io_handle_t id,
7070 bool systemReady,
7071 audio_config_base_t *mixerConfig)
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007072 : MixerThread(audioFlinger, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007073{
7074}
7075
Eric Laurentfa0f6742021-08-17 18:39:44 +02007076void AudioFlinger::SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007077{
7078 bool hasVirtualizer = false;
7079 bool hasDownMixer = false;
7080 sp<EffectHandle> finalDownMixer;
7081 {
7082 Mutex::Autolock _l(mLock);
7083 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
7084 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007085 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007086 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7087 }
7088
7089 finalDownMixer = mFinalDownMixer;
7090 mFinalDownMixer.clear();
7091 }
7092
7093 if (hasVirtualizer) {
7094 if (finalDownMixer != nullptr) {
7095 int32_t ret;
7096 finalDownMixer->disable(&ret);
7097 }
7098 finalDownMixer.clear();
7099 } else if (!hasDownMixer) {
7100 std::vector<effect_descriptor_t> descriptors;
7101 status_t status = mAudioFlinger->mEffectsFactoryHal->getDescriptors(
7102 EFFECT_UIID_DOWNMIX, &descriptors);
7103 if (status != NO_ERROR) {
7104 return;
7105 }
7106 ALOG_ASSERT(!descriptors.empty(),
7107 "%s getDescriptors() returned no error but empty list", __func__);
7108
7109 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7110 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007111 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007112
7113 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7114 ALOGW("%s error creating downmixer %d", __func__, status);
7115 finalDownMixer.clear();
7116 } else {
7117 int32_t ret;
7118 finalDownMixer->enable(&ret);
7119 }
7120 }
7121
7122 {
7123 Mutex::Autolock _l(mLock);
7124 mFinalDownMixer = finalDownMixer;
7125 }
7126}
7127
Eric Laurent6acd1d42017-01-04 14:23:29 -08007128
Eric Laurent81784c32012-11-19 14:55:58 -08007129// ----------------------------------------------------------------------------
7130// Record
7131// ----------------------------------------------------------------------------
7132
7133AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
7134 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007135 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007136 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007137 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07007138 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007139 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007140 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007141 mActiveTracks(&this->mLocalLog),
7142 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007143 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007144 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007145 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7146 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007147 // mFastCapture below
7148 , mFastCaptureFutex(0)
7149 // mInputSource
7150 // mPipeSink
7151 // mPipeSource
7152 , mPipeFramesP2(0)
7153 // mPipeMemory
7154 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007155 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007156 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007157{
Glenn Kastend7dca052015-03-05 16:05:54 -08007158 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7159 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007160
George Burgess IVa8f90c12020-05-14 11:27:19 -07007161 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007162 mIsMsdDevice = strcmp(
7163 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7164 }
7165
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007166 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007167
Andy Hungc8fddf32018-08-08 18:32:37 -07007168 // TODO: We may also match on address as well as device type for
7169 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007170 // TODO: This property should be ensure that only contains one single device type.
7171 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7172 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007173 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7174 : AUDIO_DEVICE_NONE));
7175
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007176 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007177 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007178 size_t numCounterOffers = 0;
7179 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007180#if !LOG_NDEBUG
7181 ssize_t index =
7182#else
7183 (void)
7184#endif
7185 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007186 ALOG_ASSERT(index == 0);
7187
7188 // initialize fast capture depending on configuration
7189 bool initFastCapture;
7190 switch (kUseFastCapture) {
7191 case FastCapture_Never:
7192 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007193 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007194 break;
7195 case FastCapture_Always:
7196 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007197 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007198 break;
7199 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07007200 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007201 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
7202 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
7203 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007204 break;
7205 // case FastCapture_Dynamic:
7206 }
7207
7208 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007209 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007210 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007211 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7212 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007213 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007214 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007215 const sp<MemoryDealer> roHeap(readOnlyHeap());
7216 sp<IMemory> pipeMemory;
7217 if ((roHeap == 0) ||
7218 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007219 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007220 ALOGE("not enough memory for pipe buffer size=%zu; "
7221 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7222 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7223 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007224 goto failed;
7225 }
7226 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7227 memset(pipeBuffer, 0, pipeSize);
7228 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7229 const NBAIO_Format offers[1] = {format};
7230 size_t numCounterOffers = 0;
7231 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7232 ALOG_ASSERT(index == 0);
7233 mPipeSink = pipe;
7234 PipeReader *pipeReader = new PipeReader(*pipe);
7235 numCounterOffers = 0;
7236 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7237 ALOG_ASSERT(index == 0);
7238 mPipeSource = pipeReader;
7239 mPipeFramesP2 = pipeFramesP2;
7240 mPipeMemory = pipeMemory;
7241
7242 // create fast capture
7243 mFastCapture = new FastCapture();
7244 FastCaptureStateQueue *sq = mFastCapture->sq();
7245#ifdef STATE_QUEUE_DUMP
7246 // FIXME
7247#endif
7248 FastCaptureState *state = sq->begin();
7249 state->mCblk = NULL;
7250 state->mInputSource = mInputSource.get();
7251 state->mInputSourceGen++;
7252 state->mPipeSink = pipe;
7253 state->mPipeSinkGen++;
7254 state->mFrameCount = mFrameCount;
7255 state->mCommand = FastCaptureState::COLD_IDLE;
7256 // already done in constructor initialization list
7257 //mFastCaptureFutex = 0;
7258 state->mColdFutexAddr = &mFastCaptureFutex;
7259 state->mColdGen++;
7260 state->mDumpState = &mFastCaptureDumpState;
7261#ifdef TEE_SINK
7262 // FIXME
7263#endif
7264 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7265 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7266 sq->end();
7267 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7268
7269 // start the fast capture
7270 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7271 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007272 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007273 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007274#ifdef AUDIO_WATCHDOG
7275 // FIXME
7276#endif
7277
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007278 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007279 }
Andy Hung8946a282018-04-19 20:04:56 -07007280#ifdef TEE_SINK
7281 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7282 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7283#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007284failed: ;
7285
7286 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007287}
7288
Eric Laurent81784c32012-11-19 14:55:58 -08007289AudioFlinger::RecordThread::~RecordThread()
7290{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007291 if (mFastCapture != 0) {
7292 FastCaptureStateQueue *sq = mFastCapture->sq();
7293 FastCaptureState *state = sq->begin();
7294 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7295 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7296 if (old == -1) {
7297 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7298 }
7299 }
7300 state->mCommand = FastCaptureState::EXIT;
7301 sq->end();
7302 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7303 mFastCapture->join();
7304 mFastCapture.clear();
7305 }
7306 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007307 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007308 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007309}
7310
7311void AudioFlinger::RecordThread::onFirstRef()
7312{
Glenn Kastend7dca052015-03-05 16:05:54 -08007313 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007314}
7315
Eric Laurent555530a2017-02-07 18:17:24 -08007316void AudioFlinger::RecordThread::preExit()
7317{
7318 ALOGV(" preExit()");
7319 Mutex::Autolock _l(mLock);
7320 for (size_t i = 0; i < mTracks.size(); i++) {
7321 sp<RecordTrack> track = mTracks[i];
7322 track->invalidate();
7323 }
7324 mActiveTracks.clear();
7325 mStartStopCond.broadcast();
7326}
7327
Eric Laurent81784c32012-11-19 14:55:58 -08007328bool AudioFlinger::RecordThread::threadLoop()
7329{
Eric Laurent81784c32012-11-19 14:55:58 -08007330 nsecs_t lastWarning = 0;
7331
7332 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007333
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007334reacquire_wakelock:
7335 sp<RecordTrack> activeTrack;
7336 {
7337 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007338 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007339 }
7340
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007341 // used to request a deferred sleep, to be executed later while mutex is unlocked
7342 uint32_t sleepUs = 0;
7343
Andy Hung446f4df2019-02-21 12:26:41 -08007344 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7345
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007346 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007347 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007348 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007349
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007350 // activeTracks accumulates a copy of a subset of mActiveTracks
7351 Vector< sp<RecordTrack> > activeTracks;
7352
Glenn Kasten735f45f2014-08-18 15:51:59 -07007353 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007354 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007355
Glenn Kasten735f45f2014-08-18 15:51:59 -07007356 // reference to a fast track which is about to be removed
7357 sp<RecordTrack> fastTrackToRemove;
7358
Eric Laurent33403f02020-05-29 18:35:06 -07007359 bool silenceFastCapture = false;
7360
Eric Laurent81784c32012-11-19 14:55:58 -08007361 { // scope for mLock
7362 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007363
Eric Laurent021cf962014-05-13 10:18:14 -07007364 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007365
Eric Laurent000a4192014-01-29 15:17:32 -08007366 // check exitPending here because checkForNewParameters_l() and
7367 // checkForNewParameters_l() can temporarily release mLock
7368 if (exitPending()) {
7369 break;
7370 }
7371
Eric Laurent5c25d562016-07-13 17:17:45 -07007372 // sleep with mutex unlocked
7373 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007374 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007375 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7376 ATRACE_END();
7377 sleepUs = 0;
7378 continue;
7379 }
7380
Glenn Kasten2b806402013-11-20 16:37:38 -08007381 // if no active track(s), then standby and release wakelock
7382 size_t size = mActiveTracks.size();
7383 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007384 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007385 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007386 releaseWakeLock_l();
7387 ALOGV("RecordThread: loop stopping");
7388 // go to sleep
7389 mWaitWorkCV.wait(mLock);
7390 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007391 goto reacquire_wakelock;
7392 }
7393
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007394 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007395 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007396 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007397
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007398 activeTrack = mActiveTracks[i];
7399 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007400 if (activeTrack->isFastTrack()) {
7401 ALOG_ASSERT(fastTrackToRemove == 0);
7402 fastTrackToRemove = activeTrack;
7403 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007404 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007405 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007406 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007407 continue;
7408 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007409
7410 TrackBase::track_state activeTrackState = activeTrack->mState;
7411 switch (activeTrackState) {
7412
7413 case TrackBase::PAUSING:
7414 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007415 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007416 doBroadcast = true;
7417 size--;
7418 continue;
7419
7420 case TrackBase::STARTING_1:
7421 sleepUs = 10000;
7422 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007423 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007424 continue;
7425
7426 case TrackBase::STARTING_2:
7427 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007428 if (mStandby) {
7429 mThreadMetrics.logBeginInterval();
7430 mStandby = false;
7431 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007432 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007433 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007434 break;
7435
7436 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007437 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007438 break;
7439
Andy Hungce685402018-10-05 17:23:27 -07007440 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7441 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7442 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007443 default:
Andy Hungce685402018-10-05 17:23:27 -07007444 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7445 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007446 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007447
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007448 if (activeTrack->isFastTrack()) {
7449 ALOG_ASSERT(!mFastTrackAvail);
7450 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007451 // if the active fast track is silenced either:
7452 // 1) silence the whole capture from fast capture buffer if this is
7453 // the only active track
7454 // 2) invalidate this track: this will cause the client to reconnect and possibly
7455 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007456 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07007457 if (activeTrack->isSilenced()) {
7458 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007459 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07007460 } else {
7461 silenceFastCapture = true;
7462 }
7463 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007464 // Invalidate fast tracks if access to audio history is required as this is not
7465 // possible with fast tracks. Once the fast track has been invalidated, no new
7466 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
7467 if (mMaxSharedAudioHistoryMs != 0) {
7468 invalidate = true;
7469 }
7470 if (invalidate) {
7471 activeTrack->invalidate();
7472 ALOG_ASSERT(fastTrackToRemove == 0);
7473 fastTrackToRemove = activeTrack;
7474 removeTrack_l(activeTrack);
7475 mActiveTracks.remove(activeTrack);
7476 size--;
7477 continue;
7478 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007479 fastTrack = activeTrack;
7480 }
Eric Laurent33403f02020-05-29 18:35:06 -07007481
7482 activeTracks.add(activeTrack);
7483 i++;
7484
Glenn Kasten9e982352013-08-14 14:39:50 -07007485 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007486
Andy Hungdae27702016-10-31 14:01:16 -07007487 mActiveTracks.updatePowerState(this);
7488
Kevin Rocard069c2712018-03-29 19:09:14 -07007489 updateMetadata_l();
7490
Eric Laurent5c25d562016-07-13 17:17:45 -07007491 if (allStopped) {
7492 standbyIfNotAlreadyInStandby();
7493 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007494 if (doBroadcast) {
7495 mStartStopCond.broadcast();
7496 }
7497
7498 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007499 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007500 if (sleepUs == 0) {
7501 sleepUs = kRecordThreadSleepUs;
7502 }
7503 continue;
7504 }
7505 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007506
Eric Laurent81784c32012-11-19 14:55:58 -08007507 lockEffectChains_l(effectChains);
7508 }
7509
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007510 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007511
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007512 size_t size = effectChains.size();
7513 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007514 // thread mutex is not locked, but effect chain is locked
7515 effectChains[i]->process_l();
7516 }
7517
Glenn Kasten735f45f2014-08-18 15:51:59 -07007518 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007519 if (mFastCapture != 0) {
7520 FastCaptureStateQueue *sq = mFastCapture->sq();
7521 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007522 bool didModify = false;
7523 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007524 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7525 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7526 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7527 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7528 if (old == -1) {
7529 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7530 }
7531 }
7532 state->mCommand = FastCaptureState::READ_WRITE;
7533#if 0 // FIXME
7534 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007535 FastThreadDumpState::kSamplingNforLowRamDevice :
7536 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007537#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007538 didModify = true;
7539 }
7540 audio_track_cblk_t *cblkOld = state->mCblk;
7541 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7542 if (cblkNew != cblkOld) {
7543 state->mCblk = cblkNew;
7544 // block until acked if removing a fast track
7545 if (cblkOld != NULL) {
7546 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7547 }
7548 didModify = true;
7549 }
jiabin01c8f562018-07-19 17:47:28 -07007550 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7551 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7552 if (state->mFastPatchRecordBufferProvider != abp) {
7553 state->mFastPatchRecordBufferProvider = abp;
7554 state->mFastPatchRecordFormat = fastTrack == 0 ?
7555 AUDIO_FORMAT_INVALID : fastTrack->format();
7556 didModify = true;
7557 }
Eric Laurent33403f02020-05-29 18:35:06 -07007558 if (state->mSilenceCapture != silenceFastCapture) {
7559 state->mSilenceCapture = silenceFastCapture;
7560 didModify = true;
7561 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007562 sq->end(didModify);
7563 if (didModify) {
7564 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007565#if 0
7566 if (kUseFastCapture == FastCapture_Dynamic) {
7567 mNormalSource = mPipeSource;
7568 }
7569#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007570 }
7571 }
7572
Glenn Kasten735f45f2014-08-18 15:51:59 -07007573 // now run the fast track destructor with thread mutex unlocked
7574 fastTrackToRemove.clear();
7575
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007576 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7577 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7578 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7579 // If destination is non-contiguous, first read past the nominal end of buffer, then
7580 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007581
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007582 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007583 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007584 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007585
7586 // If an NBAIO source is present, use it to read the normal capture's data
7587 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007588 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007589
7590 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7591 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7592 // we immediately retry the read() to get data and prevent another overflow.
7593 for (int retries = 0; retries <= 2; ++retries) {
7594 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7595 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7596 framesToRead);
7597 if (framesRead != OVERRUN) break;
7598 }
7599
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007600 const ssize_t availableToRead = mPipeSource->availableToRead();
7601 if (availableToRead >= 0) {
Glenn Kastena2f59b32020-08-03 16:37:24 -07007602 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007603 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7604 "more frames to read than fifo size, %zd > %zu",
7605 availableToRead, mPipeFramesP2);
7606 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7607 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7608 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7609 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007610 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7611 }
7612 if (framesRead < 0) {
7613 status_t status = (status_t) framesRead;
7614 switch (status) {
7615 case OVERRUN:
7616 ALOGW("overrun on read from pipe");
7617 framesRead = 0;
7618 break;
7619 case NEGOTIATE:
7620 ALOGE("re-negotiation is needed");
7621 framesRead = -1; // Will cause an attempt to recover.
7622 break;
7623 default:
7624 ALOGE("unknown error %d on read from pipe", status);
7625 break;
7626 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007627 }
7628 // otherwise use the HAL / AudioStreamIn directly
7629 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007630 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007631 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007632 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007633 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007634 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007635 if (result < 0) {
7636 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007637 } else {
7638 framesRead = bytesRead / mFrameSize;
7639 }
7640 }
7641
Andy Hung446f4df2019-02-21 12:26:41 -08007642 const int64_t lastIoEndNs = systemTime(); // end IO timing
7643
Andy Hung3f0c9022016-01-15 17:49:46 -08007644 // Update server timestamp with server stats
7645 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07007646 if (framesRead >= 0) {
7647 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7648 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7649 }
Andy Hung3f0c9022016-01-15 17:49:46 -08007650
7651 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007652 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007653 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007654 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11007655 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
7656 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
7657 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07007658 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007659 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7660
7661 mTimestampVerifier.add(position, time, mSampleRate);
7662
7663 // Correct timestamps
7664 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10007665 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007666 id(), (long long)time, (long long)position);
7667 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7668 position = correctedTimestamp.mFrames;
7669 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10007670 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007671 id(), (long long)time, (long long)position);
7672 }
7673
Andy Hung3f0c9022016-01-15 17:49:46 -08007674 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7675 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7676 // Note: In general record buffers should tend to be empty in
7677 // a properly running pipeline.
7678 //
7679 // Also, it is not advantageous to call get_presentation_position during the read
7680 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007681 } else {
7682 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007683 }
7684 }
Andy Hunge6c37112019-02-26 17:38:10 -08007685
7686 // From the timestamp, input read latency is negative output write latency.
7687 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7688 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7689 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7690 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7691 mLatencyMs.add(latencyMs);
7692 }
7693
Andy Hung3f0c9022016-01-15 17:49:46 -08007694 // Use this to track timestamp information
7695 // ALOGD("%s", mTimestamp.toString().c_str());
7696
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007697 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007698 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007699 // Force input into standby so that it tries to recover at next read attempt
7700 inputStandBy();
7701 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007702 }
7703 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007704 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007705 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007706 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007707 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007708
Andy Hung8946a282018-04-19 20:04:56 -07007709#ifdef TEE_SINK
7710 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7711#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007712 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007713 {
7714 size_t part1 = mRsmpInFramesP2 - rear;
7715 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007716 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007717 (framesRead - part1) * mFrameSize);
7718 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007719 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11007720 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007721
7722 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007723
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007724 // loop over each active track
7725 for (size_t i = 0; i < size; i++) {
7726 activeTrack = activeTracks[i];
7727
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007728 // skip fast tracks, as those are handled directly by FastCapture
7729 if (activeTrack->isFastTrack()) {
7730 continue;
7731 }
7732
Andy Hung73c02e42015-03-29 01:13:58 -07007733 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007734 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7735
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007736 enum {
7737 OVERRUN_UNKNOWN,
7738 OVERRUN_TRUE,
7739 OVERRUN_FALSE
7740 } overrun = OVERRUN_UNKNOWN;
7741
7742 // loop over getNextBuffer to handle circular sink
7743 for (;;) {
7744
7745 activeTrack->mSink.frameCount = ~0;
7746 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7747 size_t framesOut = activeTrack->mSink.frameCount;
7748 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7749
Andy Hung73c02e42015-03-29 01:13:58 -07007750 // check available frames and handle overrun conditions
7751 // if the record track isn't draining fast enough.
7752 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007753 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007754 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7755 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007756 overrun = OVERRUN_TRUE;
7757 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007758 if (framesOut == 0 || framesIn == 0) {
7759 break;
7760 }
7761
Andy Hung6770c6f2015-04-07 13:43:36 -07007762 // Don't allow framesOut to be larger than what is possible with resampling
7763 // from framesIn.
7764 // This isn't strictly necessary but helps limit buffer resizing in
7765 // RecordBufferConverter. TODO: remove when no longer needed.
7766 framesOut = min(framesOut,
7767 destinationFramesPossible(
7768 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007769
7770 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007771 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007772 // straight from RecordThread buffer to RecordTrack buffer.
7773 AudioBufferProvider::Buffer buffer;
7774 buffer.frameCount = framesOut;
7775 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7776 if (status == OK && buffer.frameCount != 0) {
7777 ALOGV_IF(buffer.frameCount != framesOut,
7778 "%s() read less than expected (%zu vs %zu)",
7779 __func__, buffer.frameCount, framesOut);
7780 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007781 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007782 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7783 } else {
7784 framesOut = 0;
7785 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7786 __func__, status, buffer.frameCount);
7787 }
7788 } else {
7789 // process frames from the RecordThread buffer provider to the RecordTrack
7790 // buffer
7791 framesOut = activeTrack->mRecordBufferConverter->convert(
7792 activeTrack->mSink.raw,
7793 activeTrack->mResamplerBufferProvider,
7794 framesOut);
7795 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007796
7797 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7798 overrun = OVERRUN_FALSE;
7799 }
7800
7801 if (activeTrack->mFramesToDrop == 0) {
7802 if (framesOut > 0) {
7803 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007804 // Sanitize before releasing if the track has no access to the source data
7805 // An idle UID receives silence from non virtual devices until active
7806 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007807 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007808 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007809 activeTrack->releaseBuffer(&activeTrack->mSink);
7810 }
7811 } else {
7812 // FIXME could do a partial drop of framesOut
7813 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007814 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007815 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007816 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007817 }
7818 } else {
7819 activeTrack->mFramesToDrop += framesOut;
7820 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7821 activeTrack->mSyncStartEvent->isCancelled()) {
7822 ALOGW("Synced record %s, session %d, trigger session %d",
7823 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7824 activeTrack->sessionId(),
7825 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007826 activeTrack->mSyncStartEvent->triggerSession() :
7827 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007828 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007829 }
7830 }
7831 }
7832
7833 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007834 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007835 }
7836 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007837
7838 switch (overrun) {
7839 case OVERRUN_TRUE:
7840 // client isn't retrieving buffers fast enough
7841 if (!activeTrack->setOverflow()) {
7842 nsecs_t now = systemTime();
7843 // FIXME should lastWarning per track?
7844 if ((now - lastWarning) > kWarningThrottleNs) {
7845 ALOGW("RecordThread: buffer overflow");
7846 lastWarning = now;
7847 }
7848 }
7849 break;
7850 case OVERRUN_FALSE:
7851 activeTrack->clearOverflow();
7852 break;
7853 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007854 break;
7855 }
7856
Andy Hung3f0c9022016-01-15 17:49:46 -08007857 // update frame information and push timestamp out
7858 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007859 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007860 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7861 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007862 }
7863
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007864unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007865 // enable changes in effect chain
7866 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007867 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007868 if (audio_has_proportional_frames(mFormat)
7869 && loopCount == lastLoopCountRead + 1) {
7870 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7871 const double jitterMs =
7872 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7873 {framesRead, readPeriodNs},
7874 {0, 0} /* lastTimestamp */, mSampleRate);
7875 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7876
7877 Mutex::Autolock _l(mLock);
7878 mIoJitterMs.add(jitterMs);
7879 mProcessTimeMs.add(processMs);
7880 }
7881 // update timing info.
7882 mLastIoBeginNs = lastIoBeginNs;
7883 mLastIoEndNs = lastIoEndNs;
7884 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007885 }
7886
Glenn Kasten93e471f2013-08-19 08:40:07 -07007887 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007888
7889 {
7890 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007891 for (size_t i = 0; i < mTracks.size(); i++) {
7892 sp<RecordTrack> track = mTracks[i];
7893 track->invalidate();
7894 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007895 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007896 mStartStopCond.broadcast();
7897 }
7898
7899 releaseWakeLock();
7900
7901 ALOGV("RecordThread %p exiting", this);
7902 return false;
7903}
7904
Glenn Kasten93e471f2013-08-19 08:40:07 -07007905void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007906{
7907 if (!mStandby) {
7908 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07007909 mThreadMetrics.logEndInterval();
Eric Laurent81784c32012-11-19 14:55:58 -08007910 mStandby = true;
7911 }
7912}
7913
7914void AudioFlinger::RecordThread::inputStandBy()
7915{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007916 // Idle the fast capture if it's currently running
7917 if (mFastCapture != 0) {
7918 FastCaptureStateQueue *sq = mFastCapture->sq();
7919 FastCaptureState *state = sq->begin();
7920 if (!(state->mCommand & FastCaptureState::IDLE)) {
7921 state->mCommand = FastCaptureState::COLD_IDLE;
7922 state->mColdFutexAddr = &mFastCaptureFutex;
7923 state->mColdGen++;
7924 mFastCaptureFutex = 0;
7925 sq->end();
7926 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7927 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7928#if 0
7929 if (kUseFastCapture == FastCapture_Dynamic) {
7930 // FIXME
7931 }
7932#endif
7933#ifdef AUDIO_WATCHDOG
7934 // FIXME
7935#endif
7936 } else {
7937 sq->end(false /*didModify*/);
7938 }
7939 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07007940 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007941 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007942
7943 // If going into standby, flush the pipe source.
7944 if (mPipeSource.get() != nullptr) {
7945 const ssize_t flushed = mPipeSource->flush();
7946 if (flushed > 0) {
7947 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7948 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7949 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7950 }
7951 }
Eric Laurent81784c32012-11-19 14:55:58 -08007952}
7953
Glenn Kasten05997e22014-03-13 15:08:33 -07007954// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007955sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007956 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007957 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007958 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007959 audio_format_t format,
7960 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007961 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007962 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007963 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007964 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00007965 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07007966 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007967 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007968 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02007969 audio_port_handle_t portId,
7970 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08007971{
Glenn Kasten74935e42013-12-19 08:56:45 -08007972 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007973 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007974 sp<RecordTrack> track;
7975 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007976 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007977 audio_input_flags_t requestedFlags = *flags;
7978 uint32_t sampleRate;
Svet Ganov33761132021-05-13 22:51:08 +00007979 AttributionSourceState checkedAttributionSource = AudioFlinger::checkAttributionSourcePackage(
7980 attributionSource);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007981
7982 lStatus = initCheck();
7983 if (lStatus != NO_ERROR) {
7984 ALOGE("createRecordTrack_l() audio driver not initialized");
7985 goto Exit;
7986 }
7987
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007988 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7989 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7990 lStatus = BAD_VALUE;
7991 goto Exit;
7992 }
7993
Eric Laurentec376dc2021-04-08 20:41:22 +02007994 if (maxSharedAudioHistoryMs != 0) {
Svet Ganov33761132021-05-13 22:51:08 +00007995 if (!captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02007996 lStatus = PERMISSION_DENIED;
7997 goto Exit;
7998 }
Eric Laurentec376dc2021-04-08 20:41:22 +02007999 if (maxSharedAudioHistoryMs < 0
8000 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8001 lStatus = BAD_VALUE;
8002 goto Exit;
8003 }
8004 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008005 if (*pSampleRate == 0) {
8006 *pSampleRate = mSampleRate;
8007 }
8008 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008009
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008010 // special case for FAST flag considered OK if fast capture is present and access to
8011 // audio history is not required
8012 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008013 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8014 }
8015
Eric Laurentf14db3c2017-12-08 14:20:36 -08008016 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008017 if ((*flags & inputFlags) != *flags) {
8018 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8019 " input flags (%08x)",
8020 *flags, inputFlags);
8021 *flags = (audio_input_flags_t)(*flags & inputFlags);
8022 }
Eric Laurent81784c32012-11-19 14:55:58 -08008023
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008024 // client expresses a preference for FAST and no access to audio history,
8025 // but we get the final say
8026 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008027 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008028 // we formerly checked for a callback handler (non-0 tid),
8029 // but that is no longer required for TRANSFER_OBTAIN mode
8030 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008031 // Frame count is not specified (0), or is less than or equal the pipe depth.
8032 // It is OK to provide a higher capacity than requested.
8033 // We will force it to mPipeFramesP2 below.
8034 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008035 // PCM data
8036 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008037 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008038 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008039 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008040 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008041 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008042 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008043 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008044 hasFastCapture() &&
8045 // there are sufficient fast track slots available
8046 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008047 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008048 // check compatibility with audio effects.
8049 Mutex::Autolock _l(mLock);
8050 // Do not accept FAST flag if the session has software effects
8051 sp<EffectChain> chain = getEffectChain_l(sessionId);
8052 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008053 audio_input_flags_t old = *flags;
8054 chain->checkInputFlagCompatibility(flags);
8055 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008056 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8057 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008058 }
8059 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008060 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008061 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8062 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008063 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008064 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8065 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008066 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008067 this, frameCount, mFrameCount, mPipeFramesP2,
8068 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008069 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008070 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008071 }
8072 }
8073
Eric Laurentf14db3c2017-12-08 14:20:36 -08008074 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8075 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8076 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8077 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8078 lStatus = BAD_TYPE;
8079 goto Exit;
8080 }
8081
Glenn Kasten74105912014-07-03 12:28:53 -07008082 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008083 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008084 // fast track: frame count is exactly the pipe depth
8085 frameCount = mPipeFramesP2;
8086 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008087 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008088 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008089 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8090 // or 20 ms if there is a fast capture
8091 // TODO This could be a roundupRatio inline, and const
8092 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8093 * sampleRate + mSampleRate - 1) / mSampleRate;
8094 // minimum number of notification periods is at least kMinNotifications,
8095 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8096 static const size_t kMinNotifications = 3;
8097 static const uint32_t kMinMs = 30;
8098 // TODO This could be a roundupRatio inline
8099 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8100 // TODO This could be a roundupRatio inline
8101 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8102 maxNotificationFrames;
8103 const size_t minFrameCount = maxNotificationFrames *
8104 max(kMinNotifications, minNotificationsByMs);
8105 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008106 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8107 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008108 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008109 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008110 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008111 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008112
8113 { // scope for mLock
8114 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008115 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008116 if (!mSharedAudioPackageName.empty()
Svet Ganov33761132021-05-13 22:51:08 +00008117 && mSharedAudioPackageName == checkedAttributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008118 && mSharedAudioSessionId == sessionId
Svet Ganov33761132021-05-13 22:51:08 +00008119 && captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008120 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008121 }
Eric Laurent81784c32012-11-19 14:55:58 -08008122
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008123 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008124 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008125 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008126 checkedAttributionSource, *flags, TrackBase::TYPE_DEFAULT, portId,
8127 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008128
Glenn Kasten03003332013-08-06 15:40:54 -07008129 lStatus = track->initCheck();
8130 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008131 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008132 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008133 goto Exit;
8134 }
8135 mTracks.add(track);
8136
Eric Laurent05067782016-06-01 18:27:28 -07008137 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008138 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8139 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8140 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008141 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008142 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008143
8144 if (maxSharedAudioHistoryMs != 0) {
8145 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8146 }
Eric Laurent81784c32012-11-19 14:55:58 -08008147 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008148
Eric Laurent81784c32012-11-19 14:55:58 -08008149 lStatus = NO_ERROR;
8150
8151Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008152 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008153 return track;
8154}
8155
8156status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
8157 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008158 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008159{
8160 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8161 sp<ThreadBase> strongMe = this;
8162 status_t status = NO_ERROR;
8163
8164 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008165 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008166 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008167 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08008168 triggerSession,
8169 recordTrack->sessionId(),
8170 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008171 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08008172 // Sync event can be cancelled by the trigger session if the track is not in a
8173 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008174 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008175 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008176 } else {
8177 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08008178 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008179 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08008180 }
8181 }
8182
8183 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008184 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008185 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008186 if (recordTrack->isInvalid()) {
8187 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008188 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8189 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008190 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008191 if (mActiveTracks.indexOf(recordTrack) >= 0) {
8192 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008193 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8194 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008195 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008196 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008197 } else {
8198 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008199 }
8200 return status;
8201 }
8202
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008203 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8204 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8205 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008206 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08008207 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008208 status_t status = NO_ERROR;
8209 if (recordTrack->isExternalTrack()) {
8210 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008211 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008212 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008213 if (recordTrack->isInvalid()) {
8214 recordTrack->clearSyncStartEvent();
8215 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8216 recordTrack->mState = TrackBase::STARTING_2;
8217 // STARTING_2 forces destroy to call stopInput.
8218 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008219 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8220 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008221 }
8222 if (recordTrack->mState != TrackBase::STARTING_1) {
8223 ALOGW("%s(%d): unsynchronized mState:%d change",
8224 __func__, recordTrack->id(), recordTrack->mState);
8225 // Someone else has changed state, let them take over,
8226 // leave mState in the new state.
8227 recordTrack->clearSyncStartEvent();
8228 return INVALID_OPERATION;
8229 }
8230 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008231 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008232 ALOGW("%s(%d): startInput failed, status %d",
8233 __func__, recordTrack->id(), status);
8234 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8235 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008236 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008237 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008238 return status;
8239 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008240 sendIoConfigEvent_l(
8241 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008242 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008243
8244 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8245
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008246 // Catch up with current buffer indices if thread is already running.
8247 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8248 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8249 // see previously buffered data before it called start(), but with greater risk of overrun.
8250
Andy Hung73c02e42015-03-29 01:13:58 -07008251 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008252 if (!recordTrack->isDirect()) {
8253 // clear any converter state as new data will be discontinuous
8254 recordTrack->mRecordBufferConverter->reset();
8255 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008256 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008257 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008258 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008259 return status;
8260 }
Eric Laurent81784c32012-11-19 14:55:58 -08008261}
8262
Eric Laurent81784c32012-11-19 14:55:58 -08008263void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8264{
8265 sp<SyncEvent> strongEvent = event.promote();
8266
8267 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008268 sp<RefBase> ptr = strongEvent->cookie().promote();
8269 if (ptr != 0) {
8270 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8271 recordTrack->handleSyncStartEvent(strongEvent);
8272 }
Eric Laurent81784c32012-11-19 14:55:58 -08008273 }
8274}
8275
Glenn Kastena8356f62013-07-25 14:37:52 -07008276bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008277 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008278 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008279 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008280 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008281 return false;
8282 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008283 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008284 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008285
Andy Hungabfab202019-03-07 19:45:54 -08008286 // NOTE: Waiting here is important to keep stop synchronous.
8287 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008288 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8289 mWaitWorkCV.broadcast(); // signal thread to stop
8290 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008291 }
Andy Hungce685402018-10-05 17:23:27 -07008292
8293 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008294 ALOGV("Record stopped OK");
8295 return true;
8296 }
Andy Hungce685402018-10-05 17:23:27 -07008297
8298 // don't handle anything - we've been invalidated or restarted and in a different state
8299 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8300 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008301 return false;
8302}
8303
Glenn Kasten0f11b512014-01-31 16:18:54 -08008304bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008305{
8306 return false;
8307}
8308
Glenn Kasten0f11b512014-01-31 16:18:54 -08008309status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008310{
8311#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8312 if (!isValidSyncEvent(event)) {
8313 return BAD_VALUE;
8314 }
8315
Glenn Kastend848eb42016-03-08 13:42:11 -08008316 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008317 status_t ret = NAME_NOT_FOUND;
8318
8319 Mutex::Autolock _l(mLock);
8320
8321 for (size_t i = 0; i < mTracks.size(); i++) {
8322 sp<RecordTrack> track = mTracks[i];
8323 if (eventSession == track->sessionId()) {
8324 (void) track->setSyncEvent(event);
8325 ret = NO_ERROR;
8326 }
8327 }
8328 return ret;
8329#else
8330 return BAD_VALUE;
8331#endif
8332}
8333
jiabin653cc0a2018-01-17 17:54:10 -08008334status_t AudioFlinger::RecordThread::getActiveMicrophones(
8335 std::vector<media::MicrophoneInfo>* activeMicrophones)
8336{
8337 ALOGV("RecordThread::getActiveMicrophones");
8338 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008339 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008340 return NO_INIT;
8341 }
jiabin9ff780e2018-03-19 18:19:52 -07008342 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8343 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008344}
8345
Paul McLean12340082019-03-19 09:35:05 -06008346status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8347 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008348{
Paul McLean12340082019-03-19 09:35:05 -06008349 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008350 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008351 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008352 return NO_INIT;
8353 }
Paul McLean12340082019-03-19 09:35:05 -06008354 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008355}
8356
Paul McLean12340082019-03-19 09:35:05 -06008357status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008358{
Paul McLean12340082019-03-19 09:35:05 -06008359 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008360 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008361 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008362 return NO_INIT;
8363 }
Paul McLean12340082019-03-19 09:35:05 -06008364 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008365}
8366
Eric Laurentec376dc2021-04-08 20:41:22 +02008367status_t AudioFlinger::RecordThread::shareAudioHistory(
8368 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8369 int64_t sharedAudioStartMs) {
8370 AutoMutex _l(mLock);
8371 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8372}
8373
8374status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8375 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8376 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008377
Eric Laurentec376dc2021-04-08 20:41:22 +02008378 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8379 return BAD_VALUE;
8380 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008381
8382 if (sharedAudioStartMs < 0
8383 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008384 return BAD_VALUE;
8385 }
8386
Eric Laurent2407ce32021-04-26 14:56:03 +02008387 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8388 // As we cannot detect more than one wraparound, only accept values up current write position
8389 // after one wraparound
8390 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8391 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02008392 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02008393 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8394 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02008395 // Bring the start frame position within the input buffer to match the documented
8396 // "best effort" behavior of the API.
8397 if (sharedOffset < 0) {
8398 sharedAudioStartFrames = mRsmpInRear;
8399 } else if (sharedOffset > mRsmpInFrames) {
8400 sharedAudioStartFrames =
8401 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02008402 }
8403
Eric Laurentec376dc2021-04-08 20:41:22 +02008404 mSharedAudioPackageName = sharedAudioPackageName;
8405 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008406 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02008407 } else {
8408 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02008409 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008410 }
8411 return NO_ERROR;
8412}
8413
Eric Laurent92d0a322021-07-16 15:32:33 +02008414void AudioFlinger::RecordThread::resetAudioHistory_l() {
8415 mSharedAudioSessionId = AUDIO_SESSION_NONE;
8416 mSharedAudioStartFrames = -1;
8417 mSharedAudioPackageName = "";
8418}
8419
Kevin Rocard069c2712018-03-29 19:09:14 -07008420void AudioFlinger::RecordThread::updateMetadata_l()
8421{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008422 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
8423 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07008424 }
8425 StreamInHalInterface::SinkMetadata metadata;
8426 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01008427 // Do not forward PatchRecord metadata to audio HAL
8428 if (track->isPatchTrack()) {
8429 continue;
8430 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008431 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01008432 record_track_metadata_v7_t trackMetadata;
8433 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07008434 .source = track->attributes().source,
8435 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +01008436 };
8437 trackMetadata.channel_mask = track->channelMask(),
8438 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8439
8440 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07008441 }
8442 mInput->stream->updateSinkMetadata(metadata);
8443}
8444
Eric Laurent81784c32012-11-19 14:55:58 -08008445// destroyTrack_l() must be called with ThreadBase::mLock held
8446void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8447{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008448 track->terminate();
8449 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008450
Eric Laurent81784c32012-11-19 14:55:58 -08008451 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008452 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008453 removeTrack_l(track);
8454 }
8455}
8456
8457void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8458{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008459 String8 result;
8460 track->appendDump(result, false /* active */);
8461 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8462
Eric Laurent81784c32012-11-19 14:55:58 -08008463 mTracks.remove(track);
8464 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008465 if (track->isFastTrack()) {
8466 ALOG_ASSERT(!mFastTrackAvail);
8467 mFastTrackAvail = true;
8468 }
Eric Laurent81784c32012-11-19 14:55:58 -08008469}
8470
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008471void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008472{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008473 AudioStreamIn *input = mInput;
8474 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8475 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008476 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008477 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008478 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008479 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008480 }
Andy Hungbfa64962017-06-12 14:43:19 -07008481
8482 if (input != nullptr) {
8483 dprintf(fd, " Hal stream dump:\n");
8484 (void)input->stream->dump(fd);
8485 }
8486
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008487 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008488 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008489
Glenn Kasten2f90c512015-12-02 11:40:09 -08008490 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8491 // while we are dumping it. It may be inconsistent, but it won't mutate!
8492 // This is a large object so we place it on the heap.
8493 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008494 const std::unique_ptr<FastCaptureDumpState> copy =
8495 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008496 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008497}
8498
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008499void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008500{
Eric Laurent81784c32012-11-19 14:55:58 -08008501 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008502 size_t numtracks = mTracks.size();
8503 size_t numactive = mActiveTracks.size();
8504 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008505 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008506 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008507 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008508 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008509 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008510 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008511 for (size_t i = 0; i < numtracks ; ++i) {
8512 sp<RecordTrack> track = mTracks[i];
8513 if (track != 0) {
8514 bool active = mActiveTracks.indexOf(track) >= 0;
8515 if (active) {
8516 numactiveseen++;
8517 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008518 result.append(prefix);
8519 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008520 }
Eric Laurent81784c32012-11-19 14:55:58 -08008521 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008522 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008523 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008524 }
8525
Marco Nelissenb2208842014-02-07 14:00:50 -08008526 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008527 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008528 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008529 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008530 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008531 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008532 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008533 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008534 result.append(prefix);
8535 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008536 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008537 }
Eric Laurent81784c32012-11-19 14:55:58 -08008538
8539 }
8540 write(fd, result.string(), result.size());
8541}
8542
Eric Laurent5ada82e2019-08-29 17:53:54 -07008543void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008544{
8545 Mutex::Autolock _l(mLock);
8546 for (size_t i = 0; i < mTracks.size() ; i++) {
8547 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008548 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008549 track->setSilenced(silenced);
8550 }
8551 }
8552}
Andy Hung73c02e42015-03-29 01:13:58 -07008553
8554void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8555{
8556 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8557 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008558 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008559 const int32_t rear = recordThread->mRsmpInRear;
8560 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008561 if (mRecordTrack->startFrames() >= 0) {
8562 int32_t startFrames = mRecordTrack->startFrames();
8563 // Accept a recent wraparound of mRsmpInRear
8564 if (startFrames <= rear) {
8565 deltaFrames = rear - startFrames;
8566 } else {
8567 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008568 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008569 // start frame cannot be further in the past than start of resampling buffer
8570 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8571 deltaFrames = recordThread->mRsmpInFrames;
8572 }
8573 }
8574 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008575}
8576
8577void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8578 size_t *framesAvailable, bool *hasOverrun)
8579{
8580 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8581 RecordThread *recordThread = (RecordThread *) threadBase.get();
8582 const int32_t rear = recordThread->mRsmpInRear;
8583 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008584 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008585
8586 size_t framesIn;
8587 bool overrun = false;
8588 if (filled < 0) {
8589 // should not happen, but treat like a massive overrun and re-sync
8590 framesIn = 0;
8591 mRsmpInFront = rear;
8592 overrun = true;
8593 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8594 framesIn = (size_t) filled;
8595 } else {
8596 // client is not keeping up with server, but give it latest data
8597 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008598 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8599 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008600 overrun = true;
8601 }
8602 if (framesAvailable != NULL) {
8603 *framesAvailable = framesIn;
8604 }
8605 if (hasOverrun != NULL) {
8606 *hasOverrun = overrun;
8607 }
8608}
8609
Eric Laurent81784c32012-11-19 14:55:58 -08008610// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008611status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008612 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008613{
Andy Hung73c02e42015-03-29 01:13:58 -07008614 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008615 if (threadBase == 0) {
8616 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008617 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008618 return NOT_ENOUGH_DATA;
8619 }
8620 RecordThread *recordThread = (RecordThread *) threadBase.get();
8621 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008622 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008623 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008624 // FIXME should not be P2 (don't want to increase latency)
8625 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008626 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008627 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008628
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008629 front &= recordThread->mRsmpInFramesP2 - 1;
8630 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008631 if (part1 > (size_t) filled) {
8632 part1 = filled;
8633 }
8634 size_t ask = buffer->frameCount;
8635 ALOG_ASSERT(ask > 0);
8636 if (part1 > ask) {
8637 part1 = ask;
8638 }
8639 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008640 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008641 buffer->raw = NULL;
8642 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008643 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008644 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008645 }
8646
Andy Hung57446612015-04-19 23:56:46 -07008647 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008648 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008649 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008650 return NO_ERROR;
8651}
8652
8653// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008654void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8655 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008656{
Hongwei Wang95e37682019-04-12 11:13:36 -07008657 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008658 if (stepCount == 0) {
8659 return;
8660 }
Andy Hung73c02e42015-03-29 01:13:58 -07008661 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8662 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008663 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008664 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008665 buffer->frameCount = 0;
8666}
8667
Eric Laurentd8365c52017-07-16 15:27:05 -07008668void AudioFlinger::RecordThread::checkBtNrec()
8669{
8670 Mutex::Autolock _l(mLock);
8671 checkBtNrec_l();
8672}
8673
8674void AudioFlinger::RecordThread::checkBtNrec_l()
8675{
8676 // disable AEC and NS if the device is a BT SCO headset supporting those
8677 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07008678 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008679 mAudioFlinger->btNrecIsOff();
8680 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8681 for (size_t i = 0; i < mEffectChains.size(); i++) {
8682 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8683 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8684 }
8685 }
8686}
8687
Andy Hung97a893e2015-03-29 01:03:07 -07008688
Eric Laurent10351942014-05-08 18:49:52 -07008689bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8690 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008691{
8692 bool reconfig = false;
8693
Eric Laurent10351942014-05-08 18:49:52 -07008694 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008695
Eric Laurent10351942014-05-08 18:49:52 -07008696 audio_format_t reqFormat = mFormat;
8697 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008698 // 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 -07008699 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8700
8701 AudioParameter param = AudioParameter(keyValuePair);
8702 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008703
8704 // scope for AutoPark extends to end of method
8705 AutoPark<FastCapture> park(mFastCapture);
8706
Eric Laurent10351942014-05-08 18:49:52 -07008707 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8708 // channel count change can be requested. Do we mandate the first client defines the
8709 // HAL sampling rate and channel count or do we allow changes on the fly?
8710 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8711 samplingRate = value;
8712 reconfig = true;
8713 }
8714 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008715 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008716 status = BAD_VALUE;
8717 } else {
8718 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008719 reconfig = true;
8720 }
Eric Laurent10351942014-05-08 18:49:52 -07008721 }
8722 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8723 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008724 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07008725 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07008726 status = BAD_VALUE;
8727 } else {
8728 channelMask = mask;
8729 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008730 }
Eric Laurent10351942014-05-08 18:49:52 -07008731 }
8732 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8733 // do not accept frame count changes if tracks are open as the track buffer
8734 // size depends on frame count and correct behavior would not be guaranteed
8735 // if frame count is changed after track creation
8736 if (mActiveTracks.size() > 0) {
8737 status = INVALID_OPERATION;
8738 } else {
8739 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008740 }
Eric Laurent10351942014-05-08 18:49:52 -07008741 }
8742 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008743 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008744 }
8745 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8746 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07008747 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008748 }
Glenn Kastene198c362013-08-13 09:13:36 -07008749
Eric Laurent10351942014-05-08 18:49:52 -07008750 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008751 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008752 if (status == INVALID_OPERATION) {
8753 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008754 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008755 }
8756 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008757 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00008758 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
8759 if (mInput->stream->getAudioProperties(&config) == OK &&
8760 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
8761 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07008762 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008763 status = NO_ERROR;
8764 }
Eric Laurent81784c32012-11-19 14:55:58 -08008765 }
Eric Laurent10351942014-05-08 18:49:52 -07008766 if (status == NO_ERROR) {
8767 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008768 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008769 }
8770 }
Eric Laurent81784c32012-11-19 14:55:58 -08008771 }
Eric Laurent10351942014-05-08 18:49:52 -07008772
Eric Laurent81784c32012-11-19 14:55:58 -08008773 return reconfig;
8774}
8775
8776String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8777{
Eric Laurent81784c32012-11-19 14:55:58 -08008778 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008779 if (initCheck() == NO_ERROR) {
8780 String8 out_s8;
8781 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8782 return out_s8;
8783 }
Eric Laurent81784c32012-11-19 14:55:58 -08008784 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008785 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008786}
8787
Eric Laurent09f1ed22019-04-24 17:45:17 -07008788void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8789 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008790 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8791
8792 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008793
8794 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008795 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008796 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008797 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008798 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008799 desc->mChannelMask = mChannelMask;
8800 desc->mSamplingRate = mSampleRate;
8801 desc->mFormat = mFormat;
8802 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008803 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008804 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008805 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008806 case AUDIO_CLIENT_STARTED:
8807 desc->mPatch = mPatch;
8808 desc->mPortId = portId;
8809 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008810 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008811 default:
8812 break;
8813 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008814 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008815}
8816
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008817void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008818{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008819 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8820 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008821 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008822 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8823 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07008824 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
8825 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008826 } else {
Andy Hung936845a2021-06-08 00:09:06 -07008827 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008828 ALOGI("HAL format %#x is not linear pcm", mFormat);
8829 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008830 result = mInput->stream->getFrameSize(&mFrameSize);
8831 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008832 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
8833 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008834 result = mInput->stream->getBufferSize(&mBufferSize);
8835 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008836 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008837 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
8838 "mBufferSize=%zu, mFrameCount=%zu",
8839 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008840
Eric Laurentec376dc2021-04-08 20:41:22 +02008841 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
8842 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008843 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08008844
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008845 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8846 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07008847
8848 audio_input_flags_t flags = mInput->flags;
8849 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
8850 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
8851 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
8852 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
8853 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
8854 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
8855 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
8856 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
8857 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08008858}
8859
Glenn Kasten5f972c02014-01-13 09:59:31 -08008860uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008861{
8862 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008863 uint32_t result;
8864 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8865 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008866 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008867 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008868}
8869
Glenn Kastend848eb42016-03-08 13:42:11 -08008870KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008871{
Glenn Kastend848eb42016-03-08 13:42:11 -08008872 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008873 Mutex::Autolock _l(mLock);
8874 for (size_t j = 0; j < mTracks.size(); ++j) {
8875 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008876 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008877 if (ids.indexOfKey(sessionId) < 0) {
8878 ids.add(sessionId, true);
8879 }
8880 }
8881 return ids;
8882}
8883
8884AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8885{
8886 Mutex::Autolock _l(mLock);
8887 AudioStreamIn *input = mInput;
8888 mInput = NULL;
8889 return input;
8890}
8891
8892// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008893sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008894{
8895 if (mInput == NULL) {
8896 return NULL;
8897 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008898 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008899}
8900
8901status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8902{
Eric Laurent81784c32012-11-19 14:55:58 -08008903 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008904 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008905 chain->setInBuffer(NULL);
8906 chain->setOutBuffer(NULL);
8907
8908 checkSuspendOnAddEffectChain_l(chain);
8909
Eric Laurent1b928682014-10-02 19:41:47 -07008910 // make sure enabled pre processing effects state is communicated to the HAL as we
8911 // just moved them to a new input stream.
8912 chain->syncHalEffectsState();
8913
Eric Laurent81784c32012-11-19 14:55:58 -08008914 mEffectChains.add(chain);
8915
8916 return NO_ERROR;
8917}
8918
8919size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8920{
8921 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008922
8923 for (size_t i = 0; i < mEffectChains.size(); i++) {
8924 if (chain == mEffectChains[i]) {
8925 mEffectChains.removeAt(i);
8926 break;
8927 }
Eric Laurent81784c32012-11-19 14:55:58 -08008928 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008929 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008930}
8931
Eric Laurent1c333e22014-05-20 10:48:17 -07008932status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8933 audio_patch_handle_t *handle)
8934{
8935 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008936
8937 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07008938 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07008939 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02008940 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07008941 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008942 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07008943 }
8944
Eric Laurentd8365c52017-07-16 15:27:05 -07008945 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008946
8947 // store new source and send to effects
8948 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8949 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008950 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008951 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008952 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008953 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008954
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008955 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008956 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8957 status = hwDevice->createAudioPatch(patch->num_sources,
8958 patch->sources,
8959 patch->num_sinks,
8960 patch->sinks,
8961 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008962 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008963 char *address;
8964 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8965 address = audio_device_address_to_parameter(
8966 patch->sources[0].ext.device.type,
8967 patch->sources[0].ext.device.address);
8968 } else {
8969 address = (char *)calloc(1, 1);
8970 }
8971 AudioParameter param = AudioParameter(String8(address));
8972 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008973 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008974 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008975 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008976 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008977 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008978 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008979 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008980
jiabinc52b1ff2019-10-31 17:20:42 -07008981 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008982 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07008983 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07008984 }
Eric Laurent296fb132015-05-01 11:38:42 -07008985
Andy Hungc2b11cb2020-04-22 09:04:01 -07008986 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07008987 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07008988 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07008989 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07008990 // also dispatch to active AudioRecords
8991 for (const auto &track : mActiveTracks) {
8992 track->logEndInterval();
8993 track->logBeginInterval(pathSourcesAsString);
8994 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008995 return status;
8996}
8997
8998status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8999{
9000 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009001
jiabinc52b1ff2019-10-31 17:20:42 -07009002 mPatch = audio_patch{};
9003 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009004
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009005 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009006 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9007 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009008 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07009009 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07009010 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009011 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07009012 }
9013 return status;
9014}
9015
jiabinc52b1ff2019-10-31 17:20:42 -07009016void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
9017{
wendy lin56aa82b2020-12-02 15:19:55 +08009018 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009019 mOutDevices = outDevices;
9020 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9021 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009022 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009023 }
9024}
9025
Eric Laurentec376dc2021-04-08 20:41:22 +02009026int32_t AudioFlinger::RecordThread::getOldestFront_l()
9027{
9028 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009029 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009030 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009031 int32_t oldestFront = mRsmpInRear;
9032 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009033 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009034 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9035 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009036 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009037 if (filled > maxFilled) {
9038 oldestFront = front;
9039 maxFilled = filled;
9040 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009041 }
Eric Laurent92d0a322021-07-16 15:32:33 +02009042 if (maxFilled > mRsmpInFrames) {
9043 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9044 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009045 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009046}
9047
9048void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
9049{
9050 if (offset == 0) {
9051 return;
9052 }
9053 for (size_t i = 0; i < mTracks.size(); i++) {
9054 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9055 front = audio_utils::safe_sub_overflow(front, offset);
9056 mTracks[i]->mResamplerBufferProvider->setFront(front);
9057 }
9058}
9059
9060void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
9061{
9062 // This is the formula for calculating the temporary buffer size.
9063 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9064 // 1 full output buffer, regardless of the alignment of the available input.
9065 // The value is somewhat arbitrary, and could probably be even larger.
9066 // A larger value should allow more old data to be read after a track calls start(),
9067 // without increasing latency.
9068 //
9069 // Note this is independent of the maximum downsampling ratio permitted for capture.
9070 size_t minRsmpInFrames = mFrameCount * 7;
9071
9072 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9073 // capture history available to another client using the same session ID:
9074 // dimension the resampler input buffer accordingly.
9075
9076 // Get oldest client read position: getOldestFront_l() must be called before altering
9077 // mRsmpInRear, or mRsmpInFrames
9078 int32_t previousFront = getOldestFront_l();
9079 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9080 int32_t previousRear = mRsmpInRear;
9081 mRsmpInRear = 0;
9082
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009083 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
9084 && maxSharedAudioHistoryMs <= AudioFlinger::kMaxSharedAudioHistoryMs,
9085 "resizeInputBuffer_l() called with invalid max shared history %d",
9086 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009087 if (maxSharedAudioHistoryMs != 0) {
9088 // resizeInputBuffer_l should never be called with a non zero shared history if the
9089 // buffer was not already allocated
9090 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9091 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9092 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9093 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009094 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009095 return;
9096 }
9097 mRsmpInFrames = rsmpInFrames;
9098 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009099 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009100 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9101 // initialized
9102 if (mRsmpInFrames < minRsmpInFrames) {
9103 mRsmpInFrames = minRsmpInFrames;
9104 }
9105 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9106
9107 // TODO optimize audio capture buffer sizes ...
9108 // Here we calculate the size of the sliding buffer used as a source
9109 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9110 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9111 // be better to have it derived from the pipe depth in the long term.
9112 // The current value is higher than necessary. However it should not add to latency.
9113
9114 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9115 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9116
9117 void *rsmpInBuffer;
9118 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9119 // if posix_memalign fails, will segv here.
9120 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9121
9122 // Copy audio history if any from old buffer before freeing it
9123 if (previousRear != 0) {
9124 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9125 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9126
9127 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9128 previousFront &= previousRsmpInFramesP2 - 1;
9129 size_t part1 = previousRsmpInFramesP2 - previousFront;
9130 if (part1 > (size_t) unread) {
9131 part1 = unread;
9132 }
9133 if (part1 != 0) {
9134 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9135 part1 * mFrameSize);
9136 mRsmpInRear = part1;
9137 part1 = unread - part1;
9138 if (part1 != 0) {
9139 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9140 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9141 mRsmpInRear += part1;
9142 }
9143 }
9144 // Update front for all clients according to new rear
9145 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9146 } else {
9147 mRsmpInRear = 0;
9148 }
9149 free(mRsmpInBuffer);
9150 mRsmpInBuffer = rsmpInBuffer;
9151}
9152
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009153void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009154{
9155 Mutex::Autolock _l(mLock);
9156 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009157 if (record->getSource()) {
9158 mSource = record->getSource();
9159 }
Eric Laurent83b88082014-06-20 18:31:16 -07009160}
9161
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009162void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009163{
9164 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009165 if (mSource == record->getSource()) {
9166 mSource = mInput;
9167 }
Eric Laurent83b88082014-06-20 18:31:16 -07009168 destroyTrack_l(record);
9169}
9170
Mikhail Naganovdc769682018-05-04 15:34:08 -07009171void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07009172{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009173 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009174 config->role = AUDIO_PORT_ROLE_SINK;
9175 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9176 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009177 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9178 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9179 config->flags.input = mInput->flags;
9180 }
Eric Laurent83b88082014-06-20 18:31:16 -07009181}
Eric Laurent1c333e22014-05-20 10:48:17 -07009182
Eric Laurent6acd1d42017-01-04 14:23:29 -08009183// ----------------------------------------------------------------------------
9184// Mmap
9185// ----------------------------------------------------------------------------
9186
9187AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
9188 : mThread(thread)
9189{
Phil Burk9fabbf82017-08-03 12:02:00 -07009190 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009191}
9192
9193AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9194{
Phil Burk9fabbf82017-08-03 12:02:00 -07009195 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009196}
9197
9198status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9199 struct audio_mmap_buffer_info *info)
9200{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009201 return mThread->createMmapBuffer(minSizeFrames, info);
9202}
9203
9204status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9205{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009206 return mThread->getMmapPosition(position);
9207}
9208
jiabinb7d8c5a2020-08-26 17:24:52 -07009209status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9210 int64_t *timeNanos) {
9211 return mThread->getExternalPosition(position, timeNanos);
9212}
9213
Eric Laurenta54f1282017-07-01 19:39:32 -07009214status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009215 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009216
9217{
jiabind1f1cb62020-03-24 11:57:57 -07009218 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009219}
9220
9221status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9222{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009223 return mThread->stop(handle);
9224}
9225
Eric Laurent18b57012017-02-13 16:23:52 -08009226status_t AudioFlinger::MmapThreadHandle::standby()
9227{
Eric Laurent18b57012017-02-13 16:23:52 -08009228 return mThread->standby();
9229}
9230
Eric Laurent6acd1d42017-01-04 14:23:29 -08009231
9232AudioFlinger::MmapThread::MmapThread(
9233 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07009234 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009235 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009236 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009237 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009238 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009239 mActiveTracks(&this->mLocalLog),
9240 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9241 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009242{
Eric Laurent18b57012017-02-13 16:23:52 -08009243 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009244 readHalParameters_l();
9245}
9246
9247AudioFlinger::MmapThread::~MmapThread()
9248{
9249}
9250
9251void AudioFlinger::MmapThread::onFirstRef()
9252{
9253 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9254}
9255
9256void AudioFlinger::MmapThread::disconnect()
9257{
Eric Laurent331679c2018-04-16 17:03:16 -07009258 ActiveTracks<MmapTrack> activeTracks;
9259 {
9260 Mutex::Autolock _l(mLock);
9261 for (const sp<MmapTrack> &t : mActiveTracks) {
9262 activeTracks.add(t);
9263 }
9264 }
9265 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009266 stop(t->portId());
9267 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009268 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009269 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009270 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009271 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009272 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009273 }
9274}
9275
9276
9277void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9278 audio_stream_type_t streamType __unused,
9279 audio_session_t sessionId,
9280 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009281 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009282 audio_port_handle_t portId)
9283{
9284 mAttr = *attr;
9285 mSessionId = sessionId;
9286 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009287 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009288 mPortId = portId;
9289}
9290
9291status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9292 struct audio_mmap_buffer_info *info)
9293{
9294 if (mHalStream == 0) {
9295 return NO_INIT;
9296 }
Eric Laurent18b57012017-02-13 16:23:52 -08009297 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009298 return mHalStream->createMmapBuffer(minSizeFrames, info);
9299}
9300
9301status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9302{
9303 if (mHalStream == 0) {
9304 return NO_INIT;
9305 }
9306 return mHalStream->getMmapPosition(position);
9307}
9308
Eric Laurent331679c2018-04-16 17:03:16 -07009309status_t AudioFlinger::MmapThread::exitStandby()
9310{
9311 status_t ret = mHalStream->start();
9312 if (ret != NO_ERROR) {
9313 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9314 return ret;
9315 }
Andy Hungcf10d742020-04-28 15:38:24 -07009316 if (mStandby) {
9317 mThreadMetrics.logBeginInterval();
9318 mStandby = false;
9319 }
Eric Laurent331679c2018-04-16 17:03:16 -07009320 return NO_ERROR;
9321}
9322
Eric Laurenta54f1282017-07-01 19:39:32 -07009323status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009324 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009325 audio_port_handle_t *handle)
9326{
Eric Laurenta54f1282017-07-01 19:39:32 -07009327 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009328 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009329 if (mHalStream == 0) {
9330 return NO_INIT;
9331 }
9332
9333 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009334
Eric Laurenta54f1282017-07-01 19:39:32 -07009335 if (*handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009336 // For the first track, reuse portId and session allocated when the stream was opened.
9337 ret = exitStandby();
9338 if (ret == NO_ERROR) {
9339 acquireWakeLock();
9340 }
9341 return ret;
Eric Laurenta54f1282017-07-01 19:39:32 -07009342 }
9343
9344 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9345
9346 audio_io_handle_t io = mId;
9347 if (isOutput()) {
9348 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9349 config.sample_rate = mSampleRate;
9350 config.channel_mask = mChannelMask;
9351 config.format = mFormat;
9352 audio_stream_type_t stream = streamType();
9353 audio_output_flags_t flags =
9354 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009355 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009356 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07009357 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9358 mSessionId,
9359 &stream,
Svet Ganov33761132021-05-13 22:51:08 +00009360 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009361 &config,
9362 flags,
9363 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009364 &portId,
9365 &secondaryOutputs);
9366 ALOGD_IF(!secondaryOutputs.empty(),
9367 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009368 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009369 audio_config_base_t config;
9370 config.sample_rate = mSampleRate;
9371 config.channel_mask = mChannelMask;
9372 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009373 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009374 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009375 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009376 mSessionId,
Svet Ganov33761132021-05-13 22:51:08 +00009377 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009378 &config,
9379 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9380 &deviceId,
9381 &portId);
9382 }
9383 // APM should not chose a different input or output stream for the same set of attributes
9384 // and audo configuration
9385 if (ret != NO_ERROR || io != mId) {
9386 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9387 __FUNCTION__, ret, io, mId);
9388 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009389 }
9390
9391 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009392 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009393 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08009394 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009395 }
9396
Eric Laurent331679c2018-04-16 17:03:16 -07009397 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009398 // abort if start is rejected by audio policy manager
9399 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009400 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009401 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009402 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009403 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009404 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009405 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009406 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009407 }
Eric Laurent331679c2018-04-16 17:03:16 -07009408 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009409 } else {
9410 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009411 }
9412 return PERMISSION_DENIED;
9413 }
9414
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009415 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009416 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +00009417 mChannelMask, mSessionId, isOutput(),
9418 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009419 IPCThreadState::self()->getCallingPid(), portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009420
Eric Laurent4eb58f12018-12-07 16:41:02 -08009421 if (isOutput()) {
9422 // force volume update when a new track is added
9423 mHalVolFloat = -1.0f;
9424 } else if (!track->isSilenced_l()) {
9425 for (const sp<MmapTrack> &t : mActiveTracks) {
Svet Ganov33761132021-05-13 22:51:08 +00009426 if (t->isSilenced_l() && t->uid() != client.attributionSource.uid)
Eric Laurent4eb58f12018-12-07 16:41:02 -08009427 t->invalidate();
9428 }
9429 }
9430
9431
Eric Laurent6acd1d42017-01-04 14:23:29 -08009432 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009433 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009434 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02009435 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009436 chain->incTrackCnt();
9437 chain->incActiveTrackCnt();
9438 }
9439
Andy Hungc2b11cb2020-04-22 09:04:01 -07009440 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009441 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009442 broadcast_l();
9443
Eric Laurenta54f1282017-07-01 19:39:32 -07009444 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009445
9446 return NO_ERROR;
9447}
9448
9449status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9450{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009451 ALOGV("%s handle %d", __FUNCTION__, handle);
9452
9453 if (mHalStream == 0) {
9454 return NO_INIT;
9455 }
9456
Eric Laurenta54f1282017-07-01 19:39:32 -07009457 if (handle == mPortId) {
9458 mHalStream->stop();
Phil Burk98ab4082020-09-25 21:46:34 +00009459 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009460 return NO_ERROR;
9461 }
9462
Eric Laurent331679c2018-04-16 17:03:16 -07009463 Mutex::Autolock _l(mLock);
9464
Eric Laurent6acd1d42017-01-04 14:23:29 -08009465 sp<MmapTrack> track;
9466 for (const sp<MmapTrack> &t : mActiveTracks) {
9467 if (handle == t->portId()) {
9468 track = t;
9469 break;
9470 }
9471 }
9472 if (track == 0) {
9473 return BAD_VALUE;
9474 }
9475
9476 mActiveTracks.remove(track);
9477
Eric Laurent331679c2018-04-16 17:03:16 -07009478 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009479 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009480 AudioSystem::stopOutput(track->portId());
9481 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009482 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009483 AudioSystem::stopInput(track->portId());
9484 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009485 }
Eric Laurent331679c2018-04-16 17:03:16 -07009486 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009487
9488 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9489 if (chain != 0) {
9490 chain->decActiveTrackCnt();
9491 chain->decTrackCnt();
9492 }
9493
9494 broadcast_l();
9495
Eric Laurent6acd1d42017-01-04 14:23:29 -08009496 return NO_ERROR;
9497}
9498
Eric Laurent18b57012017-02-13 16:23:52 -08009499status_t AudioFlinger::MmapThread::standby()
9500{
9501 ALOGV("%s", __FUNCTION__);
9502
9503 if (mHalStream == 0) {
9504 return NO_INIT;
9505 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009506 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009507 return INVALID_OPERATION;
9508 }
9509 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009510 if (!mStandby) {
9511 mThreadMetrics.logEndInterval();
9512 mStandby = true;
9513 }
Eric Laurent18b57012017-02-13 16:23:52 -08009514 releaseWakeLock();
9515 return NO_ERROR;
9516}
9517
Eric Laurent6acd1d42017-01-04 14:23:29 -08009518
9519void AudioFlinger::MmapThread::readHalParameters_l()
9520{
9521 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9522 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9523 mFormat = mHALFormat;
9524 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9525 result = mHalStream->getFrameSize(&mFrameSize);
9526 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009527 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9528 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009529 result = mHalStream->getBufferSize(&mBufferSize);
9530 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9531 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009532
Andy Hungcf10d742020-04-28 15:38:24 -07009533 // TODO: make a readHalParameters call?
9534 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009535 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9536 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9537 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9538 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9539 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9540 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9541 /*
9542 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9543 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9544 (int32_t)mHapticChannelMask)
9545 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9546 (int32_t)mHapticChannelCount)
9547 */
9548 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9549 formatToString(mHALFormat).c_str())
9550 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9551 (int32_t)mFrameCount) // sic - added HAL
9552 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009553}
9554
9555bool AudioFlinger::MmapThread::threadLoop()
9556{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009557 checkSilentMode_l();
9558
9559 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9560
9561 while (!exitPending())
9562 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009563 Vector< sp<EffectChain> > effectChains;
9564
Andy Hung13850be2019-03-14 11:33:09 -07009565 { // under Thread lock
9566 Mutex::Autolock _l(mLock);
9567
Eric Laurent6acd1d42017-01-04 14:23:29 -08009568 if (mSignalPending) {
9569 // A signal was raised while we were unlocked
9570 mSignalPending = false;
9571 } else {
9572 if (mConfigEvents.isEmpty()) {
9573 // we're about to wait, flush the binder command buffer
9574 IPCThreadState::self()->flushCommands();
9575
9576 if (exitPending()) {
9577 break;
9578 }
9579
Eric Laurent6acd1d42017-01-04 14:23:29 -08009580 // wait until we have something to do...
9581 ALOGV("%s going to sleep", myName.string());
9582 mWaitWorkCV.wait(mLock);
9583 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009584
9585 checkSilentMode_l();
9586
9587 continue;
9588 }
9589 }
9590
9591 processConfigEvents_l();
9592
9593 processVolume_l();
9594
9595 checkInvalidTracks_l();
9596
9597 mActiveTracks.updatePowerState(this);
9598
Kevin Rocard069c2712018-03-29 19:09:14 -07009599 updateMetadata_l();
9600
Eric Laurent6acd1d42017-01-04 14:23:29 -08009601 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009602 } // release Thread lock
9603
Eric Laurent6acd1d42017-01-04 14:23:29 -08009604 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009605 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009606 }
Andy Hung13850be2019-03-14 11:33:09 -07009607
9608 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009609 unlockEffectChains(effectChains);
9610 // Effect chains will be actually deleted here if they were removed from
9611 // mEffectChains list during mixing or effects processing
9612 }
9613
9614 threadLoop_exit();
9615
9616 if (!mStandby) {
9617 threadLoop_standby();
9618 mStandby = true;
9619 }
9620
Eric Laurent6acd1d42017-01-04 14:23:29 -08009621 ALOGV("Thread %p type %d exiting", this, mType);
9622 return false;
9623}
9624
9625// checkForNewParameter_l() must be called with ThreadBase::mLock held
9626bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9627 status_t& status)
9628{
9629 AudioParameter param = AudioParameter(keyValuePair);
9630 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009631 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009632 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009633 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009634 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009635 if (sendToHal) {
9636 status = mHalStream->setParameters(keyValuePair);
9637 } else {
9638 status = NO_ERROR;
9639 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009640
9641 return false;
9642}
9643
9644String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9645{
9646 Mutex::Autolock _l(mLock);
9647 String8 out_s8;
9648 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
9649 return out_s8;
9650 }
9651 return String8();
9652}
9653
Eric Laurent09f1ed22019-04-24 17:45:17 -07009654void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
9655 audio_port_handle_t portId __unused) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009656 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
9657
9658 desc->mIoHandle = mId;
9659
9660 switch (event) {
9661 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009662 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009663 case AUDIO_INPUT_CONFIG_CHANGED:
9664 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009665 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009666 case AUDIO_OUTPUT_CONFIG_CHANGED:
9667 desc->mPatch = mPatch;
9668 desc->mChannelMask = mChannelMask;
9669 desc->mSamplingRate = mSampleRate;
9670 desc->mFormat = mFormat;
9671 desc->mFrameCount = mFrameCount;
9672 desc->mFrameCountHAL = mFrameCount;
9673 desc->mLatency = 0;
9674 break;
9675
9676 case AUDIO_INPUT_CLOSED:
9677 case AUDIO_OUTPUT_CLOSED:
9678 default:
9679 break;
9680 }
9681 mAudioFlinger->ioConfigChanged(event, desc, pid);
9682}
9683
9684status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
9685 audio_patch_handle_t *handle)
9686{
9687 status_t status = NO_ERROR;
9688
9689 // store new device and send to effects
9690 audio_devices_t type = AUDIO_DEVICE_NONE;
9691 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -07009692 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
9693 AudioDeviceTypeAddr sourceDeviceTypeAddr;
9694 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009695 if (isOutput()) {
9696 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07009697 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
9698 && !mAudioHwDev->supportsAudioPatches(),
9699 "Enumerated device type(%#x) must not be used "
9700 "as it does not support audio patches",
9701 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07009702 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07009703 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
9704 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009705 }
9706 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009707 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009708 } else {
9709 type = patch->sources[0].ext.device.type;
9710 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009711 numDevices = mPatch.num_sources;
9712 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009713 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009714 }
9715
9716 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009717 if (isOutput()) {
9718 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
9719 } else {
9720 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
9721 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009722 }
9723
jiabinc52b1ff2019-10-31 17:20:42 -07009724 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009725 // store new source and send to effects
9726 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9727 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
9728 for (size_t i = 0; i < mEffectChains.size(); i++) {
9729 mEffectChains[i]->setAudioSource_l(mAudioSource);
9730 }
9731 }
9732 }
9733
9734 if (mAudioHwDev->supportsAudioPatches()) {
9735 status = mHalDevice->createAudioPatch(patch->num_sources,
9736 patch->sources,
9737 patch->num_sinks,
9738 patch->sinks,
9739 handle);
9740 } else {
9741 char *address;
9742 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
9743 //FIXME: we only support address on first sink with HAL version < 3.0
9744 address = audio_device_address_to_parameter(
9745 patch->sinks[0].ext.device.type,
9746 patch->sinks[0].ext.device.address);
9747 } else {
9748 address = (char *)calloc(1, 1);
9749 }
9750 AudioParameter param = AudioParameter(String8(address));
9751 free(address);
9752 param.addInt(String8(AudioParameter::keyRouting), (int)type);
9753 if (!isOutput()) {
9754 param.addInt(String8(AudioParameter::keyInputSource),
9755 (int)patch->sinks[0].ext.mix.usecase.source);
9756 }
9757 status = mHalStream->setParameters(param.toString());
9758 *handle = AUDIO_PATCH_HANDLE_NONE;
9759 }
9760
jiabinc52b1ff2019-10-31 17:20:42 -07009761 if (numDevices == 0 || mDeviceId != deviceId) {
9762 if (isOutput()) {
9763 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
9764 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07009765 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -07009766 } else {
9767 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
9768 mInDeviceTypeAddr = sourceDeviceTypeAddr;
9769 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08009770 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009771 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009772 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08009773 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07009774 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009775 }
jiabinc52b1ff2019-10-31 17:20:42 -07009776 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009777 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009778 }
9779 return status;
9780}
9781
9782status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9783{
9784 status_t status = NO_ERROR;
9785
jiabinc52b1ff2019-10-31 17:20:42 -07009786 mPatch = audio_patch{};
9787 mOutDeviceTypeAddrs.clear();
9788 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009789
9790 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9791 supportsAudioPatches : false;
9792
9793 if (supportsAudioPatches) {
9794 status = mHalDevice->releaseAudioPatch(handle);
9795 } else {
9796 AudioParameter param;
9797 param.addInt(String8(AudioParameter::keyRouting), 0);
9798 status = mHalStream->setParameters(param.toString());
9799 }
9800 return status;
9801}
9802
Mikhail Naganovdc769682018-05-04 15:34:08 -07009803void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009804{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009805 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009806 if (isOutput()) {
9807 config->role = AUDIO_PORT_ROLE_SOURCE;
9808 config->ext.mix.hw_module = mAudioHwDev->handle();
9809 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9810 } else {
9811 config->role = AUDIO_PORT_ROLE_SINK;
9812 config->ext.mix.hw_module = mAudioHwDev->handle();
9813 config->ext.mix.usecase.source = mAudioSource;
9814 }
9815}
9816
9817status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9818{
9819 audio_session_t session = chain->sessionId();
9820
9821 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9822 // Attach all tracks with same session ID to this chain.
9823 // indicate all active tracks in the chain
9824 for (const sp<MmapTrack> &track : mActiveTracks) {
9825 if (session == track->sessionId()) {
9826 chain->incTrackCnt();
9827 chain->incActiveTrackCnt();
9828 }
9829 }
9830
9831 chain->setThread(this);
9832 chain->setInBuffer(nullptr);
9833 chain->setOutBuffer(nullptr);
9834 chain->syncHalEffectsState();
9835
9836 mEffectChains.add(chain);
9837 checkSuspendOnAddEffectChain_l(chain);
9838 return NO_ERROR;
9839}
9840
9841size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9842{
9843 audio_session_t session = chain->sessionId();
9844
9845 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9846
9847 for (size_t i = 0; i < mEffectChains.size(); i++) {
9848 if (chain == mEffectChains[i]) {
9849 mEffectChains.removeAt(i);
9850 // detach all active tracks from the chain
9851 // detach all tracks with same session ID from this chain
9852 for (const sp<MmapTrack> &track : mActiveTracks) {
9853 if (session == track->sessionId()) {
9854 chain->decActiveTrackCnt();
9855 chain->decTrackCnt();
9856 }
9857 }
9858 break;
9859 }
9860 }
9861 return mEffectChains.size();
9862}
9863
Eric Laurent6acd1d42017-01-04 14:23:29 -08009864void AudioFlinger::MmapThread::threadLoop_standby()
9865{
9866 mHalStream->standby();
9867}
9868
9869void AudioFlinger::MmapThread::threadLoop_exit()
9870{
Phil Burk7dce7282017-09-27 13:51:41 -07009871 // Do not call callback->onTearDown() because it is redundant for thread exit
9872 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009873}
9874
9875status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9876{
9877 return BAD_VALUE;
9878}
9879
9880bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9881{
9882 return false;
9883}
9884
9885status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9886 const effect_descriptor_t *desc, audio_session_t sessionId)
9887{
9888 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -08009889 if (audio_is_global_session(sessionId)) {
9890 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -08009891 desc->name, mThreadName);
9892 return BAD_VALUE;
9893 }
9894
9895 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9896 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9897 desc->name);
9898 return BAD_VALUE;
9899 }
9900 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009901 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9902 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009903 return BAD_VALUE;
9904 }
9905
9906 // Only allow effects without processing load or latency
9907 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9908 return BAD_VALUE;
9909 }
9910
jiabineb3bda02020-06-30 14:07:03 -07009911 if (EffectModule::isHapticGenerator(&desc->type)) {
9912 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
9913 return BAD_VALUE;
9914 }
9915
Eric Laurent6acd1d42017-01-04 14:23:29 -08009916 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009917}
9918
9919void AudioFlinger::MmapThread::checkInvalidTracks_l()
9920{
9921 for (const sp<MmapTrack> &track : mActiveTracks) {
9922 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009923 sp<MmapStreamCallback> callback = mCallback.promote();
9924 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009925 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009926 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009927 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009928 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9929 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9930 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009931 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009932 }
9933 }
9934}
9935
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009936void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009937{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009938 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9939 mAttr.content_type, mAttr.usage, mAttr.source);
9940 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009941 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009942 dprintf(fd, " No active clients\n");
9943 }
9944}
9945
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009946void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009947{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009948 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009949 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009950 dprintf(fd, " %zu Tracks\n", numtracks);
9951 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009952 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009953 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009954 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009955 for (size_t i = 0; i < numtracks ; ++i) {
9956 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009957 result.append(prefix);
9958 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009959 }
9960 } else {
9961 dprintf(fd, "\n");
9962 }
9963 write(fd, result.string(), result.size());
9964}
9965
9966AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9967 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009968 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07009969 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009970 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009971 mStreamVolume(1.0),
9972 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009973 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009974{
9975 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9976 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9977 mMasterVolume = audioFlinger->masterVolume_l();
9978 mMasterMute = audioFlinger->masterMute_l();
9979 if (mAudioHwDev) {
9980 if (mAudioHwDev->canSetMasterVolume()) {
9981 mMasterVolume = 1.0;
9982 }
9983
9984 if (mAudioHwDev->canSetMasterMute()) {
9985 mMasterMute = false;
9986 }
9987 }
9988}
9989
9990void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9991 audio_stream_type_t streamType,
9992 audio_session_t sessionId,
9993 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009994 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009995 audio_port_handle_t portId)
9996{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009997 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009998 mStreamType = streamType;
9999}
10000
10001AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
10002{
10003 Mutex::Autolock _l(mLock);
10004 AudioStreamOut *output = mOutput;
10005 mOutput = NULL;
10006 return output;
10007}
10008
10009void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
10010{
10011 Mutex::Autolock _l(mLock);
10012 // Don't apply master volume in SW if our HAL can do it for us.
10013 if (mAudioHwDev &&
10014 mAudioHwDev->canSetMasterVolume()) {
10015 mMasterVolume = 1.0;
10016 } else {
10017 mMasterVolume = value;
10018 }
10019}
10020
10021void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
10022{
10023 Mutex::Autolock _l(mLock);
10024 // Don't apply master mute in SW if our HAL can do it for us.
10025 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10026 mMasterMute = false;
10027 } else {
10028 mMasterMute = muted;
10029 }
10030}
10031
10032void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
10033{
10034 Mutex::Autolock _l(mLock);
10035 if (stream == mStreamType) {
10036 mStreamVolume = value;
10037 broadcast_l();
10038 }
10039}
10040
10041float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
10042{
10043 Mutex::Autolock _l(mLock);
10044 if (stream == mStreamType) {
10045 return mStreamVolume;
10046 }
10047 return 0.0f;
10048}
10049
10050void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
10051{
10052 Mutex::Autolock _l(mLock);
10053 if (stream == mStreamType) {
10054 mStreamMute= muted;
10055 broadcast_l();
10056 }
10057}
10058
10059void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
10060{
10061 Mutex::Autolock _l(mLock);
10062 if (streamType == mStreamType) {
10063 for (const sp<MmapTrack> &track : mActiveTracks) {
10064 track->invalidate();
10065 }
10066 broadcast_l();
10067 }
10068}
10069
10070void AudioFlinger::MmapPlaybackThread::processVolume_l()
10071{
10072 float volume;
10073
10074 if (mMasterMute || mStreamMute) {
10075 volume = 0;
10076 } else {
10077 volume = mMasterVolume * mStreamVolume;
10078 }
10079
10080 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010081
10082 // Convert volumes from float to 8.24
10083 uint32_t vol = (uint32_t)(volume * (1 << 24));
10084
10085 // Delegate volume control to effect in track effect chain if needed
10086 // only one effect chain can be present on DirectOutputThread, so if
10087 // there is one, the track is connected to it
10088 if (!mEffectChains.isEmpty()) {
10089 mEffectChains[0]->setVolume_l(&vol, &vol);
10090 volume = (float)vol / (1 << 24);
10091 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010092 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010093 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10094 mHalVolFloat = volume; // HW volume control worked, so update value.
10095 mNoCallbackWarningCount = 0;
10096 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010097 sp<MmapStreamCallback> callback = mCallback.promote();
10098 if (callback != 0) {
10099 int channelCount;
10100 if (isOutput()) {
10101 channelCount = audio_channel_count_from_out_mask(mChannelMask);
10102 } else {
10103 channelCount = audio_channel_count_from_in_mask(mChannelMask);
10104 }
10105 Vector<float> values;
10106 for (int i = 0; i < channelCount; i++) {
10107 values.add(volume);
10108 }
Phil Burk56ecf3e2018-03-12 15:38:17 -070010109 mHalVolFloat = volume; // SW volume control worked, so update value.
10110 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010111 mLock.unlock();
10112 callback->onVolumeChanged(mChannelMask, values);
10113 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010114 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010115 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10116 ALOGW("Could not set MMAP stream volume: no volume callback!");
10117 mNoCallbackWarningCount++;
10118 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010119 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010120 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010121 for (const sp<MmapTrack> &track : mActiveTracks) {
10122 track->setMetadataHasChanged();
10123 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010124 }
10125}
10126
Kevin Rocard069c2712018-03-29 19:09:14 -070010127void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
10128{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010129 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10130 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010131 }
10132 StreamOutHalInterface::SourceMetadata metadata;
10133 for (const sp<MmapTrack> &track : mActiveTracks) {
10134 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010135 playback_track_metadata_v7_t trackMetadata;
10136 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010137 .usage = track->attributes().usage,
10138 .content_type = track->attributes().content_type,
10139 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010140 };
10141 trackMetadata.channel_mask = track->channelMask(),
10142 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10143 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010144 }
10145 mOutput->stream->updateSourceMetadata(metadata);
10146}
10147
Eric Laurent6acd1d42017-01-04 14:23:29 -080010148void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
10149{
10150 if (!mMasterMute) {
10151 char value[PROPERTY_VALUE_MAX];
10152 if (property_get("ro.audio.silent", value, "0") > 0) {
10153 char *endptr;
10154 unsigned long ul = strtoul(value, &endptr, 0);
10155 if (*endptr == '\0' && ul != 0) {
10156 ALOGD("Silence is golden");
10157 // The setprop command will not allow a property to be changed after
10158 // the first time it is set, so we don't have to worry about un-muting.
10159 setMasterMute_l(true);
10160 }
10161 }
10162 }
10163}
10164
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010165void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
10166{
10167 MmapThread::toAudioPortConfig(config);
10168 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10169 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10170 config->flags.output = mOutput->flags;
10171 }
10172}
10173
jiabinb7d8c5a2020-08-26 17:24:52 -070010174status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
10175 int64_t *timeNanos)
10176{
10177 if (mOutput == nullptr) {
10178 return NO_INIT;
10179 }
10180 struct timespec timestamp;
10181 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10182 if (status == NO_ERROR) {
10183 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10184 }
10185 return status;
10186}
10187
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010188void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010189{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010190 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010191
Glenn Kastend3bb6452016-12-05 18:14:37 -080010192 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10193 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010194 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10195}
10196
10197AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10198 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010199 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010200 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010201 mInput(input)
10202{
10203 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10204 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10205}
10206
Eric Laurent331679c2018-04-16 17:03:16 -070010207status_t AudioFlinger::MmapCaptureThread::exitStandby()
10208{
Phil Burkf054fc32018-12-06 09:45:59 -080010209 {
10210 // mInput might have been cleared by clearInput()
10211 Mutex::Autolock _l(mLock);
10212 if (mInput != nullptr && mInput->stream != nullptr) {
10213 mInput->stream->setGain(1.0f);
10214 }
10215 }
Eric Laurent331679c2018-04-16 17:03:16 -070010216 return MmapThread::exitStandby();
10217}
10218
Eric Laurent6acd1d42017-01-04 14:23:29 -080010219AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10220{
10221 Mutex::Autolock _l(mLock);
10222 AudioStreamIn *input = mInput;
10223 mInput = NULL;
10224 return input;
10225}
Kevin Rocard069c2712018-03-29 19:09:14 -070010226
Eric Laurent331679c2018-04-16 17:03:16 -070010227
10228void AudioFlinger::MmapCaptureThread::processVolume_l()
10229{
10230 bool changed = false;
10231 bool silenced = false;
10232
10233 sp<MmapStreamCallback> callback = mCallback.promote();
10234 if (callback == 0) {
10235 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10236 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10237 mNoCallbackWarningCount++;
10238 }
10239 }
10240
10241 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10242 // track is silenced and unmute otherwise
10243 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10244 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10245 changed = true;
10246 silenced = mActiveTracks[i]->isSilenced_l();
10247 }
10248 }
10249
10250 if (changed) {
10251 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10252 }
10253}
10254
Kevin Rocard069c2712018-03-29 19:09:14 -070010255void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10256{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010257 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10258 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010259 }
10260 StreamInHalInterface::SinkMetadata metadata;
10261 for (const sp<MmapTrack> &track : mActiveTracks) {
10262 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010263 record_track_metadata_v7_t trackMetadata;
10264 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010265 .source = track->attributes().source,
10266 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010267 };
10268 trackMetadata.channel_mask = track->channelMask(),
10269 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10270 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010271 }
10272 mInput->stream->updateSinkMetadata(metadata);
10273}
10274
Eric Laurent5ada82e2019-08-29 17:53:54 -070010275void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010276{
10277 Mutex::Autolock _l(mLock);
10278 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010279 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010280 mActiveTracks[i]->setSilenced_l(silenced);
10281 broadcast_l();
10282 }
10283 }
10284}
10285
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010286void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10287{
10288 MmapThread::toAudioPortConfig(config);
10289 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10290 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10291 config->flags.input = mInput->flags;
10292 }
10293}
10294
jiabinb7d8c5a2020-08-26 17:24:52 -070010295status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10296 uint64_t *position, int64_t *timeNanos)
10297{
10298 if (mInput == nullptr) {
10299 return NO_INIT;
10300 }
10301 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10302}
10303
Glenn Kasten63238ef2015-03-02 15:50:29 -080010304} // namespace android