blob: 357e4321ec852a7910ef8a331f784f7c5a12d72e [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>
27#include <string>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080030#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080031#include <cutils/properties.h>
jiabinc52b1ff2019-10-31 17:20:42 -070032#include <media/AudioContainers.h>
33#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070034#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070035#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080036#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070037#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080038#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080039#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040
41#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070042#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010043#include <audio_utils/Balance.h>
jiabin245cdd92018-12-07 17:55:15 -080044#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080045#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080047#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070048#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070049#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070050#include <system/audio_effects/effect_ns.h>
51#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080053
54// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070055#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080056#include <media/nbaio/AudioStreamOutSink.h>
57#include <media/nbaio/MonoPipe.h>
58#include <media/nbaio/MonoPipeReader.h>
59#include <media/nbaio/Pipe.h>
60#include <media/nbaio/PipeReader.h>
61#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080062#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080063
Mikhail Naganov2996f672019-04-18 12:29:59 -070064#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080065#include <powermanager/PowerManager.h>
66
Kevin Rocard7588ff42018-01-08 11:11:30 -080067#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070068#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080069
Eric Laurent81784c32012-11-19 14:55:58 -080070#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080071#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070072#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070073#include <mediautils/SchedulingPolicyService.h>
74#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080075
Eric Laurent81784c32012-11-19 14:55:58 -080076#ifdef ADD_BATTERY_DATA
77#include <media/IMediaPlayerService.h>
78#include <media/IMediaDeathNotifier.h>
79#endif
80
Eric Laurent81784c32012-11-19 14:55:58 -080081#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070082#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080083#include <cpustats/ThreadCpuUsage.h>
84#endif
85
Glenn Kastenc05b8d72016-03-24 09:48:17 -070086#include "AutoPark.h"
87
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080088#include <pthread.h>
89#include "TypedLogger.h"
90
Eric Laurent81784c32012-11-19 14:55:58 -080091// ----------------------------------------------------------------------------
92
93// Note: the following macro is used for extremely verbose logging message. In
94// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
95// 0; but one side effect of this is to turn all LOGV's as well. Some messages
96// are so verbose that we want to suppress them even when we have ALOG_ASSERT
97// turned on. Do not uncomment the #def below unless you really know what you
98// are doing and want to see all of the extremely verbose messages.
99//#define VERY_VERY_VERBOSE_LOGGING
100#ifdef VERY_VERY_VERBOSE_LOGGING
101#define ALOGVV ALOGV
102#else
103#define ALOGVV(a...) do { } while(0)
104#endif
105
Andy Hung6770c6f2015-04-07 13:43:36 -0700106// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700107#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -0700108template <typename T>
109static inline T min(const T& a, const T& b)
110{
111 return a < b ? a : b;
112}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700113
Eric Laurent81784c32012-11-19 14:55:58 -0800114namespace android {
115
116// retry counts for buffer fill timeout
117// 50 * ~20msecs = 1 second
118static const int8_t kMaxTrackRetries = 50;
119static const int8_t kMaxTrackStartupRetries = 50;
120// allow less retry attempts on direct output thread.
121// direct outputs can be a scarce resource in audio hardware and should
122// be released as quickly as possible.
123static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700124
Eric Laurent51716182016-02-29 18:00:56 -0800125
Eric Laurent81784c32012-11-19 14:55:58 -0800126
127// don't warn about blocked writes or record buffer overflows more often than this
128static const nsecs_t kWarningThrottleNs = seconds(5);
129
130// RecordThread loop sleep time upon application overrun or audio HAL read error
131static const int kRecordThreadSleepUs = 5000;
132
Eric Laurent10351942014-05-08 18:49:52 -0700133// maximum time to wait in sendConfigEvent_l() for a status to be received
134static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800135
136// minimum sleep time for the mixer thread loop when tracks are active but in underrun
137static const uint32_t kMinThreadSleepTimeUs = 5000;
138// maximum divider applied to the active sleep time in the mixer thread loop
139static const uint32_t kMaxThreadSleepTimeShift = 2;
140
Andy Hung09a50072014-02-27 14:30:47 -0800141// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700142// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800143static const uint32_t kMinNormalSinkBufferSizeMs = 20;
144// maximum normal sink buffer size
145static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800146
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700147// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
148// FIXME This should be based on experimentally observed scheduling jitter
149static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
150
Eric Laurent972a1732013-09-04 09:42:59 -0700151// Offloaded output thread standby delay: allows track transition without going to standby
152static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
153
Eric Laurent51716182016-02-29 18:00:56 -0800154// Direct output thread minimum sleep time in idle or active(underrun) state
155static const nsecs_t kDirectMinSleepTimeUs = 10000;
156
Glenn Kasten1b291842016-07-18 14:55:21 -0700157// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
158// balance between power consumption and latency, and allows threads to be scheduled reliably
159// by the CFS scheduler.
160// FIXME Express other hardcoded references to 20ms with references to this constant and move
161// it appropriately.
162#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800163
Eric Laurent81784c32012-11-19 14:55:58 -0800164// Whether to use fast mixer
165static const enum {
166 FastMixer_Never, // never initialize or use: for debugging only
167 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
168 // normal mixer multiplier is 1
169 FastMixer_Static, // initialize if needed, then use all the time if initialized,
170 // multiplier is calculated based on min & max normal mixer buffer size
171 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
172 // multiplier is calculated based on min & max normal mixer buffer size
173 // FIXME for FastMixer_Dynamic:
174 // Supporting this option will require fixing HALs that can't handle large writes.
175 // For example, one HAL implementation returns an error from a large write,
176 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
177 // We could either fix the HAL implementations, or provide a wrapper that breaks
178 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
179} kUseFastMixer = FastMixer_Static;
180
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700181// Whether to use fast capture
182static const enum {
183 FastCapture_Never, // never initialize or use: for debugging only
184 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
185 FastCapture_Static, // initialize if needed, then use all the time if initialized
186} kUseFastCapture = FastCapture_Static;
187
Eric Laurent81784c32012-11-19 14:55:58 -0800188// Priorities for requestPriority
189static const int kPriorityAudioApp = 2;
190static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700191static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800192
Glenn Kastenea38ee72016-04-18 11:08:01 -0700193// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
194// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
195// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700196
197// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800198static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800199
Glenn Kasten03490092014-05-27 12:30:54 -0700200// The minimum and maximum allowed values
201static const int kFastTrackMultiplierMin = 1;
202static const int kFastTrackMultiplierMax = 2;
203
204// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
205static int sFastTrackMultiplier = kFastTrackMultiplier;
206
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700207// See Thread::readOnlyHeap().
208// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
209// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
210// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700211static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700212
Eric Laurent81784c32012-11-19 14:55:58 -0800213// ----------------------------------------------------------------------------
214
Glenn Kasten03490092014-05-27 12:30:54 -0700215static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
216
217static void sFastTrackMultiplierInit()
218{
219 char value[PROPERTY_VALUE_MAX];
220 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
221 char *endptr;
222 unsigned long ul = strtoul(value, &endptr, 0);
223 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
224 sFastTrackMultiplier = (int) ul;
225 }
226 }
227}
228
229// ----------------------------------------------------------------------------
230
Eric Laurent81784c32012-11-19 14:55:58 -0800231#ifdef ADD_BATTERY_DATA
232// To collect the amplifier usage
233static void addBatteryData(uint32_t params) {
234 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
235 if (service == NULL) {
236 // it already logged
237 return;
238 }
239
240 service->addBatteryData(params);
241}
242#endif
243
Andy Hung3f0c9022016-01-15 17:49:46 -0800244// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
245struct {
246 // call when you acquire a partial wakelock
247 void acquire(const sp<IBinder> &wakeLockToken) {
248 pthread_mutex_lock(&mLock);
249 if (wakeLockToken.get() == nullptr) {
250 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
251 } else {
252 if (mCount == 0) {
253 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
254 }
255 ++mCount;
256 }
257 pthread_mutex_unlock(&mLock);
258 }
259
260 // call when you release a partial wakelock.
261 void release(const sp<IBinder> &wakeLockToken) {
262 if (wakeLockToken.get() == nullptr) {
263 return;
264 }
265 pthread_mutex_lock(&mLock);
266 if (--mCount < 0) {
267 ALOGE("negative wakelock count");
268 mCount = 0;
269 }
270 pthread_mutex_unlock(&mLock);
271 }
272
273 // retrieves the boottime timebase offset from monotonic.
274 int64_t getBoottimeOffset() {
275 pthread_mutex_lock(&mLock);
276 int64_t boottimeOffset = mBoottimeOffset;
277 pthread_mutex_unlock(&mLock);
278 return boottimeOffset;
279 }
280
281 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
282 // and the selected timebase.
283 // Currently only TIMEBASE_BOOTTIME is allowed.
284 //
285 // This only needs to be called upon acquiring the first partial wakelock
286 // after all other partial wakelocks are released.
287 //
288 // We do an empirical measurement of the offset rather than parsing
289 // /proc/timer_list since the latter is not a formal kernel ABI.
290 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
291 int clockbase;
292 switch (timebase) {
293 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
294 clockbase = SYSTEM_TIME_BOOTTIME;
295 break;
296 default:
297 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
298 break;
299 }
300 // try three times to get the clock offset, choose the one
301 // with the minimum gap in measurements.
302 const int tries = 3;
303 nsecs_t bestGap, measured;
304 for (int i = 0; i < tries; ++i) {
305 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
306 const nsecs_t tbase = systemTime(clockbase);
307 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
308 const nsecs_t gap = tmono2 - tmono;
309 if (i == 0 || gap < bestGap) {
310 bestGap = gap;
311 measured = tbase - ((tmono + tmono2) >> 1);
312 }
313 }
314
315 // to avoid micro-adjusting, we don't change the timebase
316 // unless it is significantly different.
317 //
318 // Assumption: It probably takes more than toleranceNs to
319 // suspend and resume the device.
320 static int64_t toleranceNs = 10000; // 10 us
321 if (llabs(*offset - measured) > toleranceNs) {
322 ALOGV("Adjusting timebase offset old: %lld new: %lld",
323 (long long)*offset, (long long)measured);
324 *offset = measured;
325 }
326 }
327
328 pthread_mutex_t mLock;
329 int32_t mCount;
330 int64_t mBoottimeOffset;
331} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800332
333// ----------------------------------------------------------------------------
334// CPU Stats
335// ----------------------------------------------------------------------------
336
337class CpuStats {
338public:
339 CpuStats();
340 void sample(const String8 &title);
341#ifdef DEBUG_CPU_USAGE
342private:
343 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700344 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800345
Andy Hung16698b82018-08-01 10:48:38 -0700346 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800347
348 int mCpuNum; // thread's current CPU number
349 int mCpukHz; // frequency of thread's current CPU in kHz
350#endif
351};
352
353CpuStats::CpuStats()
354#ifdef DEBUG_CPU_USAGE
355 : mCpuNum(-1), mCpukHz(-1)
356#endif
357{
358}
359
Glenn Kasten0f11b512014-01-31 16:18:54 -0800360void CpuStats::sample(const String8 &title
361#ifndef DEBUG_CPU_USAGE
362 __unused
363#endif
364 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800365#ifdef DEBUG_CPU_USAGE
366 // get current thread's delta CPU time in wall clock ns
367 double wcNs;
368 bool valid = mCpuUsage.sampleAndEnable(wcNs);
369
370 // record sample for wall clock statistics
371 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700372 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800373 }
374
375 // get the current CPU number
376 int cpuNum = sched_getcpu();
377
378 // get the current CPU frequency in kHz
379 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
380
381 // check if either CPU number or frequency changed
382 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
383 mCpuNum = cpuNum;
384 mCpukHz = cpukHz;
385 // ignore sample for purposes of cycles
386 valid = false;
387 }
388
389 // if no change in CPU number or frequency, then record sample for cycle statistics
390 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700391 const double cycles = wcNs * cpukHz * 0.000001;
392 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800393 }
394
Eric Tan5b13ff82018-07-27 11:20:17 -0700395 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800396 // mCpuUsage.elapsed() is expensive, so don't call it every loop
397 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700398 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800399 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700400 const double perLoop = elapsed / (double) n;
401 const double perLoop100 = perLoop * 0.01;
402 const double perLoop1k = perLoop * 0.001;
403 const double mean = mWcStats.getMean();
404 const double stddev = mWcStats.getStdDev();
405 const double minimum = mWcStats.getMin();
406 const double maximum = mWcStats.getMax();
407 const double meanCycles = mHzStats.getMean();
408 const double stddevCycles = mHzStats.getStdDev();
409 const double minCycles = mHzStats.getMin();
410 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800411 mCpuUsage.resetElapsed();
412 mWcStats.reset();
413 mHzStats.reset();
414 ALOGD("CPU usage for %s over past %.1f secs\n"
415 " (%u mixer loops at %.1f mean ms per loop):\n"
416 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
417 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
418 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
419 title.string(),
420 elapsed * .000000001, n, perLoop * .000001,
421 mean * .001,
422 stddev * .001,
423 minimum * .001,
424 maximum * .001,
425 mean / perLoop100,
426 stddev / perLoop100,
427 minimum / perLoop100,
428 maximum / perLoop100,
429 meanCycles / perLoop1k,
430 stddevCycles / perLoop1k,
431 minCycles / perLoop1k,
432 maxCycles / perLoop1k);
433
434 }
435 }
436#endif
437};
438
439// ----------------------------------------------------------------------------
440// ThreadBase
441// ----------------------------------------------------------------------------
442
Glenn Kasten97b7b752014-09-28 13:04:24 -0700443// static
444const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
445{
446 switch (type) {
447 case MIXER:
448 return "MIXER";
449 case DIRECT:
450 return "DIRECT";
451 case DUPLICATING:
452 return "DUPLICATING";
453 case RECORD:
454 return "RECORD";
455 case OFFLOAD:
456 return "OFFLOAD";
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800457 case MMAP:
458 return "MMAP";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700459 default:
460 return "unknown";
461 }
462}
463
Eric Laurent81784c32012-11-19 14:55:58 -0800464AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -0700465 type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800466 : Thread(false /*canCallJava*/),
467 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700468 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700469 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800470 // are set by PlaybackThread::readOutputParameters_l() or
471 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700472 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700473 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700474 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800475 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700476 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800477 mSystemReady(systemReady),
478 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800479{
Eric Laurent296fb132015-05-01 11:38:42 -0700480 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800481}
482
483AudioFlinger::ThreadBase::~ThreadBase()
484{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700485 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700486 mConfigEvents.clear();
487
Eric Laurent81784c32012-11-19 14:55:58 -0800488 // do not lock the mutex in destructor
489 releaseWakeLock_l();
490 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800491 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800492 binder->unlinkToDeath(mDeathRecipient);
493 }
Andy Hungd0979812019-02-21 15:51:44 -0800494
495 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800496}
497
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700498status_t AudioFlinger::ThreadBase::readyToRun()
499{
500 status_t status = initCheck();
501 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800502 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700503 } else {
504 ALOGE("No working audio driver found.");
505 }
506 return status;
507}
508
Eric Laurent81784c32012-11-19 14:55:58 -0800509void AudioFlinger::ThreadBase::exit()
510{
511 ALOGV("ThreadBase::exit");
512 // do any cleanup required for exit to succeed
513 preExit();
514 {
515 // This lock prevents the following race in thread (uniprocessor for illustration):
516 // if (!exitPending()) {
517 // // context switch from here to exit()
518 // // exit() calls requestExit(), what exitPending() observes
519 // // exit() calls signal(), which is dropped since no waiters
520 // // context switch back from exit() to here
521 // mWaitWorkCV.wait(...);
522 // // now thread is hung
523 // }
524 AutoMutex lock(mLock);
525 requestExit();
526 mWaitWorkCV.broadcast();
527 }
528 // When Thread::requestExitAndWait is made virtual and this method is renamed to
529 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
530 requestExitAndWait();
531}
532
533status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
534{
Eric Laurent81784c32012-11-19 14:55:58 -0800535 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
536 Mutex::Autolock _l(mLock);
537
Eric Laurent10351942014-05-08 18:49:52 -0700538 return sendSetParameterConfigEvent_l(keyValuePairs);
539}
540
541// sendConfigEvent_l() must be called with ThreadBase::mLock held
542// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
543status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
544{
545 status_t status = NO_ERROR;
546
Eric Laurent72e3f392015-05-20 14:43:50 -0700547 if (event->mRequiresSystemReady && !mSystemReady) {
548 event->mWaitStatus = false;
549 mPendingConfigEvents.add(event);
550 return status;
551 }
Eric Laurent10351942014-05-08 18:49:52 -0700552 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700553 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800554 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700555 mLock.unlock();
556 {
557 Mutex::Autolock _l(event->mLock);
558 while (event->mWaitStatus) {
559 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
560 event->mStatus = TIMED_OUT;
561 event->mWaitStatus = false;
562 }
563 }
564 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800565 }
Eric Laurent10351942014-05-08 18:49:52 -0700566 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800567 return status;
568}
569
Eric Laurent09f1ed22019-04-24 17:45:17 -0700570void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid,
571 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800572{
573 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700574 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800575}
576
577// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent09f1ed22019-04-24 17:45:17 -0700578void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid,
579 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800580{
Andy Hungd0979812019-02-21 15:51:44 -0800581 // The audio statistics history is exponentially weighted to forget events
582 // about five or more seconds in the past. In order to have
583 // crisper statistics for mediametrics, we reset the statistics on
584 // an IoConfigEvent, to reflect different properties for a new device.
585 mIoJitterMs.reset();
586 mLatencyMs.reset();
587 mProcessTimeMs.reset();
588 mTimestampVerifier.discontinuity();
589
Eric Laurent09f1ed22019-04-24 17:45:17 -0700590 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700591 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800592}
593
Mikhail Naganov83f04272017-02-07 10:45:09 -0800594void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700595{
596 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800597 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700598}
599
Eric Laurent81784c32012-11-19 14:55:58 -0800600// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800601void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
602 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800603{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800604 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700605 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800606}
607
Eric Laurent10351942014-05-08 18:49:52 -0700608// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
609status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800610{
Andy Hung2ddee192015-12-18 17:34:44 -0800611 sp<ConfigEvent> configEvent;
612 AudioParameter param(keyValuePair);
613 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700614 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800615 setMasterMono_l(value != 0);
616 if (param.size() == 1) {
617 return NO_ERROR; // should be a solo parameter - we don't pass down
618 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700619 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800620 configEvent = new SetParameterConfigEvent(param.toString());
621 } else {
622 configEvent = new SetParameterConfigEvent(keyValuePair);
623 }
Eric Laurent10351942014-05-08 18:49:52 -0700624 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700625}
626
Eric Laurent1c333e22014-05-20 10:48:17 -0700627status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
628 const struct audio_patch *patch,
629 audio_patch_handle_t *handle)
630{
631 Mutex::Autolock _l(mLock);
632 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
633 status_t status = sendConfigEvent_l(configEvent);
634 if (status == NO_ERROR) {
635 CreateAudioPatchConfigEventData *data =
636 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
637 *handle = data->mHandle;
638 }
639 return status;
640}
641
642status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
643 const audio_patch_handle_t handle)
644{
645 Mutex::Autolock _l(mLock);
646 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
647 return sendConfigEvent_l(configEvent);
648}
649
jiabinc52b1ff2019-10-31 17:20:42 -0700650status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
651 const DeviceDescriptorBaseVector& outDevices)
652{
653 if (type() != RECORD) {
654 // The update out device operation is only for record thread.
655 return INVALID_OPERATION;
656 }
657 Mutex::Autolock _l(mLock);
658 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
659 return sendConfigEvent_l(configEvent);
660}
661
Eric Laurent1c333e22014-05-20 10:48:17 -0700662
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700663// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700664void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700665{
Eric Laurent10351942014-05-08 18:49:52 -0700666 bool configChanged = false;
667
Eric Laurent81784c32012-11-19 14:55:58 -0800668 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700669 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700670 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800671 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700672 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700673 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700674 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
675 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800676 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700677 true /*asynchronous*/);
678 if (err != 0) {
679 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700680 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700681 }
682 } break;
683 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700684 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700685 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700686 } break;
687 case CFG_EVENT_SET_PARAMETER: {
688 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
689 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
690 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700691 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
692 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700693 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700694 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700695 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700696 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700697 CreateAudioPatchConfigEventData *data =
698 (CreateAudioPatchConfigEventData *)event->mData.get();
699 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700700 const DeviceTypeSet newDevices = getDeviceTypes();
701 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
702 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
703 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700704 } break;
705 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700706 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700707 ReleaseAudioPatchConfigEventData *data =
708 (ReleaseAudioPatchConfigEventData *)event->mData.get();
709 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700710 const DeviceTypeSet newDevices = getDeviceTypes();
711 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
712 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
713 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
714 } break;
715 case CFG_EVENT_UPDATE_OUT_DEVICE: {
716 UpdateOutDevicesConfigEventData *data =
717 (UpdateOutDevicesConfigEventData *)event->mData.get();
718 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700719 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700720 default:
Eric Laurent10351942014-05-08 18:49:52 -0700721 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700722 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800723 }
Eric Laurent10351942014-05-08 18:49:52 -0700724 {
725 Mutex::Autolock _l(event->mLock);
726 if (event->mWaitStatus) {
727 event->mWaitStatus = false;
728 event->mCond.signal();
729 }
730 }
731 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
732 }
733
734 if (configChanged) {
735 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800736 }
Eric Laurent81784c32012-11-19 14:55:58 -0800737}
738
Marco Nelissenb2208842014-02-07 14:00:50 -0800739String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
740 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700741 const audio_channel_representation_t representation =
742 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700743
744 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800745 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700746 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
747 if (output) {
748 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
749 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
750 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
751 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
752 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
753 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
754 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
755 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
756 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
757 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
758 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
759 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
760 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
761 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
762 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
763 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
764 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
765 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
Mikhail Naganovc9948492018-05-10 17:25:28 -0700766 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, " );
767 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, " );
jiabin245cdd92018-12-07 17:55:15 -0800768 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, " );
769 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700770 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
771 } else {
772 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
773 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
774 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
775 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
776 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
777 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
778 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
779 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
780 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
781 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
782 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
783 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700784 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
785 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
786 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
787 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low freq, ");
788 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, " );
789 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700790 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
791 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
792 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
793 }
794 const int len = s.length();
795 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700796 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700797 s.unlockBuffer(len - 2); // remove trailing ", "
798 }
799 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800800 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700801 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
802 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
803 return s;
804 default:
805 s.appendFormat("unknown mask, representation:%d bits:%#x",
806 representation, audio_channel_mask_get_bits(mask));
807 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800808 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800809}
810
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700811void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800812{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800813 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
814 this, mThreadName, getTid(), type(), threadTypeToString(type()));
815
Eric Laurent81784c32012-11-19 14:55:58 -0800816 bool locked = AudioFlinger::dumpTryLock(mLock);
817 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800818 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800819 }
820
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700821 dumpBase_l(fd, args);
822 dumpInternals_l(fd, args);
823 dumpTracks_l(fd, args);
824 dumpEffectChains_l(fd, args);
825
826 if (locked) {
827 mLock.unlock();
828 }
829
830 dprintf(fd, " Local log:\n");
831 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
832}
833
834void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
835{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700836 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700837 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700838 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700839 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700840 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700841 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700842 dprintf(fd, " Channel count: %u\n", mChannelCount);
843 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800844 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700845 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700846 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700847 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800848 size_t numConfig = mConfigEvents.size();
849 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700850 const size_t SIZE = 256;
851 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800852 for (size_t i = 0; i < numConfig; i++) {
853 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700854 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800855 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700856 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800857 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700858 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800859 }
Andy Hung293558a2017-03-21 12:19:20 -0700860 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -0700861 dprintf(fd, " Output devices: %s (%s)\n",
862 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
863 dprintf(fd, " Input device: %#x (%s)\n",
864 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800865 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800866
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700867 // Dump timestamp statistics for the Thread types that support it.
868 if (mType == RECORD
869 || mType == MIXER
870 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700871 || mType == DIRECT
872 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700873 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700874 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700875 }
876
Andy Hung446f4df2019-02-21 12:26:41 -0800877 if (mLastIoBeginNs > 0) { // MMAP may not set this
878 dprintf(fd, " Last %s occurred (msecs): %lld\n",
879 isOutput() ? "write" : "read",
880 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
881 }
882
883 if (mProcessTimeMs.getN() > 0) {
884 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
885 }
886
887 if (mIoJitterMs.getN() > 0) {
888 dprintf(fd, " Hal %s jitter ms stats: %s\n",
889 isOutput() ? "write" : "read",
890 mIoJitterMs.toString().c_str());
891 }
892
Andy Hunge6c37112019-02-26 17:38:10 -0800893 if (mLatencyMs.getN() > 0) {
894 dprintf(fd, " Threadloop %s latency stats: %s\n",
895 isOutput() ? "write" : "read",
896 mLatencyMs.toString().c_str());
897 }
Eric Laurent81784c32012-11-19 14:55:58 -0800898}
899
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700900void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800901{
902 const size_t SIZE = 256;
903 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -0800904
Marco Nelissenb2208842014-02-07 14:00:50 -0800905 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000906 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800907 write(fd, buffer, strlen(buffer));
908
Marco Nelissenb2208842014-02-07 14:00:50 -0800909 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800910 sp<EffectChain> chain = mEffectChains[i];
911 if (chain != 0) {
912 chain->dump(fd, args);
913 }
914 }
915}
916
Andy Hungdae27702016-10-31 14:01:16 -0700917void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800918{
919 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700920 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800921}
922
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100923String16 AudioFlinger::ThreadBase::getWakeLockTag()
924{
925 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800926 case MIXER:
927 return String16("AudioMix");
928 case DIRECT:
929 return String16("AudioDirectOut");
930 case DUPLICATING:
931 return String16("AudioDup");
932 case RECORD:
933 return String16("AudioIn");
934 case OFFLOAD:
935 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800936 case MMAP:
937 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800938 default:
939 ALOG_ASSERT(false);
940 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100941 }
942}
943
Andy Hungdae27702016-10-31 14:01:16 -0700944void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800945{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800946 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800947 if (mPowerManager != 0) {
948 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700949 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
950 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700951 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100952 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700953 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700954 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800955 if (status == NO_ERROR) {
956 mWakeLockToken = binder;
957 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800958 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800959 }
Wei Jia3f273d12015-11-24 09:06:49 -0800960
Andy Hung3f0c9022016-01-15 17:49:46 -0800961 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800962 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
963 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800964}
965
966void AudioFlinger::ThreadBase::releaseWakeLock()
967{
968 Mutex::Autolock _l(mLock);
969 releaseWakeLock_l();
970}
971
972void AudioFlinger::ThreadBase::releaseWakeLock_l()
973{
Andy Hung3f0c9022016-01-15 17:49:46 -0800974 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800975 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800976 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800977 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700978 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
979 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800980 }
981 mWakeLockToken.clear();
982 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800983}
984
985void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700986 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800987 // use checkService() to avoid blocking if power service is not up yet
988 sp<IBinder> binder =
989 defaultServiceManager()->checkService(String16("power"));
990 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800991 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800992 } else {
993 mPowerManager = interface_cast<IPowerManager>(binder);
994 binder->linkToDeath(mDeathRecipient);
995 }
996 }
997}
998
Andy Hungd01b0f12016-11-07 16:10:30 -0800999void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001000 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001001
1002#if !LOG_NDEBUG
1003 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001004 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001005 s << uid << " ";
1006 }
1007 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1008#endif
1009
Andy Hung438e7572015-12-14 15:51:17 -08001010 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1011 if (mSystemReady) {
1012 ALOGE("no wake lock to update, but system ready!");
1013 } else {
1014 ALOGW("no wake lock to update, system not ready yet");
1015 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001016 return;
1017 }
1018 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001019 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
1020 status_t status = mPowerManager->updateWakeLockUids(
1021 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
1022 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001023 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001024 }
1025}
1026
Eric Laurent81784c32012-11-19 14:55:58 -08001027void AudioFlinger::ThreadBase::clearPowerManager()
1028{
1029 Mutex::Autolock _l(mLock);
1030 releaseWakeLock_l();
1031 mPowerManager.clear();
1032}
1033
jiabinc52b1ff2019-10-31 17:20:42 -07001034void AudioFlinger::ThreadBase::updateOutDevices(
1035 const DeviceDescriptorBaseVector& outDevices __unused)
1036{
1037 ALOGE("%s should only be called in RecordThread", __func__);
1038}
1039
Glenn Kasten0f11b512014-01-31 16:18:54 -08001040void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001041{
1042 sp<ThreadBase> thread = mThread.promote();
1043 if (thread != 0) {
1044 thread->clearPowerManager();
1045 }
1046 ALOGW("power manager service died !!!");
1047}
1048
Eric Laurent81784c32012-11-19 14:55:58 -08001049void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001050 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001051{
1052 sp<EffectChain> chain = getEffectChain_l(sessionId);
1053 if (chain != 0) {
1054 if (type != NULL) {
1055 chain->setEffectSuspended_l(type, suspend);
1056 } else {
1057 chain->setEffectSuspendedAll_l(suspend);
1058 }
1059 }
1060
1061 updateSuspendedSessions_l(type, suspend, sessionId);
1062}
1063
1064void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1065{
1066 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1067 if (index < 0) {
1068 return;
1069 }
1070
1071 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1072 mSuspendedSessions.valueAt(index);
1073
1074 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001075 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001076 for (int j = 0; j < desc->mRefCount; j++) {
1077 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1078 chain->setEffectSuspendedAll_l(true);
1079 } else {
1080 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1081 desc->mType.timeLow);
1082 chain->setEffectSuspended_l(&desc->mType, true);
1083 }
1084 }
1085 }
1086}
1087
1088void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1089 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001090 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001091{
1092 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1093
1094 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1095
1096 if (suspend) {
1097 if (index >= 0) {
1098 sessionEffects = mSuspendedSessions.valueAt(index);
1099 } else {
1100 mSuspendedSessions.add(sessionId, sessionEffects);
1101 }
1102 } else {
1103 if (index < 0) {
1104 return;
1105 }
1106 sessionEffects = mSuspendedSessions.valueAt(index);
1107 }
1108
1109
1110 int key = EffectChain::kKeyForSuspendAll;
1111 if (type != NULL) {
1112 key = type->timeLow;
1113 }
1114 index = sessionEffects.indexOfKey(key);
1115
1116 sp<SuspendedSessionDesc> desc;
1117 if (suspend) {
1118 if (index >= 0) {
1119 desc = sessionEffects.valueAt(index);
1120 } else {
1121 desc = new SuspendedSessionDesc();
1122 if (type != NULL) {
1123 desc->mType = *type;
1124 }
1125 sessionEffects.add(key, desc);
1126 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1127 }
1128 desc->mRefCount++;
1129 } else {
1130 if (index < 0) {
1131 return;
1132 }
1133 desc = sessionEffects.valueAt(index);
1134 if (--desc->mRefCount == 0) {
1135 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1136 sessionEffects.removeItemsAt(index);
1137 if (sessionEffects.isEmpty()) {
1138 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1139 sessionId);
1140 mSuspendedSessions.removeItem(sessionId);
1141 }
1142 }
1143 }
1144 if (!sessionEffects.isEmpty()) {
1145 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1146 }
1147}
1148
1149void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1150 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001151 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001152{
1153 Mutex::Autolock _l(mLock);
1154 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1155}
1156
1157void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1158 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001159 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001160{
1161 if (mType != RECORD) {
1162 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1163 // another session. This gives the priority to well behaved effect control panels
1164 // and applications not using global effects.
1165 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1166 // global effects
1167 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1168 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1169 }
1170 }
1171
1172 sp<EffectChain> chain = getEffectChain_l(sessionId);
1173 if (chain != 0) {
1174 chain->checkSuspendOnEffectEnabled(effect, enabled);
1175 }
1176}
1177
Eric Laurent4c415062016-06-17 16:14:16 -07001178// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1179status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1180 const effect_descriptor_t *desc, audio_session_t sessionId)
1181{
1182 // No global effect sessions on record threads
1183 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1184 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1185 desc->name, mThreadName);
1186 return BAD_VALUE;
1187 }
1188 // only pre processing effects on record thread
1189 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1190 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1191 desc->name, mThreadName);
1192 return BAD_VALUE;
1193 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001194
1195 // always allow effects without processing load or latency
1196 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1197 return NO_ERROR;
1198 }
1199
Eric Laurent4c415062016-06-17 16:14:16 -07001200 audio_input_flags_t flags = mInput->flags;
1201 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1202 if (flags & AUDIO_INPUT_FLAG_RAW) {
1203 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1204 desc->name, mThreadName);
1205 return BAD_VALUE;
1206 }
1207 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1208 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1209 desc->name, mThreadName);
1210 return BAD_VALUE;
1211 }
1212 }
1213 return NO_ERROR;
1214}
1215
1216// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1217status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1218 const effect_descriptor_t *desc, audio_session_t sessionId)
1219{
1220 // no preprocessing on playback threads
1221 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1222 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1223 " thread %s", desc->name, mThreadName);
1224 return BAD_VALUE;
1225 }
1226
Eric Laurent3e4de772017-07-16 16:55:08 -07001227 // always allow effects without processing load or latency
1228 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1229 return NO_ERROR;
1230 }
1231
Eric Laurent4c415062016-06-17 16:14:16 -07001232 switch (mType) {
1233 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001234#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001235 // Reject any effect on mixer multichannel sinks.
1236 // TODO: fix both format and multichannel issues with effects.
1237 if (mChannelCount != FCC_2) {
1238 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1239 " thread %s", desc->name, mChannelCount, mThreadName);
1240 return BAD_VALUE;
1241 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001242#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001243 audio_output_flags_t flags = mOutput->flags;
1244 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1245 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1246 // global effects are applied only to non fast tracks if they are SW
1247 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1248 break;
1249 }
1250 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1251 // only post processing on output stage session
1252 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1253 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1254 " on output stage session", desc->name);
1255 return BAD_VALUE;
1256 }
1257 } else {
1258 // no restriction on effects applied on non fast tracks
1259 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1260 break;
1261 }
1262 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001263
Eric Laurent4c415062016-06-17 16:14:16 -07001264 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1265 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1266 desc->name);
1267 return BAD_VALUE;
1268 }
1269 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1270 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1271 " in fast mode", desc->name);
1272 return BAD_VALUE;
1273 }
1274 }
1275 } break;
1276 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001277 // nothing actionable on offload threads, if the effect:
1278 // - is offloadable: the effect can be created
1279 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1280 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001281 break;
1282 case DIRECT:
1283 // Reject any effect on Direct output threads for now, since the format of
1284 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1285 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1286 desc->name, mThreadName);
1287 return BAD_VALUE;
1288 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001289#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001290 // Reject any effect on mixer multichannel sinks.
1291 // TODO: fix both format and multichannel issues with effects.
1292 if (mChannelCount != FCC_2) {
1293 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1294 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1295 return BAD_VALUE;
1296 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001297#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001298 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1299 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1300 " thread %s", desc->name, mThreadName);
1301 return BAD_VALUE;
1302 }
1303 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1304 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1305 " DUPLICATING thread %s", desc->name, mThreadName);
1306 return BAD_VALUE;
1307 }
1308 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1309 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1310 " DUPLICATING thread %s", desc->name, mThreadName);
1311 return BAD_VALUE;
1312 }
1313 break;
1314 default:
1315 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1316 }
1317
1318 return NO_ERROR;
1319}
1320
Eric Laurent81784c32012-11-19 14:55:58 -08001321// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1322sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1323 const sp<AudioFlinger::Client>& client,
1324 const sp<IEffectClient>& effectClient,
1325 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001326 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001327 effect_descriptor_t *desc,
1328 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001329 status_t *status,
1330 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001331{
1332 sp<EffectModule> effect;
1333 sp<EffectHandle> handle;
1334 status_t lStatus;
1335 sp<EffectChain> chain;
1336 bool chainCreated = false;
1337 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001338 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001339
1340 lStatus = initCheck();
1341 if (lStatus != NO_ERROR) {
1342 ALOGW("createEffect_l() Audio driver not initialized.");
1343 goto Exit;
1344 }
1345
Eric Laurent81784c32012-11-19 14:55:58 -08001346 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1347
1348 { // scope for mLock
1349 Mutex::Autolock _l(mLock);
1350
Eric Laurent4c415062016-06-17 16:14:16 -07001351 lStatus = checkEffectCompatibility_l(desc, sessionId);
1352 if (lStatus != NO_ERROR) {
1353 goto Exit;
1354 }
1355
Eric Laurent81784c32012-11-19 14:55:58 -08001356 // check for existing effect chain with the requested audio session
1357 chain = getEffectChain_l(sessionId);
1358 if (chain == 0) {
1359 // create a new chain for this session
1360 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1361 chain = new EffectChain(this, sessionId);
1362 addEffectChain_l(chain);
1363 chain->setStrategy(getStrategyForSession_l(sessionId));
1364 chainCreated = true;
1365 } else {
1366 effect = chain->getEffectFromDesc_l(desc);
1367 }
1368
1369 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1370
1371 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001372 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001373 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001374 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001375 if (lStatus != NO_ERROR) {
1376 goto Exit;
1377 }
1378 effectCreated = true;
1379
jiabinc52b1ff2019-10-31 17:20:42 -07001380 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001381 effect->setDevices(outDeviceTypeAddrs());
1382 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001383 effect->setMode(mAudioFlinger->getMode());
1384 effect->setAudioSource(mAudioSource);
1385 }
1386 // create effect handle and connect it to effect module
1387 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001388 lStatus = handle->initCheck();
1389 if (lStatus == OK) {
1390 lStatus = effect->addHandle(handle.get());
1391 }
Eric Laurent81784c32012-11-19 14:55:58 -08001392 if (enabled != NULL) {
1393 *enabled = (int)effect->isEnabled();
1394 }
1395 }
1396
1397Exit:
1398 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1399 Mutex::Autolock _l(mLock);
1400 if (effectCreated) {
1401 chain->removeEffect_l(effect);
1402 }
Eric Laurent81784c32012-11-19 14:55:58 -08001403 if (chainCreated) {
1404 removeEffectChain_l(chain);
1405 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001406 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001407 }
1408
Glenn Kasten9156ef32013-08-06 15:39:08 -07001409 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001410 return handle;
1411}
1412
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001413void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1414 bool unpinIfLast)
1415{
1416 bool remove = false;
1417 sp<EffectModule> effect;
1418 {
1419 Mutex::Autolock _l(mLock);
1420
1421 effect = handle->effect().promote();
1422 if (effect == 0) {
1423 return;
1424 }
1425 // restore suspended effects if the disconnected handle was enabled and the last one.
1426 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1427 if (remove) {
1428 removeEffect_l(effect, true);
1429 }
1430 }
1431 if (remove) {
1432 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001433 if (handle->enabled()) {
1434 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1435 }
1436 }
1437}
1438
Glenn Kastend848eb42016-03-08 13:42:11 -08001439sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1440 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001441{
1442 Mutex::Autolock _l(mLock);
1443 return getEffect_l(sessionId, effectId);
1444}
1445
Glenn Kastend848eb42016-03-08 13:42:11 -08001446sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1447 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001448{
1449 sp<EffectChain> chain = getEffectChain_l(sessionId);
1450 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1451}
1452
Eric Laurent6c796322019-04-09 14:13:17 -07001453std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1454{
1455 sp<EffectChain> chain = getEffectChain_l(sessionId);
1456 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1457}
1458
Eric Laurent81784c32012-11-19 14:55:58 -08001459// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1460// PlaybackThread::mLock held
1461status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1462{
1463 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001464 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001465 sp<EffectChain> chain = getEffectChain_l(sessionId);
1466 bool chainCreated = false;
1467
Eric Laurent5baf2af2013-09-12 17:37:00 -07001468 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001469 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001470 this, effect->desc().name, effect->desc().flags);
1471
Eric Laurent81784c32012-11-19 14:55:58 -08001472 if (chain == 0) {
1473 // create a new chain for this session
1474 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1475 chain = new EffectChain(this, sessionId);
1476 addEffectChain_l(chain);
1477 chain->setStrategy(getStrategyForSession_l(sessionId));
1478 chainCreated = true;
1479 }
1480 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1481
1482 if (chain->getEffectFromId_l(effect->id()) != 0) {
1483 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1484 this, effect->desc().name, chain.get());
1485 return BAD_VALUE;
1486 }
1487
Eric Laurent5baf2af2013-09-12 17:37:00 -07001488 effect->setOffloaded(mType == OFFLOAD, mId);
1489
Eric Laurent81784c32012-11-19 14:55:58 -08001490 status_t status = chain->addEffect_l(effect);
1491 if (status != NO_ERROR) {
1492 if (chainCreated) {
1493 removeEffectChain_l(chain);
1494 }
1495 return status;
1496 }
1497
jiabin8f278ee2019-11-11 12:16:27 -08001498 effect->setDevices(outDeviceTypeAddrs());
1499 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001500 effect->setMode(mAudioFlinger->getMode());
1501 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001502
Eric Laurent81784c32012-11-19 14:55:58 -08001503 return NO_ERROR;
1504}
1505
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001506void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001507
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001508 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001509 effect_descriptor_t desc = effect->desc();
1510 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1511 detachAuxEffect_l(effect->id());
1512 }
1513
1514 sp<EffectChain> chain = effect->chain().promote();
1515 if (chain != 0) {
1516 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001517 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001518 removeEffectChain_l(chain);
1519 }
1520 } else {
1521 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1522 }
1523}
1524
1525void AudioFlinger::ThreadBase::lockEffectChains_l(
1526 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1527{
1528 effectChains = mEffectChains;
1529 for (size_t i = 0; i < mEffectChains.size(); i++) {
1530 mEffectChains[i]->lock();
1531 }
1532}
1533
1534void AudioFlinger::ThreadBase::unlockEffectChains(
1535 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1536{
1537 for (size_t i = 0; i < effectChains.size(); i++) {
1538 effectChains[i]->unlock();
1539 }
1540}
1541
Glenn Kastend848eb42016-03-08 13:42:11 -08001542sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001543{
1544 Mutex::Autolock _l(mLock);
1545 return getEffectChain_l(sessionId);
1546}
1547
Glenn Kastend848eb42016-03-08 13:42:11 -08001548sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1549 const
Eric Laurent81784c32012-11-19 14:55:58 -08001550{
1551 size_t size = mEffectChains.size();
1552 for (size_t i = 0; i < size; i++) {
1553 if (mEffectChains[i]->sessionId() == sessionId) {
1554 return mEffectChains[i];
1555 }
1556 }
1557 return 0;
1558}
1559
1560void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1561{
1562 Mutex::Autolock _l(mLock);
1563 size_t size = mEffectChains.size();
1564 for (size_t i = 0; i < size; i++) {
1565 mEffectChains[i]->setMode_l(mode);
1566 }
1567}
1568
Mikhail Naganovdc769682018-05-04 15:34:08 -07001569void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001570{
1571 config->type = AUDIO_PORT_TYPE_MIX;
1572 config->ext.mix.handle = mId;
1573 config->sample_rate = mSampleRate;
1574 config->format = mFormat;
1575 config->channel_mask = mChannelMask;
1576 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1577 AUDIO_PORT_CONFIG_FORMAT;
1578}
1579
Eric Laurent72e3f392015-05-20 14:43:50 -07001580void AudioFlinger::ThreadBase::systemReady()
1581{
1582 Mutex::Autolock _l(mLock);
1583 if (mSystemReady) {
1584 return;
1585 }
1586 mSystemReady = true;
1587
1588 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1589 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1590 }
1591 mPendingConfigEvents.clear();
1592}
1593
Andy Hungdae27702016-10-31 14:01:16 -07001594template <typename T>
1595ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1596 ssize_t index = mActiveTracks.indexOf(track);
1597 if (index >= 0) {
1598 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1599 return index;
1600 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001601 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001602 mActiveTracksGeneration++;
1603 mLatestActiveTrack = track;
1604 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001605 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001606 return mActiveTracks.add(track);
1607}
1608
1609template <typename T>
1610ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1611 ssize_t index = mActiveTracks.remove(track);
1612 if (index < 0) {
1613 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1614 return index;
1615 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001616 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001617 mActiveTracksGeneration++;
1618 --mBatteryCounter[track->uid()].second;
1619 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001620 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001621#ifdef TEE_SINK
1622 track->dumpTee(-1 /* fd */, "_REMOVE");
1623#endif
Andy Hungdae27702016-10-31 14:01:16 -07001624 return index;
1625}
1626
1627template <typename T>
1628void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1629 for (const sp<T> &track : mActiveTracks) {
1630 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001631 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001632 }
1633 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001634 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001635 mActiveTracks.clear();
1636 mLatestActiveTrack.clear();
1637 mBatteryCounter.clear();
1638}
1639
1640template <typename T>
1641void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1642 sp<ThreadBase> thread, bool force) {
1643 // Updates ActiveTracks client uids to the thread wakelock.
1644 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1645 thread->updateWakeLockUids_l(getWakeLockUids());
1646 mLastActiveTracksGeneration = mActiveTracksGeneration;
1647 }
1648
1649 // Updates BatteryNotifier uids
1650 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1651 const uid_t uid = it->first;
1652 ssize_t &previous = it->second.first;
1653 ssize_t &current = it->second.second;
1654 if (current > 0) {
1655 if (previous == 0) {
1656 BatteryNotifier::getInstance().noteStartAudio(uid);
1657 }
1658 previous = current;
1659 ++it;
1660 } else if (current == 0) {
1661 if (previous > 0) {
1662 BatteryNotifier::getInstance().noteStopAudio(uid);
1663 }
1664 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1665 } else /* (current < 0) */ {
1666 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1667 }
1668 }
1669}
Eric Laurent83b88082014-06-20 18:31:16 -07001670
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001671template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001672bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1673 const bool hasChanged = mHasChanged;
1674 mHasChanged = false;
1675 return hasChanged;
1676}
1677
1678template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001679void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1680 const char *funcName, const sp<T> &track) const {
1681 if (mLocalLog != nullptr) {
1682 String8 result;
1683 track->appendDump(result, false /* active */);
1684 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1685 }
1686}
1687
Eric Laurent6acd1d42017-01-04 14:23:29 -08001688void AudioFlinger::ThreadBase::broadcast_l()
1689{
1690 // Thread could be blocked waiting for async
1691 // so signal it to handle state changes immediately
1692 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1693 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1694 mSignalPending = true;
1695 mWaitWorkCV.broadcast();
1696}
1697
Andy Hungd0979812019-02-21 15:51:44 -08001698// Call only from threadLoop() or when it is idle.
1699// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1700void AudioFlinger::ThreadBase::sendStatistics(bool force)
1701{
1702 // Do not log if we have no stats.
1703 // We choose the timestamp verifier because it is the most likely item to be present.
1704 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1705 if (nstats == 0) {
1706 return;
1707 }
1708
1709 // Don't log more frequently than once per 12 hours.
1710 // We use BOOTTIME to include suspend time.
1711 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1712 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1713 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1714 return;
1715 }
1716
1717 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1718 mLastRecordedTimeNs = timeNs;
1719
1720 std::unique_ptr<MediaAnalyticsItem> item(MediaAnalyticsItem::create("audiothread"));
1721
1722#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1723
1724 // thread configuration
1725 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1726 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1727 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1728 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1729 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1730 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1731 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001732 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1733 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001734
1735 // thread statistics
1736 if (mIoJitterMs.getN() > 0) {
1737 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1738 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1739 }
1740 if (mProcessTimeMs.getN() > 0) {
1741 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1742 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1743 }
1744 const auto tsjitter = mTimestampVerifier.getJitterMs();
1745 if (tsjitter.getN() > 0) {
1746 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1747 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1748 }
1749 if (mLatencyMs.getN() > 0) {
1750 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1751 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1752 }
1753
1754 item->selfrecord();
1755}
1756
Eric Laurent81784c32012-11-19 14:55:58 -08001757// ----------------------------------------------------------------------------
1758// Playback
1759// ----------------------------------------------------------------------------
1760
1761AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1762 AudioStreamOut* output,
1763 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001764 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001765 bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07001766 : ThreadBase(audioFlinger, id, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001767 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001768 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001769 mMixerBuffer(NULL),
1770 mMixerBufferSize(0),
1771 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1772 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001773 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001774 mEffectBuffer(NULL),
1775 mEffectBufferSize(0),
1776 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1777 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001778 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001779 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001780 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001781 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001782 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001783 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001784 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001785 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001786 mMixerStatus(MIXER_IDLE),
1787 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001788 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001789 mBytesRemaining(0),
1790 mCurrentWriteLength(0),
1791 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001792 mWriteAckSequence(0),
1793 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001794 mScreenState(AudioFlinger::mScreenState),
1795 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001796 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001797 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1798 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001799{
Glenn Kastend7dca052015-03-05 16:05:54 -08001800 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1801 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001802
1803 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1804 // it would be safer to explicitly pass initial masterVolume/masterMute as
1805 // parameter.
1806 //
1807 // If the HAL we are using has support for master volume or master mute,
1808 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1809 // and the mute set to false).
1810 mMasterVolume = audioFlinger->masterVolume_l();
1811 mMasterMute = audioFlinger->masterMute_l();
1812 if (mOutput && mOutput->audioHwDev) {
1813 if (mOutput->audioHwDev->canSetMasterVolume()) {
1814 mMasterVolume = 1.0;
1815 }
1816
1817 if (mOutput->audioHwDev->canSetMasterMute()) {
1818 mMasterMute = false;
1819 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001820 mIsMsdDevice = strcmp(
1821 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001822 }
1823
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001824 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001825
Andy Hungc8fddf32018-08-08 18:32:37 -07001826 // TODO: We may also match on address as well as device type for
1827 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11001828 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07001829 // TODO: This property should be ensure that only contains one single device type.
1830 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
1831 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07001832 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1833 : AUDIO_DEVICE_NONE));
1834 }
1835
Eric Laurent223fd5c2014-11-11 13:43:36 -08001836 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001837 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001838 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001839 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001840 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1841 }
Eric Laurent98e38192018-02-15 18:31:53 -08001842 // Audio patch volume is always max
1843 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1844 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001845}
1846
1847AudioFlinger::PlaybackThread::~PlaybackThread()
1848{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001849 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001850 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001851 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001852 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001853}
1854
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001855// Thread virtuals
1856
1857void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08001858{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001859 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001860}
1861
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001862// ThreadBase virtuals
1863void AudioFlinger::PlaybackThread::preExit()
1864{
1865 ALOGV(" preExit()");
1866 // FIXME this is using hard-coded strings but in the future, this functionality will be
1867 // converted to use audio HAL extensions required to support tunneling
1868 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1869 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
1870}
1871
1872void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001873{
Eric Laurent81784c32012-11-19 14:55:58 -08001874 String8 result;
1875
Marco Nelissenb2208842014-02-07 14:00:50 -08001876 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001877 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1878 const stream_type_t *st = &mStreamTypes[i];
1879 if (i > 0) {
1880 result.appendFormat(", ");
1881 }
1882 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1883 if (st->mute) {
1884 result.append("M");
1885 }
1886 }
1887 result.append("\n");
1888 write(fd, result.string(), result.length());
1889 result.clear();
1890
Eric Laurent81784c32012-11-19 14:55:58 -08001891 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1892 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001893 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001894 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001895
1896 size_t numtracks = mTracks.size();
1897 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001898 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001899 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001900 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001901 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001902 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001903 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001904 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001905 for (size_t i = 0; i < numtracks; ++i) {
1906 sp<Track> track = mTracks[i];
1907 if (track != 0) {
1908 bool active = mActiveTracks.indexOf(track) >= 0;
1909 if (active) {
1910 numactiveseen++;
1911 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001912 result.append(prefix);
1913 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001914 }
1915 }
1916 } else {
1917 result.append("\n");
1918 }
1919 if (numactiveseen != numactive) {
1920 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001921 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001922 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001923 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001924 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001925 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001926 sp<Track> track = mActiveTracks[i];
1927 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001928 result.append(prefix);
1929 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001930 }
1931 }
1932 }
1933
1934 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001935}
1936
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001937void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001938{
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07001939 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
jiabin245cdd92018-12-07 17:55:15 -08001940 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
1941 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
1942 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
1943 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001944 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001945 dprintf(fd, " Total writes: %d\n", mNumWrites);
1946 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1947 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1948 dprintf(fd, " Suspend count: %d\n", mSuspended);
1949 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1950 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1951 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1952 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001953 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001954 AudioStreamOut *output = mOutput;
1955 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001956 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08001957 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001958 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1959 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1960 if (mPipeSink.get() != nullptr) {
1961 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1962 }
1963 if (output != nullptr) {
1964 dprintf(fd, " Hal stream dump:\n");
1965 (void)output->stream->dump(fd);
1966 }
Eric Laurent81784c32012-11-19 14:55:58 -08001967}
1968
Eric Laurent81784c32012-11-19 14:55:58 -08001969// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1970sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1971 const sp<AudioFlinger::Client>& client,
1972 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001973 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08001974 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001975 audio_format_t format,
1976 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001977 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001978 size_t *pNotificationFrameCount,
1979 uint32_t notificationsPerBuffer,
1980 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001981 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001982 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001983 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07001984 pid_t creatorPid,
Eric Laurent81784c32012-11-19 14:55:58 -08001985 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001986 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001987 status_t *status,
1988 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001989{
Glenn Kasten74935e42013-12-19 08:56:45 -08001990 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001991 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001992 sp<Track> track;
1993 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001994 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08001995 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07001996 uint32_t sampleRate;
1997
1998 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
1999 lStatus = BAD_VALUE;
2000 goto Exit;
2001 }
Eric Laurent21da6472017-11-09 16:29:26 -08002002
2003 if (*pSampleRate == 0) {
2004 *pSampleRate = mSampleRate;
2005 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002006 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002007
2008 // special case for FAST flag considered OK if fast mixer is present
2009 if (hasFastMixer()) {
2010 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2011 }
2012
2013 // Check if requested flags are compatible with output stream flags
2014 if ((*flags & outputFlags) != *flags) {
2015 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2016 *flags, outputFlags);
2017 *flags = (audio_output_flags_t)(*flags & outputFlags);
2018 }
Eric Laurent81784c32012-11-19 14:55:58 -08002019
Eric Laurent81784c32012-11-19 14:55:58 -08002020 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002021 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002022 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002023 // PCM data
2024 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002025 // TODO: extract as a data library function that checks that a computationally
2026 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002027 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002028 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2029 (channelMask == AUDIO_CHANNEL_OUT_MONO
2030 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002031 // hardware sample rate
2032 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002033 // normal mixer has an associated fast mixer
2034 hasFastMixer() &&
2035 // there are sufficient fast track slots available
2036 (mFastTrackAvailMask != 0)
2037 // FIXME test that MixerThread for this fast track has a capable output HAL
2038 // FIXME add a permission test also?
2039 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002040 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2041 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002042 // read the fast track multiplier property the first time it is needed
2043 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2044 if (ok != 0) {
2045 ALOGE("%s pthread_once failed: %d", __func__, ok);
2046 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002047 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002048 }
Eric Laurent4c415062016-06-17 16:14:16 -07002049
2050 // check compatibility with audio effects.
2051 { // scope for mLock
2052 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002053 for (audio_session_t session : {
2054 AUDIO_SESSION_OUTPUT_STAGE,
2055 AUDIO_SESSION_OUTPUT_MIX,
2056 sessionId,
2057 }) {
2058 sp<EffectChain> chain = getEffectChain_l(session);
2059 if (chain.get() != nullptr) {
2060 audio_output_flags_t old = *flags;
2061 chain->checkOutputFlagCompatibility(flags);
2062 if (old != *flags) {
2063 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2064 (int)session, (int)old, (int)*flags);
2065 }
Eric Laurent4c415062016-06-17 16:14:16 -07002066 }
2067 }
2068 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002069 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002070 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2071 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002072 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002073 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2074 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002075 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002076 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002077 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08002078 audio_is_linear_pcm(format),
2079 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002080 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002081 }
2082 }
Eric Laurent21da6472017-11-09 16:29:26 -08002083
2084 if (!audio_has_proportional_frames(format)) {
2085 if (sharedBuffer != 0) {
2086 // Same comment as below about ignoring frameCount parameter for set()
2087 frameCount = sharedBuffer->size();
2088 } else if (frameCount == 0) {
2089 frameCount = mNormalFrameCount;
2090 }
2091 if (notificationFrameCount != frameCount) {
2092 notificationFrameCount = frameCount;
2093 }
2094 } else if (sharedBuffer != 0) {
2095 // FIXME: Ensure client side memory buffers need
2096 // not have additional alignment beyond sample
2097 // (e.g. 16 bit stereo accessed as 32 bit frame).
2098 size_t alignment = audio_bytes_per_sample(format);
2099 if (alignment & 1) {
2100 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2101 alignment = 1;
2102 }
2103 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2104 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2105 if (channelCount > 1) {
2106 // More than 2 channels does not require stronger alignment than stereo
2107 alignment <<= 1;
2108 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002109 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002110 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002111 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002112 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002113 goto Exit;
2114 }
Eric Laurent21da6472017-11-09 16:29:26 -08002115
2116 // When initializing a shared buffer AudioTrack via constructors,
2117 // there's no frameCount parameter.
2118 // But when initializing a shared buffer AudioTrack via set(),
2119 // there _is_ a frameCount parameter. We silently ignore it.
2120 frameCount = sharedBuffer->size() / frameSize;
2121 } else {
2122 size_t minFrameCount = 0;
2123 // For fast tracks we try to respect the application's request for notifications per buffer.
2124 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2125 if (notificationsPerBuffer > 0) {
2126 // Avoid possible arithmetic overflow during multiplication.
2127 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2128 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2129 notificationsPerBuffer, mFrameCount);
2130 } else {
2131 minFrameCount = mFrameCount * notificationsPerBuffer;
2132 }
2133 }
2134 } else {
2135 // For normal PCM streaming tracks, update minimum frame count.
2136 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2137 // cover audio hardware latency.
2138 // This is probably too conservative, but legacy application code may depend on it.
2139 // If you change this calculation, also review the start threshold which is related.
2140 uint32_t latencyMs = latency_l();
2141 if (latencyMs == 0) {
2142 ALOGE("Error when retrieving output stream latency");
2143 lStatus = UNKNOWN_ERROR;
2144 goto Exit;
2145 }
2146
2147 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2148 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2149
Eric Laurent81784c32012-11-19 14:55:58 -08002150 }
Eric Laurent21da6472017-11-09 16:29:26 -08002151 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002152 frameCount = minFrameCount;
2153 }
Eric Laurent81784c32012-11-19 14:55:58 -08002154 }
Eric Laurent21da6472017-11-09 16:29:26 -08002155
2156 // Make sure that application is notified with sufficient margin before underrun.
2157 // The client can divide the AudioTrack buffer into sub-buffers,
2158 // and expresses its desire to server as the notification frame count.
2159 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2160 size_t maxNotificationFrames;
2161 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2162 // notify every HAL buffer, regardless of the size of the track buffer
2163 maxNotificationFrames = mFrameCount;
2164 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002165 // Triple buffer the notification period for a triple buffered mixer period;
2166 // otherwise, double buffering for the notification period is fine.
2167 //
2168 // TODO: This should be moved to AudioTrack to modify the notification period
2169 // on AudioTrack::setBufferSizeInFrames() changes.
2170 const int nBuffering =
2171 (uint64_t{frameCount} * mSampleRate)
2172 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2173
Eric Laurent21da6472017-11-09 16:29:26 -08002174 maxNotificationFrames = frameCount / nBuffering;
2175 // If client requested a fast track but this was denied, then use the smaller maximum.
2176 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2177 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2178 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2179 maxNotificationFrames = maxNotificationFramesFastDenied;
2180 }
2181 }
2182 }
2183 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2184 if (notificationFrameCount == 0) {
2185 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2186 maxNotificationFrames, frameCount);
2187 } else {
2188 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2189 notificationFrameCount, maxNotificationFrames, frameCount);
2190 }
2191 notificationFrameCount = maxNotificationFrames;
2192 }
2193 }
2194
Glenn Kasten74935e42013-12-19 08:56:45 -08002195 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002196 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002197
Glenn Kastenc3df8382014-03-13 15:05:25 -07002198 switch (mType) {
2199
2200 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002201 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002202 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002203 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2204 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002205 sampleRate, format, channelMask, mOutput, mFormat);
2206 lStatus = BAD_VALUE;
2207 goto Exit;
2208 }
2209 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002210 break;
2211
2212 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002213 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002214 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2215 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002216 sampleRate, format, channelMask, mOutput, mFormat);
2217 lStatus = BAD_VALUE;
2218 goto Exit;
2219 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002220 break;
2221
2222 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002223 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002224 ALOGE("createTrack_l() Bad parameter: format %#x \""
2225 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002226 format, mOutput, mFormat);
2227 lStatus = BAD_VALUE;
2228 goto Exit;
2229 }
Andy Hungcd044842014-08-07 11:04:34 -07002230 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002231 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2232 lStatus = BAD_VALUE;
2233 goto Exit;
2234 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002235 break;
2236
Eric Laurent81784c32012-11-19 14:55:58 -08002237 }
2238
2239 lStatus = initCheck();
2240 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002241 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002242 goto Exit;
2243 }
2244
2245 { // scope for mLock
2246 Mutex::Autolock _l(mLock);
2247
2248 // all tracks in same audio session must share the same routing strategy otherwise
2249 // conflicts will happen when tracks are moved from one output to another by audio policy
2250 // manager
2251 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2252 for (size_t i = 0; i < mTracks.size(); ++i) {
2253 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002254 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002255 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2256 if (sessionId == t->sessionId() && strategy != actual) {
2257 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2258 strategy, actual);
2259 lStatus = BAD_VALUE;
2260 goto Exit;
2261 }
2262 }
2263 }
2264
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002265 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002266 channelMask, frameCount,
2267 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002268 sessionId, creatorPid, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002269
Glenn Kasten03003332013-08-06 15:40:54 -07002270 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2271 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002272 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002273 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002274 goto Exit;
2275 }
2276 mTracks.add(track);
2277
2278 sp<EffectChain> chain = getEffectChain_l(sessionId);
2279 if (chain != 0) {
2280 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2281 track->setMainBuffer(chain->inBuffer());
2282 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2283 chain->incTrackCnt();
2284 }
2285
Eric Laurent05067782016-06-01 18:27:28 -07002286 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002287 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2288 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2289 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002290 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002291 }
2292 }
2293
2294 lStatus = NO_ERROR;
2295
2296Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002297 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002298 return track;
2299}
2300
Andy Hung1bc088a2018-02-09 15:57:31 -08002301template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002302ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2303{
Andy Hungc0691382018-09-12 18:01:57 -07002304 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002305 const ssize_t index = mTracks.remove(track);
2306 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002307 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002308 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002309 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002310 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002311 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002312 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002313 }
2314 return index;
2315}
2316
Eric Laurent81784c32012-11-19 14:55:58 -08002317uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2318{
2319 return latency;
2320}
2321
2322uint32_t AudioFlinger::PlaybackThread::latency() const
2323{
2324 Mutex::Autolock _l(mLock);
2325 return latency_l();
2326}
2327uint32_t AudioFlinger::PlaybackThread::latency_l() const
2328{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002329 uint32_t latency;
2330 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2331 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002332 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002333 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002334}
2335
2336void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2337{
2338 Mutex::Autolock _l(mLock);
2339 // Don't apply master volume in SW if our HAL can do it for us.
2340 if (mOutput && mOutput->audioHwDev &&
2341 mOutput->audioHwDev->canSetMasterVolume()) {
2342 mMasterVolume = 1.0;
2343 } else {
2344 mMasterVolume = value;
2345 }
2346}
2347
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002348void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2349{
2350 mMasterBalance.store(balance);
2351}
2352
Eric Laurent81784c32012-11-19 14:55:58 -08002353void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2354{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002355 if (isDuplicating()) {
2356 return;
2357 }
Eric Laurent81784c32012-11-19 14:55:58 -08002358 Mutex::Autolock _l(mLock);
2359 // Don't apply master mute in SW if our HAL can do it for us.
2360 if (mOutput && mOutput->audioHwDev &&
2361 mOutput->audioHwDev->canSetMasterMute()) {
2362 mMasterMute = false;
2363 } else {
2364 mMasterMute = muted;
2365 }
2366}
2367
2368void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2369{
2370 Mutex::Autolock _l(mLock);
2371 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002372 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002373}
2374
2375void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2376{
2377 Mutex::Autolock _l(mLock);
2378 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002379 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002380}
2381
2382float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2383{
2384 Mutex::Autolock _l(mLock);
2385 return mStreamTypes[stream].volume;
2386}
2387
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002388void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2389{
2390 mOutput->stream->setVolume(left, right);
2391}
2392
Eric Laurent81784c32012-11-19 14:55:58 -08002393// addTrack_l() must be called with ThreadBase::mLock held
2394status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2395{
2396 status_t status = ALREADY_EXISTS;
2397
Eric Laurent81784c32012-11-19 14:55:58 -08002398 if (mActiveTracks.indexOf(track) < 0) {
2399 // the track is newly added, make sure it fills up all its
2400 // buffers before playing. This is to ensure the client will
2401 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002402 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002403 TrackBase::track_state state = track->mState;
2404 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002405 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002406 mLock.lock();
2407 // abort track was stopped/paused while we released the lock
2408 if (state != track->mState) {
2409 if (status == NO_ERROR) {
2410 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002411 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002412 mLock.lock();
2413 }
2414 return INVALID_OPERATION;
2415 }
2416 // abort if start is rejected by audio policy manager
2417 if (status != NO_ERROR) {
2418 return PERMISSION_DENIED;
2419 }
2420#ifdef ADD_BATTERY_DATA
2421 // to track the speaker usage
2422 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2423#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002424 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002425 }
2426
Eric Laurent51716182016-02-29 18:00:56 -08002427 // set retry count for buffer fill
2428 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002429 if (track->isStopping_1()) {
2430 track->mRetryCount = kMaxTrackStopRetriesOffload;
2431 } else {
2432 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2433 }
2434 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002435 } else {
2436 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002437 track->mFillingUpStatus =
2438 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002439 }
2440
jiabin245cdd92018-12-07 17:55:15 -08002441 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2442 && mHapticChannelMask != AUDIO_CHANNEL_NONE) {
jiabin57303cc2018-12-18 15:45:57 -08002443 // Unlock due to VibratorService will lock for this call and will
2444 // call Tracks.mute/unmute which also require thread's lock.
2445 mLock.unlock();
2446 const int intensity = AudioFlinger::onExternalVibrationStart(
2447 track->getExternalVibration());
2448 mLock.lock();
jiabinbf6b0ec2019-02-12 12:30:12 -08002449 track->setHapticIntensity(static_cast<AudioMixer::haptic_intensity_t>(intensity));
jiabin57303cc2018-12-18 15:45:57 -08002450 // Haptic playback should be enabled by vibrator service.
2451 if (track->getHapticPlaybackEnabled()) {
2452 // Disable haptic playback of all active track to ensure only
2453 // one track playing haptic if current track should play haptic.
2454 for (const auto &t : mActiveTracks) {
2455 t->setHapticPlaybackEnabled(false);
2456 }
jiabin245cdd92018-12-07 17:55:15 -08002457 }
jiabin245cdd92018-12-07 17:55:15 -08002458 }
2459
Eric Laurent81784c32012-11-19 14:55:58 -08002460 track->mResetDone = false;
2461 track->mPresentationCompleteFrames = 0;
2462 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002463 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2464 if (chain != 0) {
2465 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2466 track->sessionId());
2467 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002468 }
2469
2470 status = NO_ERROR;
2471 }
2472
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002473 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002474 return status;
2475}
2476
Eric Laurentbfb1b832013-01-07 09:53:42 -08002477bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002478{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002479 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002480 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002481 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2482 track->mState = TrackBase::STOPPED;
2483 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002484 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002485 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002486 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002487 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002488
2489 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002490}
2491
2492void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2493{
2494 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002495
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002496 String8 result;
2497 track->appendDump(result, false /* active */);
2498 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002499
Eric Laurent81784c32012-11-19 14:55:58 -08002500 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002501 if (track->isFastTrack()) {
2502 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002503 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002504 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2505 mFastTrackAvailMask |= 1 << index;
2506 // redundant as track is about to be destroyed, for dumpsys only
2507 track->mFastIndex = -1;
2508 }
2509 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2510 if (chain != 0) {
2511 chain->decTrackCnt();
2512 }
2513}
2514
2515String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2516{
Eric Laurent81784c32012-11-19 14:55:58 -08002517 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002518 String8 out_s8;
2519 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2520 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002521 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002522 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002523}
2524
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002525status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2526 Mutex::Autolock _l(mLock);
2527 if (mOutput == nullptr || mOutput->stream == nullptr) {
2528 return NO_INIT;
2529 }
2530 return mOutput->stream->selectPresentation(presentationId, programId);
2531}
2532
Eric Laurent09f1ed22019-04-24 17:45:17 -07002533void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
2534 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002535 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2536 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002537
Eric Laurent73e26b62015-04-27 16:55:58 -07002538 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002539
2540 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002541 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002542 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002543 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002544 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002545 desc->mChannelMask = mChannelMask;
2546 desc->mSamplingRate = mSampleRate;
2547 desc->mFormat = mFormat;
2548 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002549 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002550 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002551 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002552 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002553 case AUDIO_CLIENT_STARTED:
2554 desc->mPatch = mPatch;
2555 desc->mPortId = portId;
2556 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002557 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002558 default:
2559 break;
2560 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002561 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002562}
2563
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002564void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002565{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002566 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002567}
2568
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002569void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002570{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002571 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002572}
2573
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002574void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002575{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002576 mCallbackThread->setAsyncError();
2577}
2578
Eric Laurent3b4529e2013-09-05 18:09:19 -07002579void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002580{
2581 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002582 // reject out of sequence requests
2583 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2584 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002585 mWaitWorkCV.signal();
2586 }
2587}
2588
Eric Laurent3b4529e2013-09-05 18:09:19 -07002589void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002590{
2591 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002592 // reject out of sequence requests
2593 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002594 // Register discontinuity when HW drain is completed because that can cause
2595 // the timestamp frame position to reset to 0 for direct and offload threads.
2596 // (Out of sequence requests are ignored, since the discontinuity would be handled
2597 // elsewhere, e.g. in flush).
2598 mTimestampVerifier.discontinuity();
Eric Laurent3b4529e2013-09-05 18:09:19 -07002599 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002600 mWaitWorkCV.signal();
2601 }
2602}
2603
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002604void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002605{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002606 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002607 mSampleRate = mOutput->getSampleRate();
2608 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002609 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002610 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002611 }
Andy Hung9a592762014-07-21 21:56:01 -07002612 if ((mType == MIXER || mType == DUPLICATING)
2613 && !isValidPcmSinkChannelMask(mChannelMask)) {
2614 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2615 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002616 }
Andy Hunge5412692014-05-16 11:25:07 -07002617 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002618 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002619
2620 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002621 status_t result = mOutput->stream->getFormat(&mHALFormat);
2622 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002623 // Get format from the shim, which will be different than the HAL format
2624 // if playing compressed audio over HDMI passthrough.
2625 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002626 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002627 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002628 }
Andy Hung6146c082014-03-18 11:56:15 -07002629 if ((mType == MIXER || mType == DUPLICATING)
2630 && !isValidPcmSinkFormat(mFormat)) {
2631 LOG_FATAL("HAL format %#x not supported for mixed output",
2632 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002633 }
Phil Burk062e67a2015-02-11 13:40:50 -08002634 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002635 result = mOutput->stream->getBufferSize(&mBufferSize);
2636 LOG_ALWAYS_FATAL_IF(result != OK,
2637 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002638 mFrameCount = mBufferSize / mFrameSize;
Dean Wheatley77cbebd2019-04-23 14:18:44 +10002639 if ((mType == MIXER || mType == DUPLICATING) && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002640 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002641 mFrameCount);
2642 }
2643
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002644 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2645 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002646 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002647 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002648 }
2649 }
2650
Eric Laurentd1f69b02014-12-15 14:33:13 -08002651 mHwSupportsPause = false;
2652 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002653 bool supportsPause = false, supportsResume = false;
2654 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2655 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002656 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002657 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002658 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002659 } else if (supportsResume) {
2660 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002661 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002662 }
2663 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002664 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2665 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2666 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002667
Andy Hungfbfc3952015-01-15 13:33:51 -08002668 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2669 // For best precision, we use float instead of the associated output
2670 // device format (typically PCM 16 bit).
2671
2672 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2673 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2674 mBufferSize = mFrameSize * mFrameCount;
2675
2676 // TODO: We currently use the associated output device channel mask and sample rate.
2677 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2678 // (if a valid mask) to avoid premature downmix.
2679 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2680 // instead of the output device sample rate to avoid loss of high frequency information.
2681 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2682 }
2683
Andy Hung09a50072014-02-27 14:30:47 -08002684 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002685 double multiplier = 1.0;
2686 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2687 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002688 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2689 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002690
Eric Laurent81784c32012-11-19 14:55:58 -08002691 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2692 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2693 maxNormalFrameCount = maxNormalFrameCount & ~15;
2694 if (maxNormalFrameCount < minNormalFrameCount) {
2695 maxNormalFrameCount = minNormalFrameCount;
2696 }
2697 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2698 if (multiplier <= 1.0) {
2699 multiplier = 1.0;
2700 } else if (multiplier <= 2.0) {
2701 if (2 * mFrameCount <= maxNormalFrameCount) {
2702 multiplier = 2.0;
2703 } else {
2704 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2705 }
2706 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002707 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002708 }
2709 }
2710 mNormalFrameCount = multiplier * mFrameCount;
2711 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002712 if (mType == MIXER || mType == DUPLICATING) {
2713 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2714 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002715 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002716 mNormalFrameCount);
2717
Andy Hung08fb1742015-05-31 23:22:10 -07002718 // Check if we want to throttle the processing to no more than 2x normal rate
2719 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002720 mThreadThrottleTimeMs = 0;
2721 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002722 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2723
Andy Hung010a1a12014-03-13 13:57:33 -07002724 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2725 // Originally this was int16_t[] array, need to remove legacy implications.
2726 free(mSinkBuffer);
2727 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002728 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2729 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2730 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002731 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002732
Andy Hung69aed5f2014-02-25 17:24:40 -08002733 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2734 // drives the output.
2735 free(mMixerBuffer);
2736 mMixerBuffer = NULL;
2737 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002738 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Andy Hung69aed5f2014-02-25 17:24:40 -08002739 mMixerBufferSize = mNormalFrameCount * mChannelCount
2740 * audio_bytes_per_sample(mMixerBufferFormat);
2741 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2742 }
Andy Hung98ef9782014-03-04 14:46:50 -08002743 free(mEffectBuffer);
2744 mEffectBuffer = NULL;
2745 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002746 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002747 mEffectBufferSize = mNormalFrameCount * mChannelCount
2748 * audio_bytes_per_sample(mEffectBufferFormat);
2749 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2750 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002751
jiabin245cdd92018-12-07 17:55:15 -08002752 mHapticChannelMask = mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL;
2753 mChannelMask &= ~mHapticChannelMask;
2754 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2755 mChannelCount -= mHapticChannelCount;
2756
Eric Laurent81784c32012-11-19 14:55:58 -08002757 // force reconfiguration of effect chains and engines to take new buffer size and audio
2758 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002759 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002760 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2761 // matter.
2762 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2763 Vector< sp<EffectChain> > effectChains = mEffectChains;
2764 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07002765 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
2766 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08002767 }
2768}
2769
Kevin Rocard069c2712018-03-29 19:09:14 -07002770void AudioFlinger::PlaybackThread::updateMetadata_l()
2771{
Kevin Rocard12381092018-04-11 09:19:59 -07002772 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2773 return; // That should not happen
2774 }
2775 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2776 for (const sp<Track> &track : mActiveTracks) {
2777 // Do not short-circuit as all hasChanged states must be reset
2778 // as all the metadata are going to be sent
2779 hasChanged |= track->readAndClearHasChanged();
2780 }
2781 if (!hasChanged) {
2782 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002783 }
2784 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002785 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002786 for (const sp<Track> &track : mActiveTracks) {
2787 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002788 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002789 }
Kevin Rocard12381092018-04-11 09:19:59 -07002790 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002791}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002792
Kevin Rocard12381092018-04-11 09:19:59 -07002793void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2794 const StreamOutHalInterface::SourceMetadata& metadata)
2795{
2796 mOutput->stream->updateSourceMetadata(metadata);
2797};
2798
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002799status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002800{
2801 if (halFrames == NULL || dspFrames == NULL) {
2802 return BAD_VALUE;
2803 }
2804 Mutex::Autolock _l(mLock);
2805 if (initCheck() != NO_ERROR) {
2806 return INVALID_OPERATION;
2807 }
Andy Hung818e7a32016-02-16 18:08:07 -08002808 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002809 *halFrames = framesWritten;
2810
2811 if (isSuspended()) {
2812 // return an estimation of rendered frames when the output is suspended
2813 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002814 *dspFrames = (uint32_t)
2815 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002816 return NO_ERROR;
2817 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002818 status_t status;
2819 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002820 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002821 *dspFrames = (size_t)frames;
2822 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002823 }
2824}
2825
Glenn Kastend848eb42016-03-08 13:42:11 -08002826uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002827{
2828 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2829 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2830 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2831 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2832 }
2833 for (size_t i = 0; i < mTracks.size(); i++) {
2834 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002835 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002836 return AudioSystem::getStrategyForStream(track->streamType());
2837 }
2838 }
2839 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2840}
2841
2842
Phil Burk062e67a2015-02-11 13:40:50 -08002843AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002844{
2845 Mutex::Autolock _l(mLock);
2846 return mOutput;
2847}
2848
Phil Burk062e67a2015-02-11 13:40:50 -08002849AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002850{
2851 Mutex::Autolock _l(mLock);
2852 AudioStreamOut *output = mOutput;
2853 mOutput = NULL;
2854 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2855 // must push a NULL and wait for ack
2856 mOutputSink.clear();
2857 mPipeSink.clear();
2858 mNormalSink.clear();
2859 return output;
2860}
2861
2862// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002863sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002864{
2865 if (mOutput == NULL) {
2866 return NULL;
2867 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002868 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002869}
2870
2871uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2872{
2873 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2874}
2875
2876status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2877{
2878 if (!isValidSyncEvent(event)) {
2879 return BAD_VALUE;
2880 }
2881
2882 Mutex::Autolock _l(mLock);
2883
2884 for (size_t i = 0; i < mTracks.size(); ++i) {
2885 sp<Track> track = mTracks[i];
2886 if (event->triggerSession() == track->sessionId()) {
2887 (void) track->setSyncEvent(event);
2888 return NO_ERROR;
2889 }
2890 }
2891
2892 return NAME_NOT_FOUND;
2893}
2894
2895bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2896{
2897 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2898}
2899
2900void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2901 const Vector< sp<Track> >& tracksToRemove)
2902{
Andy Hungfe726a62018-09-27 15:17:25 -07002903 // Miscellaneous track cleanup when removed from the active list,
2904 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002905#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07002906 for (const auto& track : tracksToRemove) {
2907 if (track->isExternalTrack()) {
2908 // to track the speaker usage
2909 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08002910 }
2911 }
Andy Hungfe726a62018-09-27 15:17:25 -07002912#else
2913 (void)tracksToRemove; // suppress unused warning
2914#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002915}
2916
2917void AudioFlinger::PlaybackThread::checkSilentMode_l()
2918{
2919 if (!mMasterMute) {
2920 char value[PROPERTY_VALUE_MAX];
jiabinc52b1ff2019-10-31 17:20:42 -07002921 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002922 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2923 return;
2924 }
Eric Laurent81784c32012-11-19 14:55:58 -08002925 if (property_get("ro.audio.silent", value, "0") > 0) {
2926 char *endptr;
2927 unsigned long ul = strtoul(value, &endptr, 0);
2928 if (*endptr == '\0' && ul != 0) {
2929 ALOGD("Silence is golden");
2930 // The setprop command will not allow a property to be changed after
2931 // the first time it is set, so we don't have to worry about un-muting.
2932 setMasterMute_l(true);
2933 }
2934 }
2935 }
2936}
2937
2938// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002939ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002940{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002941 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002942 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002943 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002944 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002945
2946 // If an NBAIO sink is present, use it to write the normal mixer's submix
2947 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002948
Andy Hung010a1a12014-03-13 13:57:33 -07002949 const size_t count = mBytesRemaining / mFrameSize;
2950
Simon Wilson2d590962012-11-29 15:18:50 -08002951 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002952 // update the setpoint when AudioFlinger::mScreenState changes
2953 uint32_t screenState = AudioFlinger::mScreenState;
2954 if (screenState != mScreenState) {
2955 mScreenState = screenState;
2956 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2957 if (pipe != NULL) {
2958 pipe->setAvgFrames((mScreenState & 1) ?
2959 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2960 }
2961 }
Andy Hung010a1a12014-03-13 13:57:33 -07002962 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002963 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002964 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002965 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07002966#ifdef TEE_SINK
2967 mTee.write((char *)mSinkBuffer + offset, framesWritten);
2968#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002969 } else {
2970 bytesWritten = framesWritten;
2971 }
2972 // otherwise use the HAL / AudioStreamOut directly
2973 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002974 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002975
Eric Laurentbfb1b832013-01-07 09:53:42 -08002976 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002977 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2978 mWriteAckSequence += 2;
2979 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002980 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002981 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002982 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07002983 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07002984 // FIXME We should have an implementation of timestamps for direct output threads.
2985 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002986 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07002987 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08002988
Eric Laurentbfb1b832013-01-07 09:53:42 -08002989 if (mUseAsyncWrite &&
2990 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2991 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002992 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002993 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002994 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002995 }
Eric Laurent81784c32012-11-19 14:55:58 -08002996 }
2997
Eric Laurent81784c32012-11-19 14:55:58 -08002998 mNumWrites++;
2999 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07003000 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003001 return bytesWritten;
3002}
3003
3004void AudioFlinger::PlaybackThread::threadLoop_drain()
3005{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003006 bool supportsDrain = false;
3007 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003008 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3009 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003010 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3011 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003012 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003013 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003014 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003015 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003016 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003017 }
3018}
3019
3020void AudioFlinger::PlaybackThread::threadLoop_exit()
3021{
Eric Laurent275e8e92014-11-30 15:14:47 -08003022 {
3023 Mutex::Autolock _l(mLock);
3024 for (size_t i = 0; i < mTracks.size(); i++) {
3025 sp<Track> track = mTracks[i];
3026 track->invalidate();
3027 }
Andy Hungdae27702016-10-31 14:01:16 -07003028 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3029 // After we exit there are no more track changes sent to BatteryNotifier
3030 // because that requires an active threadLoop.
3031 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3032 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003033 }
Eric Laurent81784c32012-11-19 14:55:58 -08003034}
3035
3036/*
3037The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003038 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003039 - mActiveSleepTimeUs from activeSleepTimeUs()
3040 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003041 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3042 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003043 - maxPeriod from frame count and sample rate (MIXER only)
3044
3045The parameters that affect these derived values are:
3046 - frame count
3047 - frame size
3048 - sample rate
3049 - device type: A2DP or not
3050 - device latency
3051 - format: PCM or not
3052 - active sleep time
3053 - idle sleep time
3054*/
3055
3056void AudioFlinger::PlaybackThread::cacheParameters_l()
3057{
Andy Hung25c2dac2014-02-27 14:56:00 -08003058 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003059 mActiveSleepTimeUs = activeSleepTimeUs();
3060 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003061
3062 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3063 // truncating audio when going to standby.
3064 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003065 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003066 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3067 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3068 }
3069 }
Eric Laurent81784c32012-11-19 14:55:58 -08003070}
3071
Eric Laurent13084622016-05-17 10:51:49 -07003072bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003073{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003074 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003075 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003076 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003077 size_t size = mTracks.size();
3078 for (size_t i = 0; i < size; i++) {
3079 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003080 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003081 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003082 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003083 }
3084 }
Eric Laurent13084622016-05-17 10:51:49 -07003085 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003086}
3087
Haynes Mathew George05317d22016-05-03 16:34:26 -07003088void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3089{
3090 Mutex::Autolock _l(mLock);
3091 invalidateTracks_l(streamType);
3092}
3093
Eric Laurent81784c32012-11-19 14:55:58 -08003094status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3095{
Glenn Kastend848eb42016-03-08 13:42:11 -08003096 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003097 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003098 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003099 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3100 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3101 &halInBuffer);
3102 if (result != OK) return result;
3103 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003104 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003105 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08003106 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08003107 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003108 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003109 if (mType != DIRECT) {
jiabin245cdd92018-12-07 17:55:15 -08003110 size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003111 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003112 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003113 &halInBuffer);
3114 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003115#ifdef FLOAT_EFFECT_CHAIN
3116 buffer = halInBuffer->audioBuffer()->f32;
3117#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003118 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003119#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003120 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3121 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003122 }
3123
3124 // Attach all tracks with same session ID to this chain.
3125 for (size_t i = 0; i < mTracks.size(); ++i) {
3126 sp<Track> track = mTracks[i];
3127 if (session == track->sessionId()) {
3128 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3129 buffer);
3130 track->setMainBuffer(buffer);
3131 chain->incTrackCnt();
3132 }
3133 }
3134
3135 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003136 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003137 if (session == track->sessionId()) {
3138 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3139 chain->incActiveTrackCnt();
3140 }
3141 }
3142 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003143 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003144 chain->setInBuffer(halInBuffer);
3145 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003146 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08003147 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08003148 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3149 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003150 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003151 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003152 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003153 // Effect chain for other sessions are inserted at beginning of effect
3154 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003155 // sessions is not important.
3156 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3157 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
3158 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003159 size_t size = mEffectChains.size();
3160 size_t i = 0;
3161 for (i = 0; i < size; i++) {
3162 if (mEffectChains[i]->sessionId() < session) {
3163 break;
3164 }
3165 }
3166 mEffectChains.insertAt(chain, i);
3167 checkSuspendOnAddEffectChain_l(chain);
3168
3169 return NO_ERROR;
3170}
3171
3172size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3173{
Glenn Kastend848eb42016-03-08 13:42:11 -08003174 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003175
3176 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3177
3178 for (size_t i = 0; i < mEffectChains.size(); i++) {
3179 if (chain == mEffectChains[i]) {
3180 mEffectChains.removeAt(i);
3181 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003182 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003183 if (session == track->sessionId()) {
3184 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3185 chain.get(), session);
3186 chain->decActiveTrackCnt();
3187 }
3188 }
3189
3190 // detach all tracks with same session ID from this chain
3191 for (size_t i = 0; i < mTracks.size(); ++i) {
3192 sp<Track> track = mTracks[i];
3193 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003194 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003195 chain->decTrackCnt();
3196 }
3197 }
3198 break;
3199 }
3200 }
3201 return mEffectChains.size();
3202}
3203
3204status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003205 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003206{
3207 Mutex::Autolock _l(mLock);
3208 return attachAuxEffect_l(track, EffectId);
3209}
3210
3211status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003212 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003213{
3214 status_t status = NO_ERROR;
3215
3216 if (EffectId == 0) {
3217 track->setAuxBuffer(0, NULL);
3218 } else {
3219 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3220 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3221 if (effect != 0) {
3222 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3223 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3224 } else {
3225 status = INVALID_OPERATION;
3226 }
3227 } else {
3228 status = BAD_VALUE;
3229 }
3230 }
3231 return status;
3232}
3233
3234void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3235{
3236 for (size_t i = 0; i < mTracks.size(); ++i) {
3237 sp<Track> track = mTracks[i];
3238 if (track->auxEffectId() == effectId) {
3239 attachAuxEffect_l(track, 0);
3240 }
3241 }
3242}
3243
3244bool AudioFlinger::PlaybackThread::threadLoop()
3245{
Glenn Kasten388d5712017-04-07 14:38:41 -07003246 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003247
Eric Laurent81784c32012-11-19 14:55:58 -08003248 Vector< sp<Track> > tracksToRemove;
3249
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003250 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003251 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
3252 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003253
3254 // MIXER
3255 nsecs_t lastWarning = 0;
3256
3257 // DUPLICATING
3258 // FIXME could this be made local to while loop?
3259 writeFrames = 0;
3260
3261 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003262 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003263
3264 if (mType == MIXER) {
3265 sleepTimeShift = 0;
3266 }
3267
3268 CpuStats cpuStats;
3269 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3270
3271 acquireWakeLock();
3272
Glenn Kasteneef598c2017-04-03 14:41:13 -07003273 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3274 // thread associated with this PlaybackThread.
3275 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3276 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003277 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3278 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003279 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003280 const char *logString = NULL;
3281
rago1bb90822017-05-02 18:31:48 -07003282 // Estimated time for next buffer to be written to hal. This is used only on
3283 // suspended mode (for now) to help schedule the wait time until next iteration.
3284 nsecs_t timeLoopNextNs = 0;
3285
Eric Laurent664539d2013-09-23 18:24:31 -07003286 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003287
Andy Hungf3234512018-07-03 14:51:47 -07003288 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
3289 // TODO: add confirmation checks:
3290 // 1) DIRECT threads and linear PCM format really resets to 0?
3291 // 2) Is frame count really valid if not linear pcm?
3292 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
3293 if (mType == OFFLOAD || mType == DIRECT) {
3294 mTimestampVerifier.setDiscontinuityMode(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
3295 }
Andy Hung2dbffc22018-08-08 18:50:41 -07003296 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003297
Andy Hung446f4df2019-02-21 12:26:41 -08003298 // loopCount is used for statistics and diagnostics.
3299 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003300 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003301 // Log merge requests are performed during AudioFlinger binder transactions, but
3302 // that does not cover audio playback. It's requested here for that reason.
3303 mAudioFlinger->requestLogMerge();
3304
Eric Laurent81784c32012-11-19 14:55:58 -08003305 cpuStats.sample(myName);
3306
3307 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003308 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003309 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003310
Andy Hung2dbffc22018-08-08 18:50:41 -07003311 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3312 //
jiabinc52b1ff2019-10-31 17:20:42 -07003313 // Note: we access outDeviceTypes() outside of mLock.
3314 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003315 // Here, we try for the AF lock, but do not block on it as the latency
3316 // is more informational.
3317 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3318 std::vector<PatchPanel::SoftwarePatch> swPatches;
3319 double latencyMs;
3320 status_t status = INVALID_OPERATION;
3321 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3322 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3323 && swPatches.size() > 0) {
3324 status = swPatches[0].getLatencyMs_l(&latencyMs);
3325 downstreamPatchHandle = swPatches[0].getPatchHandle();
3326 }
3327 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003328 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003329 lastDownstreamPatchHandle = downstreamPatchHandle;
3330 }
3331 if (status == OK) {
3332 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003333 // latency of 5 seconds).
3334 const double minLatency = 0., maxLatency = 5000.;
3335 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003336 ALOGV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003337 } else {
3338 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003339 if (latencyMs < minLatency) latencyMs = minLatency;
3340 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003341 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003342 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003343 }
3344 mAudioFlinger->mLock.unlock();
3345 }
3346 } else {
3347 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3348 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003349 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003350 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3351 }
3352 }
3353
Eric Laurent81784c32012-11-19 14:55:58 -08003354 { // scope for mLock
3355
3356 Mutex::Autolock _l(mLock);
3357
Eric Laurent021cf962014-05-13 10:18:14 -07003358 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003359
Glenn Kasteneef598c2017-04-03 14:41:13 -07003360 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003361 if (logString != NULL) {
3362 mNBLogWriter->logTimestamp();
3363 mNBLogWriter->log(logString);
3364 logString = NULL;
3365 }
3366
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003367 // Collect timestamp statistics for the Playback Thread types that support it.
3368 if (mType == MIXER
3369 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07003370 || mType == DIRECT
3371 || mType == OFFLOAD) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003372 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003373 // and associate with the sink frames written out. We need
3374 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003375 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003376 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003377 if (mStandby) {
3378 mTimestampVerifier.discontinuity();
3379 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3380 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3381 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3382 mSampleRate);
Andy Hungc8fddf32018-08-08 18:32:37 -07003383
3384 if (isTimestampCorrectionEnabled()) {
3385 ALOGV("TS_BEFORE: %d %lld %lld", id(),
3386 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3387 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
3388 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
3389 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3390 = correctedTimestamp.mFrames;
3391 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
3392 = correctedTimestamp.mTimeNs;
3393 ALOGV("TS_AFTER: %d %lld %lld", id(),
3394 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3395 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
Andy Hung2dbffc22018-08-08 18:50:41 -07003396
3397 // Note: Downstream latency only added if timestamp correction enabled.
Dean Wheatley30d28422018-11-06 10:27:40 +11003398 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
Andy Hung2dbffc22018-08-08 18:50:41 -07003399 const int64_t newPosition =
3400 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
Dean Wheatley30d28422018-11-06 10:27:40 +11003401 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
Andy Hung2dbffc22018-08-08 18:50:41 -07003402 // prevent retrograde
3403 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
3404 newPosition,
3405 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3406 - mSuspendedFrames));
3407 }
Andy Hungc8fddf32018-08-08 18:32:37 -07003408 }
3409
Andy Hung818e7a32016-02-16 18:08:07 -08003410 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003411 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003412
3413 // We keep track of the last valid kernel position in case we are in underrun
3414 // and the normal mixer period is the same as the fast mixer period, or there
3415 // is some error from the HAL.
3416 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3417 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3418 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3419 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3420 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3421
3422 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3423 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3424 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3425 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003426 }
3427
3428 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3429 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003430 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003431 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003432 }
3433
Andy Hung818e7a32016-02-16 18:08:07 -08003434 // copy over kernel info
3435 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003436 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3437 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003438 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3439 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003440 } else {
3441 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003442 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003443
Andy Hungc54b1ff2016-02-23 14:07:07 -08003444 // mFramesWritten for non-offloaded tracks are contiguous
3445 // even after standby() is called. This is useful for the track frame
3446 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003447 bool serverLocationUpdate = false;
3448 if (mFramesWritten != lastFramesWritten) {
3449 serverLocationUpdate = true;
3450 lastFramesWritten = mFramesWritten;
3451 }
3452 // Only update timestamps if there is a meaningful change.
3453 // Either the kernel timestamp must be valid or we have written something.
3454 if (kernelLocationUpdate || serverLocationUpdate) {
3455 if (serverLocationUpdate) {
3456 // use the time before we called the HAL write - it is a bit more accurate
3457 // to when the server last read data than the current time here.
3458 //
Andy Hung446f4df2019-02-21 12:26:41 -08003459 // If we haven't written anything, mLastIoBeginNs will be -1
Andy Hung69488c42016-05-16 18:43:33 -07003460 // and we use systemTime().
3461 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
Andy Hung446f4df2019-02-21 12:26:41 -08003462 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
3463 ? systemTime() : mLastIoBeginNs;
Andy Hung69488c42016-05-16 18:43:33 -07003464 }
Andy Hungdae27702016-10-31 14:01:16 -07003465
3466 for (const sp<Track> &t : mActiveTracks) {
3467 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003468 t->updateTrackFrameInfo(
3469 t->mAudioTrackServerProxy->framesReleased(),
3470 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003471 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003472 mTimestamp);
3473 }
Andy Hunge10393e2015-06-12 13:59:33 -07003474 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003475 }
Andy Hunge6c37112019-02-26 17:38:10 -08003476
3477 if (audio_has_proportional_frames(mFormat)) {
3478 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
3479 if (latencyMs != 0.) { // note 0. means timestamp is empty.
3480 mLatencyMs.add(latencyMs);
3481 }
3482 }
3483
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003484 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003485#if 0
3486 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003487 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003488 timespec ts;
3489 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003490 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003491 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003492 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003493 }
3494 ++z;
3495#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003496 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003497 if (mSignalPending) {
3498 // A signal was raised while we were unlocked
3499 mSignalPending = false;
3500 } else if (waitingAsyncCallback_l()) {
3501 if (exitPending()) {
3502 break;
3503 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003504 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003505 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003506 releaseWakeLock_l();
3507 released = true;
3508 }
Andy Hung10cbff12017-02-21 17:30:14 -08003509
3510 const int64_t waitNs = computeWaitTimeNs_l();
3511 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3512 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3513 if (status == TIMED_OUT) {
3514 mSignalPending = true; // if timeout recheck everything
3515 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003516 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003517 if (released) {
3518 acquireWakeLock_l();
3519 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003520 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3521 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003522
3523 continue;
3524 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003525 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003526 isSuspended()) {
3527 // put audio hardware into standby after short delay
3528 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003529
3530 threadLoop_standby();
3531
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003532 // This is where we go into standby
3533 if (!mStandby) {
3534 LOG_AUDIO_STATE();
3535 }
Eric Laurent81784c32012-11-19 14:55:58 -08003536 mStandby = true;
Andy Hungd0979812019-02-21 15:51:44 -08003537 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003538 }
3539
Eric Tan39ec8d62018-07-24 09:49:29 -07003540 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003541 // we're about to wait, flush the binder command buffer
3542 IPCThreadState::self()->flushCommands();
3543
3544 clearOutputTracks();
3545
3546 if (exitPending()) {
3547 break;
3548 }
3549
3550 releaseWakeLock_l();
3551 // wait until we have something to do...
3552 ALOGV("%s going to sleep", myName.string());
3553 mWaitWorkCV.wait(mLock);
3554 ALOGV("%s waking up", myName.string());
3555 acquireWakeLock_l();
3556
3557 mMixerStatus = MIXER_IDLE;
3558 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3559 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003560 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003561 checkSilentMode_l();
3562
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003563 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3564 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003565 if (mType == MIXER) {
3566 sleepTimeShift = 0;
3567 }
3568
3569 continue;
3570 }
3571 }
Eric Laurent81784c32012-11-19 14:55:58 -08003572 // mMixerStatusIgnoringFastTracks is also updated internally
3573 mMixerStatus = prepareTracks_l(&tracksToRemove);
3574
Andy Hungdae27702016-10-31 14:01:16 -07003575 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003576
Kevin Rocard069c2712018-03-29 19:09:14 -07003577 updateMetadata_l();
3578
Eric Laurent81784c32012-11-19 14:55:58 -08003579 // prevent any changes in effect chain list and in each effect chain
3580 // during mixing and effect process as the audio buffers could be deleted
3581 // or modified if an effect is created or deleted
3582 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003583
3584 // Determine which session to pick up haptic data.
3585 // This must be done under the same lock as prepareTracks_l().
3586 // TODO: Write haptic data directly to sink buffer when mixing.
3587 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3588 for (const auto& track : mActiveTracks) {
3589 if (track->getHapticPlaybackEnabled()) {
3590 activeHapticSessionId = track->sessionId();
3591 break;
3592 }
3593 }
3594 }
3595
Andy Hungc1646382019-04-30 16:12:10 -07003596 // Acquire a local copy of active tracks with lock (release w/o lock).
3597 //
3598 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3599 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3600 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3601 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003602 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003603
Eric Laurentbfb1b832013-01-07 09:53:42 -08003604 if (mBytesRemaining == 0) {
3605 mCurrentWriteLength = 0;
3606 if (mMixerStatus == MIXER_TRACKS_READY) {
3607 // threadLoop_mix() sets mCurrentWriteLength
3608 threadLoop_mix();
3609 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3610 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003611 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003612 // must be written to HAL
3613 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003614 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003615 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003616
3617 // Tally underrun frames as we are inserting 0s here.
3618 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003619 if (track->mFillingUpStatus == Track::FS_ACTIVE
3620 && !track->isStopped()
3621 && !track->isPaused()
3622 && !track->isTerminated()) {
3623 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3624 __func__, track->id(), track->getTrackStateAsString(),
3625 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003626 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3627 }
3628 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003629 }
3630 }
Andy Hung98ef9782014-03-04 14:46:50 -08003631 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003632 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003633 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3634 // or mSinkBuffer (if there are no effects).
3635 //
3636 // This is done pre-effects computation; if effects change to
3637 // support higher precision, this needs to move.
3638 //
3639 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003640 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003641 if (mMixerBufferValid) {
3642 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3643 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3644
Andy Hung2ddee192015-12-18 17:34:44 -08003645 // mono blend occurs for mixer threads only (not direct or offloaded)
3646 // and is handled here if we're going directly to the sink.
3647 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003648 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3649 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003650 }
3651
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003652 if (!hasFastMixer()) {
3653 // Balance must take effect after mono conversion.
3654 // We do it here if there is no FastMixer.
3655 // mBalance detects zero balance within the class for speed (not needed here).
3656 mBalance.setBalance(mMasterBalance.load());
3657 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3658 }
3659
Andy Hung98ef9782014-03-04 14:46:50 -08003660 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003661 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3662
3663 // If we're going directly to the sink and there are haptic channels,
3664 // we should adjust channels as the sample data is partially interleaved
3665 // in this case.
3666 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3667 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3668 mChannelCount + mHapticChannelCount,
3669 audio_bytes_per_sample(format),
3670 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3671 }
Andy Hung98ef9782014-03-04 14:46:50 -08003672 }
3673
Eric Laurentbfb1b832013-01-07 09:53:42 -08003674 mBytesRemaining = mCurrentWriteLength;
3675 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003676 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3677 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3678 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3679 mBytesWritten += mBytesRemaining;
3680 mFramesWritten += framesRemaining;
3681 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003682 mBytesRemaining = 0;
3683 }
Eric Laurent81784c32012-11-19 14:55:58 -08003684
Eric Laurentbfb1b832013-01-07 09:53:42 -08003685 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003686 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003687 for (size_t i = 0; i < effectChains.size(); i ++) {
3688 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003689 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003690 if (activeHapticSessionId != AUDIO_SESSION_NONE
3691 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003692 // Haptic data is active in this case, copy it directly from
3693 // in buffer to out buffer.
3694 const size_t audioBufferSize = mNormalFrameCount
3695 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3696 memcpy_by_audio_format(
3697 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3698 EFFECT_BUFFER_FORMAT,
3699 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3700 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3701 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003702 }
Eric Laurent81784c32012-11-19 14:55:58 -08003703 }
3704 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003705 // Process effect chains for offloaded thread even if no audio
3706 // was read from audio track: process only updates effect state
3707 // and thus does have to be synchronized with audio writes but may have
3708 // to be called while waiting for async write callback
3709 if (mType == OFFLOAD) {
3710 for (size_t i = 0; i < effectChains.size(); i ++) {
3711 effectChains[i]->process_l();
3712 }
3713 }
Eric Laurent81784c32012-11-19 14:55:58 -08003714
Andy Hung98ef9782014-03-04 14:46:50 -08003715 // Only if the Effects buffer is enabled and there is data in the
3716 // Effects buffer (buffer valid), we need to
3717 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003718 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003719 if (mEffectBufferValid) {
3720 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003721
3722 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003723 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3724 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003725 }
3726
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003727 if (!hasFastMixer()) {
3728 // Balance must take effect after mono conversion.
3729 // We do it here if there is no FastMixer.
3730 // mBalance detects zero balance within the class for speed (not needed here).
3731 mBalance.setBalance(mMasterBalance.load());
3732 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3733 }
3734
Andy Hung98ef9782014-03-04 14:46:50 -08003735 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003736 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3737 // The sample data is partially interleaved when haptic channels exist,
3738 // we need to adjust channels here.
3739 if (mHapticChannelCount > 0) {
3740 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3741 mChannelCount + mHapticChannelCount,
3742 audio_bytes_per_sample(mFormat),
3743 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3744 }
Andy Hung98ef9782014-03-04 14:46:50 -08003745 }
3746
Eric Laurent81784c32012-11-19 14:55:58 -08003747 // enable changes in effect chain
3748 unlockEffectChains(effectChains);
3749
Eric Laurentbfb1b832013-01-07 09:53:42 -08003750 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003751 // mSleepTimeUs == 0 means we must write to audio hardware
3752 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003753 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003754 // writePeriodNs is updated >= 0 when ret > 0.
3755 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003756 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003757 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003758 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003759 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003760 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003761 if (ret < 0) {
3762 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003763 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003764 mBytesWritten += ret;
3765 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003766 const int64_t frames = ret / mFrameSize;
3767 mFramesWritten += frames;
3768
3769 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3770 // process information relating to write time.
3771 if (audio_has_proportional_frames(mFormat)) {
3772 // we are in a continuous mixing cycle
3773 if (mMixerStatus == MIXER_TRACKS_READY &&
3774 loopCount == lastLoopCountWritten + 1) {
3775
3776 const double jitterMs =
3777 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3778 {frames, writePeriodNs},
3779 {0, 0} /* lastTimestamp */, mSampleRate);
3780 const double processMs =
3781 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3782
3783 Mutex::Autolock _l(mLock);
3784 mIoJitterMs.add(jitterMs);
3785 mProcessTimeMs.add(processMs);
3786 }
3787
3788 // write blocked detection
3789 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3790 if (mType == MIXER && deltaWriteNs > maxPeriod) {
3791 mNumDelayedWrites++;
3792 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3793 ATRACE_NAME("underrun");
3794 ALOGW("write blocked for %lld msecs, "
3795 "%d delayed writes, thread %d",
3796 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3797 mNumDelayedWrites, mId);
3798 lastWarning = lastIoEndNs;
3799 }
3800 }
3801 }
3802 // update timing info.
3803 mLastIoBeginNs = lastIoBeginNs;
3804 mLastIoEndNs = lastIoEndNs;
3805 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003806 }
3807 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3808 (mMixerStatus == MIXER_DRAIN_ALL)) {
3809 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003810 }
Andy Hung08fb1742015-05-31 23:22:10 -07003811 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07003812
3813 if (mThreadThrottle
3814 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08003815 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07003816 // Limit MixerThread data processing to no more than twice the
3817 // expected processing rate.
3818 //
3819 // This helps prevent underruns with NuPlayer and other applications
3820 // which may set up buffers that are close to the minimum size, or use
3821 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3822 //
3823 // The throttle smooths out sudden large data drains from the device,
3824 // e.g. when it comes out of standby, which often causes problems with
3825 // (1) mixer threads without a fast mixer (which has its own warm-up)
3826 // (2) minimum buffer sized tracks (even if the track is full,
3827 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003828 //
3829 // Total time spent in last processing cycle equals time spent in
3830 // 1. threadLoop_write, as well as time spent in
3831 // 2. threadLoop_mix (significant for heavy mixing, especially
3832 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003833
Andy Hung446f4df2019-02-21 12:26:41 -08003834 // it's OK if deltaMs is an overestimate.
3835
3836 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003837
Ivan Lozanoea04d392017-11-07 14:37:07 -08003838 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003839 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3840 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003841 // notify of throttle start on verbose log
3842 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3843 "mixer(%p) throttle begin:"
3844 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003845 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003846 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003847 // Throttle must be attributed to the previous mixer loop's write time
3848 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08003849 // This also ensures proper timing statistics.
3850 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07003851 } else {
3852 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3853 if (diff > 0) {
3854 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003855 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07003856 ALOGD_IF(!isSingleDeviceType(
3857 outDeviceTypes(), audio_is_a2dp_out_device) &&
3858 !isSingleDeviceType(
3859 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07003860 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003861 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3862 }
Andy Hung08fb1742015-05-31 23:22:10 -07003863 }
3864 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003865 }
Eric Laurent81784c32012-11-19 14:55:58 -08003866
Eric Laurentbfb1b832013-01-07 09:53:42 -08003867 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003868 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003869 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003870 // suspended requires accurate metering of sleep time.
3871 if (isSuspended()) {
3872 // advance by expected sleepTime
3873 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3874 const nsecs_t nowNs = systemTime();
3875
3876 // compute expected next time vs current time.
3877 // (negative deltas are treated as delays).
3878 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3879 if (deltaNs < -kMaxNextBufferDelayNs) {
3880 // Delays longer than the max allowed trigger a reset.
3881 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3882 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3883 timeLoopNextNs = nowNs + deltaNs;
3884 } else if (deltaNs < 0) {
3885 // Delays within the max delay allowed: zero the delta/sleepTime
3886 // to help the system catch up in the next iteration(s)
3887 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3888 deltaNs = 0;
3889 }
3890 // update sleep time (which is >= 0)
3891 mSleepTimeUs = deltaNs / 1000;
3892 }
Eric Laurente93cc032016-05-05 10:15:10 -07003893 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3894 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003895 }
Glenn Kastene7754022014-10-31 12:11:26 -07003896 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003897 }
Eric Laurent81784c32012-11-19 14:55:58 -08003898 }
3899
3900 // Finally let go of removed track(s), without the lock held
3901 // since we can't guarantee the destructors won't acquire that
3902 // same lock. This will also mutate and push a new fast mixer state.
3903 threadLoop_removeTracks(tracksToRemove);
3904 tracksToRemove.clear();
3905
3906 // FIXME I don't understand the need for this here;
3907 // it was in the original code but maybe the
3908 // assignment in saveOutputTracks() makes this unnecessary?
3909 clearOutputTracks();
3910
3911 // Effect chains will be actually deleted here if they were removed from
3912 // mEffectChains list during mixing or effects processing
3913 effectChains.clear();
3914
3915 // FIXME Note that the above .clear() is no longer necessary since effectChains
3916 // is now local to this block, but will keep it for now (at least until merge done).
3917 }
3918
Eric Laurentbfb1b832013-01-07 09:53:42 -08003919 threadLoop_exit();
3920
Eric Laurentcf817a22014-08-04 20:36:31 -07003921 if (!mStandby) {
3922 threadLoop_standby();
3923 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003924 }
3925
3926 releaseWakeLock();
3927
3928 ALOGV("Thread %p type %d exiting", this, mType);
3929 return false;
3930}
3931
Eric Laurentbfb1b832013-01-07 09:53:42 -08003932// removeTracks_l() must be called with ThreadBase::mLock held
3933void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3934{
Andy Hungfe726a62018-09-27 15:17:25 -07003935 for (const auto& track : tracksToRemove) {
3936 mActiveTracks.remove(track);
3937 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
3938 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3939 if (chain != 0) {
3940 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
3941 __func__, track->id(), chain.get(), track->sessionId());
3942 chain->decActiveTrackCnt();
3943 }
3944 // If an external client track, inform APM we're no longer active, and remove if needed.
3945 // We do this under lock so that the state is consistent if the Track is destroyed.
3946 if (track->isExternalTrack()) {
3947 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003948 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07003949 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003950 }
3951 }
Andy Hungfe726a62018-09-27 15:17:25 -07003952 if (track->isTerminated()) {
3953 // remove from our tracks vector
3954 removeTrack_l(track);
3955 }
jiabin57303cc2018-12-18 15:45:57 -08003956 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
3957 && mHapticChannelCount > 0) {
3958 mLock.unlock();
3959 // Unlock due to VibratorService will lock for this call and will
3960 // call Tracks.mute/unmute which also require thread's lock.
3961 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
3962 mLock.lock();
jiabin245cdd92018-12-07 17:55:15 -08003963 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003964 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003965}
Eric Laurent81784c32012-11-19 14:55:58 -08003966
Eric Laurentaccc1472013-09-20 09:36:34 -07003967status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3968{
3969 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003970 ExtendedTimestamp ets;
3971 status_t status = mNormalSink->getTimestamp(ets);
3972 if (status == NO_ERROR) {
3973 status = ets.getBestTimestamp(&timestamp);
3974 }
3975 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003976 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003977 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003978 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003979 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003980 timestamp.mPosition = (uint32_t)position64;
Dean Wheatley30d28422018-11-06 10:27:40 +11003981 if (mDownstreamLatencyStatMs.getN() > 0) {
3982 const uint32_t positionOffset =
3983 (uint32_t)(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
3984 if (positionOffset > timestamp.mPosition) {
3985 timestamp.mPosition = 0;
3986 } else {
3987 timestamp.mPosition -= positionOffset;
3988 }
3989 }
Eric Laurentaccc1472013-09-20 09:36:34 -07003990 return NO_ERROR;
3991 }
3992 }
3993 return INVALID_OPERATION;
3994}
Eric Laurent1c333e22014-05-20 10:48:17 -07003995
Eric Laurenteab90452019-06-24 15:17:46 -07003996// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
3997// still applied by the mixer.
3998// All tracks attached to a mixer with flag VOIP_RX are tied to the same
3999// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4000// if more than one track are active
4001status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4002{
4003 status_t result = NO_ERROR;
4004 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4005 if (*volume != mLeftVolFloat) {
4006 result = mOutput->stream->setVolume(*volume, *volume);
4007 ALOGE_IF(result != OK,
4008 "Error when setting output stream volume: %d", result);
4009 if (result == NO_ERROR) {
4010 mLeftVolFloat = *volume;
4011 }
4012 }
4013 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4014 // remove stream volume contribution from software volume.
4015 if (mLeftVolFloat == *volume) {
4016 *volume = 1.0f;
4017 }
4018 }
4019 return result;
4020}
4021
Eric Laurent054d9d32015-04-24 08:48:48 -07004022status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4023 audio_patch_handle_t *handle)
4024{
Andy Hungf60abce2016-08-26 11:37:54 -07004025 status_t status;
4026 if (property_get_bool("af.patch_park", false /* default_value */)) {
4027 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4028 // or if HAL does not properly lock against access.
4029 AutoPark<FastMixer> park(mFastMixer);
4030 status = PlaybackThread::createAudioPatch_l(patch, handle);
4031 } else {
4032 status = PlaybackThread::createAudioPatch_l(patch, handle);
4033 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004034 return status;
4035}
4036
Eric Laurent1c333e22014-05-20 10:48:17 -07004037status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4038 audio_patch_handle_t *handle)
4039{
4040 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004041
4042 // store new device and send to effects
4043 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004044 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004045 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004046 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4047 && !mOutput->audioHwDev->supportsAudioPatches(),
4048 "Enumerated device type(%#x) must not be used "
4049 "as it does not support audio patches",
4050 patch->sinks[i].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004051 type |= patch->sinks[i].ext.device.type;
jiabinc52b1ff2019-10-31 17:20:42 -07004052 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4053 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004054 }
4055
François Gaffie0c280aa2018-07-25 10:02:15 +02004056 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004057#ifdef ADD_BATTERY_DATA
4058 // when changing the audio output device, call addBatteryData to notify
4059 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004060 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004061 uint32_t params = 0;
4062 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004063 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004064 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004065 }
4066
Eric Laurent054d9d32015-04-24 08:48:48 -07004067 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004068 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004069 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4070 }
4071
4072 if (params != 0) {
4073 addBatteryData(params);
4074 }
4075 }
4076#endif
4077
4078 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004079 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004080 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004081
jiabinc52b1ff2019-10-31 17:20:42 -07004082 // mPatch.num_sinks is not set when the thread is created so that
4083 // the first patch creation triggers an ioConfigChanged callback
4084 bool configChanged = (mPatch.num_sinks == 0) ||
4085 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004086 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004087 mOutDeviceTypeAddrs = deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004088
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004089 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004090 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4091 status = hwDevice->createAudioPatch(patch->num_sources,
4092 patch->sources,
4093 patch->num_sinks,
4094 patch->sinks,
4095 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004096 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004097 char *address;
4098 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4099 //FIXME: we only support address on first sink with HAL version < 3.0
4100 address = audio_device_address_to_parameter(
4101 patch->sinks[0].ext.device.type,
4102 patch->sinks[0].ext.device.address);
4103 } else {
4104 address = (char *)calloc(1, 1);
4105 }
4106 AudioParameter param = AudioParameter(String8(address));
4107 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004108 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004109 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004110 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004111 }
Eric Laurente8726fe2015-06-26 09:39:24 -07004112 if (configChanged) {
4113 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4114 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004115 return status;
4116}
4117
Eric Laurent054d9d32015-04-24 08:48:48 -07004118status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4119{
Andy Hungf60abce2016-08-26 11:37:54 -07004120 status_t status;
4121 if (property_get_bool("af.patch_park", false /* default_value */)) {
4122 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4123 // or if HAL does not properly lock against access.
4124 AutoPark<FastMixer> park(mFastMixer);
4125 status = PlaybackThread::releaseAudioPatch_l(handle);
4126 } else {
4127 status = PlaybackThread::releaseAudioPatch_l(handle);
4128 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004129 return status;
4130}
4131
Eric Laurent1c333e22014-05-20 10:48:17 -07004132status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4133{
4134 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004135
jiabinc52b1ff2019-10-31 17:20:42 -07004136 mPatch = audio_patch{};
4137 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004138
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004139 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004140 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4141 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004142 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004143 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004144 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004145 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004146 }
4147 return status;
4148}
4149
Eric Laurent83b88082014-06-20 18:31:16 -07004150void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4151{
4152 Mutex::Autolock _l(mLock);
4153 mTracks.add(track);
4154}
4155
4156void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4157{
4158 Mutex::Autolock _l(mLock);
4159 destroyTrack_l(track);
4160}
4161
Mikhail Naganovdc769682018-05-04 15:34:08 -07004162void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004163{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004164 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004165 config->role = AUDIO_PORT_ROLE_SOURCE;
4166 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4167 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004168 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4169 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4170 config->flags.output = mOutput->flags;
4171 }
Eric Laurent83b88082014-06-20 18:31:16 -07004172}
4173
Eric Laurent81784c32012-11-19 14:55:58 -08004174// ----------------------------------------------------------------------------
4175
4176AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
jiabinc52b1ff2019-10-31 17:20:42 -07004177 audio_io_handle_t id, bool systemReady, type_t type)
4178 : PlaybackThread(audioFlinger, output, id, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004179 // mAudioMixer below
4180 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004181 mFastMixerFutex(0),
4182 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004183 // mOutputSink below
4184 // mPipeSink below
4185 // mNormalSink below
4186{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004187 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004188 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004189 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004190 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004191 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4192 mNormalFrameCount);
4193 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4194
Andy Hungfbfc3952015-01-15 13:33:51 -08004195 if (type == DUPLICATING) {
4196 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4197 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4198 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4199 return;
4200 }
Eric Laurent81784c32012-11-19 14:55:58 -08004201 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004202 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004203 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004204 const NBAIO_Format offers[1] = {Format_from_SR_C(
4205 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004206#if !LOG_NDEBUG
4207 ssize_t index =
4208#else
4209 (void)
4210#endif
4211 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004212 ALOG_ASSERT(index == 0);
4213
4214 // initialize fast mixer depending on configuration
4215 bool initFastMixer;
4216 switch (kUseFastMixer) {
4217 case FastMixer_Never:
4218 initFastMixer = false;
4219 break;
4220 case FastMixer_Always:
4221 initFastMixer = true;
4222 break;
4223 case FastMixer_Static:
4224 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004225 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4226 // where the period is less than an experimentally determined threshold that can be
4227 // scheduled reliably with CFS. However, the BT A2DP HAL is
4228 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4229 initFastMixer = mFrameCount < mNormalFrameCount
jiabinc52b1ff2019-10-31 17:20:42 -07004230 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
Eric Laurent81784c32012-11-19 14:55:58 -08004231 break;
4232 }
Andy Hungfda69402017-02-15 14:33:12 -08004233 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4234 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4235 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004236 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004237 audio_format_t fastMixerFormat;
4238 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4239 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4240 } else {
4241 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4242 }
4243 if (mFormat != fastMixerFormat) {
4244 // change our Sink format to accept our intermediate precision
4245 mFormat = fastMixerFormat;
4246 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004247 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004248 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4249 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4250 }
Eric Laurent81784c32012-11-19 14:55:58 -08004251
4252 // create a MonoPipe to connect our submix to FastMixer
4253 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004254
Andy Hung1258c1a2014-05-23 21:22:17 -07004255 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004256 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004257 format.mFormat = fastMixerFormat;
4258 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4259
Eric Laurent81784c32012-11-19 14:55:58 -08004260 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4261 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4262 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4263 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4264 const NBAIO_Format offers[1] = {format};
4265 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004266#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004267 ssize_t index =
4268#else
4269 (void)
4270#endif
4271 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004272 ALOG_ASSERT(index == 0);
4273 monoPipe->setAvgFrames((mScreenState & 1) ?
4274 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4275 mPipeSink = monoPipe;
4276
Eric Laurent81784c32012-11-19 14:55:58 -08004277 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004278 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004279 FastMixerStateQueue *sq = mFastMixer->sq();
4280#ifdef STATE_QUEUE_DUMP
4281 sq->setObserverDump(&mStateQueueObserverDump);
4282 sq->setMutatorDump(&mStateQueueMutatorDump);
4283#endif
4284 FastMixerState *state = sq->begin();
4285 FastTrack *fastTrack = &state->mFastTracks[0];
4286 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4287 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4288 fastTrack->mVolumeProvider = NULL;
jiabin245cdd92018-12-07 17:55:15 -08004289 fastTrack->mChannelMask = mChannelMask | mHapticChannelMask; // mPipeSink channel mask for
4290 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004291 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004292 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabin84114c32019-04-10 16:38:07 -07004293 fastTrack->mHapticIntensity = AudioMixer::HAPTIC_SCALE_NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08004294 fastTrack->mGeneration++;
4295 state->mFastTracksGen++;
4296 state->mTrackMask = 1;
4297 // fast mixer will use the HAL output sink
4298 state->mOutputSink = mOutputSink.get();
4299 state->mOutputSinkGen++;
4300 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004301 // specify sink channel mask when haptic channel mask present as it can not
4302 // be calculated directly from channel count
4303 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
4304 ? AUDIO_CHANNEL_NONE : mChannelMask | mHapticChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08004305 state->mCommand = FastMixerState::COLD_IDLE;
4306 // already done in constructor initialization list
4307 //mFastMixerFutex = 0;
4308 state->mColdFutexAddr = &mFastMixerFutex;
4309 state->mColdGen++;
4310 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004311 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4312 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004313 sq->end();
4314 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4315
Eric Tan0513b5d2018-09-17 10:32:48 -07004316 NBLog::thread_info_t info;
4317 info.id = mId;
4318 info.type = NBLog::FASTMIXER;
4319 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4320
Eric Laurent81784c32012-11-19 14:55:58 -08004321 // start the fast mixer
4322 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4323 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004324 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004325 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004326
4327#ifdef AUDIO_WATCHDOG
4328 // create and start the watchdog
4329 mAudioWatchdog = new AudioWatchdog();
4330 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4331 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4332 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004333 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004334#endif
Andy Hung8946a282018-04-19 20:04:56 -07004335 } else {
4336#ifdef TEE_SINK
4337 // Only use the MixerThread tee if there is no FastMixer.
4338 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4339 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4340#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004341 }
4342
4343 switch (kUseFastMixer) {
4344 case FastMixer_Never:
4345 case FastMixer_Dynamic:
4346 mNormalSink = mOutputSink;
4347 break;
4348 case FastMixer_Always:
4349 mNormalSink = mPipeSink;
4350 break;
4351 case FastMixer_Static:
4352 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4353 break;
4354 }
4355}
4356
4357AudioFlinger::MixerThread::~MixerThread()
4358{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004359 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004360 FastMixerStateQueue *sq = mFastMixer->sq();
4361 FastMixerState *state = sq->begin();
4362 if (state->mCommand == FastMixerState::COLD_IDLE) {
4363 int32_t old = android_atomic_inc(&mFastMixerFutex);
4364 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004365 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004366 }
4367 }
4368 state->mCommand = FastMixerState::EXIT;
4369 sq->end();
4370 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4371 mFastMixer->join();
4372 // Though the fast mixer thread has exited, it's state queue is still valid.
4373 // We'll use that extract the final state which contains one remaining fast track
4374 // corresponding to our sub-mix.
4375 state = sq->begin();
4376 ALOG_ASSERT(state->mTrackMask == 1);
4377 FastTrack *fastTrack = &state->mFastTracks[0];
4378 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4379 delete fastTrack->mBufferProvider;
4380 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004381 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004382#ifdef AUDIO_WATCHDOG
4383 if (mAudioWatchdog != 0) {
4384 mAudioWatchdog->requestExit();
4385 mAudioWatchdog->requestExitAndWait();
4386 mAudioWatchdog.clear();
4387 }
4388#endif
4389 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004390 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004391 delete mAudioMixer;
4392}
4393
4394
4395uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4396{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004397 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004398 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4399 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4400 }
4401 return latency;
4402}
4403
Eric Laurentbfb1b832013-01-07 09:53:42 -08004404ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004405{
4406 // FIXME we should only do one push per cycle; confirm this is true
4407 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004408 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004409 FastMixerStateQueue *sq = mFastMixer->sq();
4410 FastMixerState *state = sq->begin();
4411 if (state->mCommand != FastMixerState::MIX_WRITE &&
4412 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4413 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004414
4415 // FIXME workaround for first HAL write being CPU bound on some devices
4416 ATRACE_BEGIN("write");
4417 mOutput->write((char *)mSinkBuffer, 0);
4418 ATRACE_END();
4419
Eric Laurent81784c32012-11-19 14:55:58 -08004420 int32_t old = android_atomic_inc(&mFastMixerFutex);
4421 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004422 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004423 }
4424#ifdef AUDIO_WATCHDOG
4425 if (mAudioWatchdog != 0) {
4426 mAudioWatchdog->resume();
4427 }
4428#endif
4429 }
4430 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004431#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004432 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004433 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004434#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004435 sq->end();
4436 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4437 if (kUseFastMixer == FastMixer_Dynamic) {
4438 mNormalSink = mPipeSink;
4439 }
4440 } else {
4441 sq->end(false /*didModify*/);
4442 }
4443 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004444 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004445}
4446
4447void AudioFlinger::MixerThread::threadLoop_standby()
4448{
4449 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004450 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004451 FastMixerStateQueue *sq = mFastMixer->sq();
4452 FastMixerState *state = sq->begin();
4453 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004454 // Report any frames trapped in the Monopipe
4455 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4456 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4457 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4458 "monoPipeWritten:%lld monoPipeLeft:%lld",
4459 (long long)mFramesWritten, (long long)mSuspendedFrames,
4460 (long long)mPipeSink->framesWritten(), pipeFrames);
4461 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4462
Eric Laurent81784c32012-11-19 14:55:58 -08004463 state->mCommand = FastMixerState::COLD_IDLE;
4464 state->mColdFutexAddr = &mFastMixerFutex;
4465 state->mColdGen++;
4466 mFastMixerFutex = 0;
4467 sq->end();
4468 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4469 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4470 if (kUseFastMixer == FastMixer_Dynamic) {
4471 mNormalSink = mOutputSink;
4472 }
4473#ifdef AUDIO_WATCHDOG
4474 if (mAudioWatchdog != 0) {
4475 mAudioWatchdog->pause();
4476 }
4477#endif
4478 } else {
4479 sq->end(false /*didModify*/);
4480 }
4481 }
4482 PlaybackThread::threadLoop_standby();
4483}
4484
Eric Laurentbfb1b832013-01-07 09:53:42 -08004485bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4486{
4487 return false;
4488}
4489
4490bool AudioFlinger::PlaybackThread::shouldStandby_l()
4491{
4492 return !mStandby;
4493}
4494
4495bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4496{
4497 Mutex::Autolock _l(mLock);
4498 return waitingAsyncCallback_l();
4499}
4500
Eric Laurent81784c32012-11-19 14:55:58 -08004501// shared by MIXER and DIRECT, overridden by DUPLICATING
4502void AudioFlinger::PlaybackThread::threadLoop_standby()
4503{
4504 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004505 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004506 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004507 // discard any pending drain or write ack by incrementing sequence
4508 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4509 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004510 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004511 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4512 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004513 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004514 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004515}
4516
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004517void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4518{
4519 ALOGV("signal playback thread");
4520 broadcast_l();
4521}
4522
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004523void AudioFlinger::PlaybackThread::onAsyncError()
4524{
4525 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4526 invalidateTracks((audio_stream_type_t)i);
4527 }
4528}
4529
Eric Laurent81784c32012-11-19 14:55:58 -08004530void AudioFlinger::MixerThread::threadLoop_mix()
4531{
Eric Laurent81784c32012-11-19 14:55:58 -08004532 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004533 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004534 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004535 // increase sleep time progressively when application underrun condition clears.
4536 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4537 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4538 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004539 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004540 sleepTimeShift--;
4541 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004542 mSleepTimeUs = 0;
4543 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004544 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004545
Eric Laurent81784c32012-11-19 14:55:58 -08004546}
4547
4548void AudioFlinger::MixerThread::threadLoop_sleepTime()
4549{
4550 // If no tracks are ready, sleep once for the duration of an output
4551 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004552 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004553 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004554 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4555 // Using the Monopipe availableToWrite, we estimate the
4556 // sleep time to retry for more data (before we underrun).
4557 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4558 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4559 const size_t pipeFrames = monoPipe->maxFrames();
4560 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4561 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4562 const size_t framesDelay = std::min(
4563 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4564 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4565 pipeFrames, framesLeft, framesDelay);
4566 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4567 } else {
4568 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4569 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4570 mSleepTimeUs = kMinThreadSleepTimeUs;
4571 }
4572 // reduce sleep time in case of consecutive application underruns to avoid
4573 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4574 // duration we would end up writing less data than needed by the audio HAL if
4575 // the condition persists.
4576 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4577 sleepTimeShift++;
4578 }
Eric Laurent81784c32012-11-19 14:55:58 -08004579 }
4580 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004581 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004582 }
4583 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004584 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4585 // before effects processing or output.
4586 if (mMixerBufferValid) {
4587 memset(mMixerBuffer, 0, mMixerBufferSize);
4588 } else {
4589 memset(mSinkBuffer, 0, mSinkBufferSize);
4590 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004591 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004592 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4593 "anticipated start");
4594 }
4595 // TODO add standby time extension fct of effect tail
4596}
4597
4598// prepareTracks_l() must be called with ThreadBase::mLock held
4599AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4600 Vector< sp<Track> > *tracksToRemove)
4601{
Andy Hungc0691382018-09-12 18:01:57 -07004602 // clean up deleted track ids in AudioMixer before allocating new tracks
4603 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4604 // for each trackId, destroy it in the AudioMixer
4605 if (mAudioMixer->exists(trackId)) {
4606 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004607 }
4608 });
Andy Hungc0691382018-09-12 18:01:57 -07004609 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004610
4611 mixer_state mixerStatus = MIXER_IDLE;
4612 // find out which tracks need to be processed
4613 size_t count = mActiveTracks.size();
4614 size_t mixedTracks = 0;
4615 size_t tracksWithEffect = 0;
4616 // counts only _active_ fast tracks
4617 size_t fastTracks = 0;
4618 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4619
4620 float masterVolume = mMasterVolume;
4621 bool masterMute = mMasterMute;
4622
4623 if (masterMute) {
4624 masterVolume = 0;
4625 }
4626 // Delegate master volume control to effect in output mix effect chain if needed
4627 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4628 if (chain != 0) {
4629 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4630 chain->setVolume_l(&v, &v);
4631 masterVolume = (float)((v + (1 << 23)) >> 24);
4632 chain.clear();
4633 }
4634
4635 // prepare a new state to push
4636 FastMixerStateQueue *sq = NULL;
4637 FastMixerState *state = NULL;
4638 bool didModify = false;
4639 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004640 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004641 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004642 sq = mFastMixer->sq();
4643 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004644 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004645 }
4646
Andy Hung69aed5f2014-02-25 17:24:40 -08004647 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004648 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004649
Andy Hungbd3b2b02018-05-21 10:53:11 -07004650 // DeferredOperations handles statistics after setting mixerStatus.
4651 class DeferredOperations {
4652 public:
4653 DeferredOperations(mixer_state *mixerStatus)
4654 : mMixerStatus(mixerStatus) { }
4655
4656 // when leaving scope, tally frames properly.
4657 ~DeferredOperations() {
4658 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4659 // because that is when the underrun occurs.
4660 // We do not distinguish between FastTracks and NormalTracks here.
4661 if (*mMixerStatus == MIXER_TRACKS_READY) {
4662 for (const auto &underrun : mUnderrunFrames) {
4663 underrun.first->mAudioTrackServerProxy->tallyUnderrunFrames(
4664 underrun.second);
4665 }
4666 }
4667 }
4668
4669 // tallyUnderrunFrames() is called to update the track counters
4670 // with the number of underrun frames for a particular mixer period.
4671 // We defer tallying until we know the final mixer status.
4672 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4673 mUnderrunFrames.emplace_back(track, underrunFrames);
4674 }
4675
4676 private:
4677 const mixer_state * const mMixerStatus;
4678 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4679 } deferredOperations(&mixerStatus); // implicit nested scope for variable capture
4680
jiabin245cdd92018-12-07 17:55:15 -08004681 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004682 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004683 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004684
4685 // this const just means the local variable doesn't change
4686 Track* const track = t.get();
4687
4688 // process fast tracks
4689 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07004690 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
4691 "%s(%d): FastTrack(%d) present without FastMixer",
4692 __func__, id(), track->id());
4693
jiabin245cdd92018-12-07 17:55:15 -08004694 if (track->getHapticPlaybackEnabled()) {
4695 noFastHapticTrack = false;
4696 }
Eric Laurent81784c32012-11-19 14:55:58 -08004697
4698 // It's theoretically possible (though unlikely) for a fast track to be created
4699 // and then removed within the same normal mix cycle. This is not a problem, as
4700 // the track never becomes active so it's fast mixer slot is never touched.
4701 // The converse, of removing an (active) track and then creating a new track
4702 // at the identical fast mixer slot within the same normal mix cycle,
4703 // is impossible because the slot isn't marked available until the end of each cycle.
4704 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004705 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004706 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4707 FastTrack *fastTrack = &state->mFastTracks[j];
4708
4709 // Determine whether the track is currently in underrun condition,
4710 // and whether it had a recent underrun.
4711 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4712 FastTrackUnderruns underruns = ftDump->mUnderruns;
4713 uint32_t recentFull = (underruns.mBitFields.mFull -
4714 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4715 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4716 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4717 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4718 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4719 uint32_t recentUnderruns = recentPartial + recentEmpty;
4720 track->mObservedUnderruns = underruns;
4721 // don't count underruns that occur while stopping or pausing
4722 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004723 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004724 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4725 recentUnderruns > 0) {
4726 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004727 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004728 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004729 // Immediately account for FastTrack underruns.
4730 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004731
4732 // This is similar to the state machine for normal tracks,
4733 // with a few modifications for fast tracks.
4734 bool isActive = true;
4735 switch (track->mState) {
4736 case TrackBase::STOPPING_1:
4737 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004738 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004739 track->mState = TrackBase::STOPPING_2;
4740 }
4741 break;
4742 case TrackBase::PAUSING:
4743 // ramp down is not yet implemented
4744 track->setPaused();
4745 break;
4746 case TrackBase::RESUMING:
4747 // ramp up is not yet implemented
4748 track->mState = TrackBase::ACTIVE;
4749 break;
4750 case TrackBase::ACTIVE:
4751 if (recentFull > 0 || recentPartial > 0) {
4752 // track has provided at least some frames recently: reset retry count
4753 track->mRetryCount = kMaxTrackRetries;
4754 }
4755 if (recentUnderruns == 0) {
4756 // no recent underruns: stay active
4757 break;
4758 }
4759 // there has recently been an underrun of some kind
4760 if (track->sharedBuffer() == 0) {
4761 // were any of the recent underruns "empty" (no frames available)?
4762 if (recentEmpty == 0) {
4763 // no, then ignore the partial underruns as they are allowed indefinitely
4764 break;
4765 }
4766 // there has recently been an "empty" underrun: decrement the retry counter
4767 if (--(track->mRetryCount) > 0) {
4768 break;
4769 }
4770 // indicate to client process that the track was disabled because of underrun;
4771 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004772 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004773 // remove from active list, but state remains ACTIVE [confusing but true]
4774 isActive = false;
4775 break;
4776 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07004777 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08004778 case TrackBase::STOPPING_2:
4779 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004780 case TrackBase::STOPPED:
4781 case TrackBase::FLUSHED: // flush() while active
4782 // Check for presentation complete if track is inactive
4783 // We have consumed all the buffers of this track.
4784 // This would be incomplete if we auto-paused on underrun
4785 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004786 uint32_t latency = 0;
4787 status_t result = mOutput->stream->getLatency(&latency);
4788 ALOGE_IF(result != OK,
4789 "Error when retrieving output stream latency: %d", result);
4790 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004791 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004792 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4793 // track stays in active list until presentation is complete
4794 break;
4795 }
4796 }
4797 if (track->isStopping_2()) {
4798 track->mState = TrackBase::STOPPED;
4799 }
4800 if (track->isStopped()) {
4801 // Can't reset directly, as fast mixer is still polling this track
4802 // track->reset();
4803 // So instead mark this track as needing to be reset after push with ack
4804 resetMask |= 1 << i;
4805 }
4806 isActive = false;
4807 break;
4808 case TrackBase::IDLE:
4809 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004810 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004811 }
4812
4813 if (isActive) {
4814 // was it previously inactive?
4815 if (!(state->mTrackMask & (1 << j))) {
4816 ExtendedAudioBufferProvider *eabp = track;
4817 VolumeProvider *vp = track;
4818 fastTrack->mBufferProvider = eabp;
4819 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004820 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004821 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08004822 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08004823 fastTrack->mHapticIntensity = track->getHapticIntensity();
Eric Laurent81784c32012-11-19 14:55:58 -08004824 fastTrack->mGeneration++;
4825 state->mTrackMask |= 1 << j;
4826 didModify = true;
4827 // no acknowledgement required for newly active tracks
4828 }
Kevin Rocard12381092018-04-11 09:19:59 -07004829 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07004830 float volume;
4831 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
4832 volume = 0.f;
4833 } else {
4834 volume = masterVolume * mStreamTypes[track->streamType()].volume;
4835 }
4836
4837 handleVoipVolume_l(&volume);
4838
Eric Laurent81784c32012-11-19 14:55:58 -08004839 // cache the combined master volume and stream type volume for fast mixer; this
4840 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004841 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07004842 proxy->framesReleased()).first;
4843 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004844 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004845 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4846 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4847 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07004848
Kevin Rocard12381092018-04-11 09:19:59 -07004849 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004850 ++fastTracks;
4851 } else {
4852 // was it previously active?
4853 if (state->mTrackMask & (1 << j)) {
4854 fastTrack->mBufferProvider = NULL;
4855 fastTrack->mGeneration++;
4856 state->mTrackMask &= ~(1 << j);
4857 didModify = true;
4858 // If any fast tracks were removed, we must wait for acknowledgement
4859 // because we're about to decrement the last sp<> on those tracks.
4860 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4861 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004862 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4863 // AudioTrack may start (which may not be with a start() but with a write()
4864 // after underrun) and immediately paused or released. In that case the
4865 // FastTrack state hasn't had time to update.
4866 // TODO Remove the ALOGW when this theory is confirmed.
4867 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004868 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4869 j, track->mState, state->mTrackMask, recentUnderruns,
4870 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004871 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004872 }
4873 tracksToRemove->add(track);
4874 // Avoids a misleading display in dumpsys
4875 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4876 }
jiabin245cdd92018-12-07 17:55:15 -08004877 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
4878 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
4879 didModify = true;
4880 }
Eric Laurent81784c32012-11-19 14:55:58 -08004881 continue;
4882 }
4883
4884 { // local variable scope to avoid goto warning
4885
4886 audio_track_cblk_t* cblk = track->cblk();
4887
4888 // The first time a track is added we wait
4889 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07004890 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08004891
4892 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07004893 // use the trackId as the AudioMixer name.
4894 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08004895 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07004896 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08004897 track->mChannelMask,
4898 track->mFormat,
4899 track->mSessionId);
4900 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07004901 ALOGW("%s(): AudioMixer cannot create track(%d)"
4902 " mask %#x, format %#x, sessionId %d",
4903 __func__, trackId,
4904 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004905 tracksToRemove->add(track);
4906 track->invalidate(); // consider it dead.
4907 continue;
4908 }
4909 }
4910
Eric Laurent81784c32012-11-19 14:55:58 -08004911 // make sure that we have enough frames to mix one full buffer.
4912 // enforce this condition only once to enable draining the buffer in case the client
4913 // app does not call stop() and relies on underrun to stop:
4914 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4915 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004916 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004917 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004918 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004919
4920 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004921 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004922 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4923 // add frames already consumed but not yet released by the resampler
4924 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07004925 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004926
Eric Laurent81784c32012-11-19 14:55:58 -08004927 uint32_t minFrames = 1;
4928 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4929 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004930 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004931 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004932
4933 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004934 if (ATRACE_ENABLED()) {
4935 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004936 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07004937 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004938 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004939 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004940 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004941 !track->isPaused() && !track->isTerminated())
4942 {
Andy Hungc0691382018-09-12 18:01:57 -07004943 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004944
4945 mixedTracks++;
4946
Andy Hung69aed5f2014-02-25 17:24:40 -08004947 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4948 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004949 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004950 if (track->mainBuffer() != mSinkBuffer &&
4951 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004952 if (mEffectBufferEnabled) {
4953 mEffectBufferValid = true; // Later can set directly.
4954 }
Eric Laurent81784c32012-11-19 14:55:58 -08004955 chain = getEffectChain_l(track->sessionId());
4956 // Delegate volume control to effect in track effect chain if needed
4957 if (chain != 0) {
4958 tracksWithEffect++;
4959 } else {
Andy Hungc0691382018-09-12 18:01:57 -07004960 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08004961 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07004962 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08004963 }
4964 }
4965
4966
4967 int param = AudioMixer::VOLUME;
4968 if (track->mFillingUpStatus == Track::FS_FILLED) {
4969 // no ramp for the first volume setting
4970 track->mFillingUpStatus = Track::FS_ACTIVE;
4971 if (track->mState == TrackBase::RESUMING) {
4972 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08004973 // If a new track is paused immediately after start, do not ramp on resume.
4974 if (cblk->mServer != 0) {
4975 param = AudioMixer::RAMP_VOLUME;
4976 }
Eric Laurent81784c32012-11-19 14:55:58 -08004977 }
Andy Hungc0691382018-09-12 18:01:57 -07004978 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004979 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004980 // FIXME should not make a decision based on mServer
4981 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004982 // If the track is stopped before the first frame was mixed,
4983 // do not apply ramp
4984 param = AudioMixer::RAMP_VOLUME;
4985 }
4986
4987 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004988 uint32_t vl, vr; // in U8.24 integer format
4989 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004990 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07004991 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07004992 // Always fetch volumeshaper volume to ensure state is updated.
4993 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
4994 const float vh = track->getVolumeHandler()->getVolume(
4995 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07004996
Eric Laurenteab90452019-06-24 15:17:46 -07004997 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
4998 v = 0;
4999 }
5000
5001 handleVoipVolume_l(&v);
5002
5003 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005004 vl = vr = 0;
5005 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005006 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005007 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005008 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005009 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5010 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005011 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005012 if (vlf > GAIN_FLOAT_UNITY) {
5013 ALOGV("Track left volume out of range: %.3g", vlf);
5014 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005015 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005016 if (vrf > GAIN_FLOAT_UNITY) {
5017 ALOGV("Track right volume out of range: %.3g", vrf);
5018 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005019 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005020 // now apply the master volume and stream type volume and shaper volume
5021 vlf *= v * vh;
5022 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005023 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005024 // then derive vl and vr as U8.24 versions for the effect chain
5025 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5026 vl = (uint32_t) (scaleto8_24 * vlf);
5027 vr = (uint32_t) (scaleto8_24 * vrf);
5028 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005029 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005030 // send level comes from shared memory and so may be corrupt
5031 if (sendLevel > MAX_GAIN_INT) {
5032 ALOGV("Track send level out of range: %04X", sendLevel);
5033 sendLevel = MAX_GAIN_INT;
5034 }
Andy Hung6be49402014-05-30 10:42:03 -07005035 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5036 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005037 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005038
Kevin Rocard12381092018-04-11 09:19:59 -07005039 track->setFinalVolume((vrf + vlf) / 2.f);
5040
Eric Laurent81784c32012-11-19 14:55:58 -08005041 // Delegate volume control to effect in track effect chain if needed
5042 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5043 // Do not ramp volume if volume is controlled by effect
5044 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005045 // Update remaining floating point volume levels
5046 vlf = (float)vl / (1 << 24);
5047 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005048 track->mHasVolumeController = true;
5049 } else {
5050 // force no volume ramp when volume controller was just disabled or removed
5051 // from effect chain to avoid volume spike
5052 if (track->mHasVolumeController) {
5053 param = AudioMixer::VOLUME;
5054 }
5055 track->mHasVolumeController = false;
5056 }
5057
Eric Laurent81784c32012-11-19 14:55:58 -08005058 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005059 mAudioMixer->setBufferProvider(trackId, track);
5060 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005061
Andy Hungc0691382018-09-12 18:01:57 -07005062 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5063 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5064 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005065 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005066 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005067 AudioMixer::TRACK,
5068 AudioMixer::FORMAT, (void *)track->format());
5069 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005070 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005071 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005072 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07005073 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005074 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07005075 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08005076 AudioMixer::MIXER_CHANNEL_MASK,
5077 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08005078 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005079 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005080 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005081 if (reqSampleRate == 0) {
5082 reqSampleRate = mSampleRate;
5083 } else if (reqSampleRate > maxSampleRate) {
5084 reqSampleRate = maxSampleRate;
5085 }
Eric Laurent81784c32012-11-19 14:55:58 -08005086 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005087 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005088 AudioMixer::RESAMPLE,
5089 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005090 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005091
Andy Hung333ab962019-05-28 20:23:35 -07005092 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005093 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005094 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005095 AudioMixer::TIMESTRETCH,
5096 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005097 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005098
Andy Hung69aed5f2014-02-25 17:24:40 -08005099 /*
5100 * Select the appropriate output buffer for the track.
5101 *
Andy Hung98ef9782014-03-04 14:46:50 -08005102 * Tracks with effects go into their own effects chain buffer
5103 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005104 *
5105 * Other tracks can use mMixerBuffer for higher precision
5106 * channel accumulation. If this buffer is enabled
5107 * (mMixerBufferEnabled true), then selected tracks will accumulate
5108 * into it.
5109 *
5110 */
5111 if (mMixerBufferEnabled
5112 && (track->mainBuffer() == mSinkBuffer
5113 || track->mainBuffer() == mMixerBuffer)) {
5114 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005115 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005116 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08005117 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08005118 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005119 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005120 AudioMixer::TRACK,
5121 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5122 // TODO: override track->mainBuffer()?
5123 mMixerBufferValid = true;
5124 } else {
5125 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005126 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005127 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005128 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005129 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005130 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005131 AudioMixer::TRACK,
5132 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5133 }
Eric Laurent81784c32012-11-19 14:55:58 -08005134 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005135 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005136 AudioMixer::TRACK,
5137 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005138 mAudioMixer->setParameter(
5139 trackId,
5140 AudioMixer::TRACK,
5141 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005142 mAudioMixer->setParameter(
5143 trackId,
5144 AudioMixer::TRACK,
5145 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Eric Laurent81784c32012-11-19 14:55:58 -08005146
5147 // reset retry count
5148 track->mRetryCount = kMaxTrackRetries;
5149
5150 // If one track is ready, set the mixer ready if:
5151 // - the mixer was not ready during previous round OR
5152 // - no other track is not ready
5153 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5154 mixerStatus != MIXER_TRACKS_ENABLED) {
5155 mixerStatus = MIXER_TRACKS_READY;
5156 }
5157 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005158 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005159 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungc0691382018-09-12 18:01:57 -07005160 ALOGV("track(%d) underrun, framesReady(%zu) < framesDesired(%zd)",
5161 trackId, framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005162 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005163 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005164 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005165
Eric Laurent81784c32012-11-19 14:55:58 -08005166 // clear effect chain input buffer if an active track underruns to avoid sending
5167 // previous audio buffer again to effects
5168 chain = getEffectChain_l(track->sessionId());
5169 if (chain != 0) {
5170 chain->clearInputBuffer();
5171 }
5172
Andy Hungc0691382018-09-12 18:01:57 -07005173 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005174 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5175 track->isStopped() || track->isPaused()) {
5176 // We have consumed all the buffers of this track.
5177 // Remove it from the list of active tracks.
5178 // TODO: use actual buffer filling status instead of latency when available from
5179 // audio HAL
5180 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005181 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005182 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5183 if (track->isStopped()) {
5184 track->reset();
5185 }
5186 tracksToRemove->add(track);
5187 }
5188 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005189 // No buffers for this track. Give it a few chances to
5190 // fill a buffer, then remove it from active list.
5191 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005192 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5193 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005194 tracksToRemove->add(track);
5195 // indicate to client process that the track was disabled because of underrun;
5196 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005197 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005198 // If one track is not ready, mark the mixer also not ready if:
5199 // - the mixer was ready during previous round OR
5200 // - no other track is ready
5201 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5202 mixerStatus != MIXER_TRACKS_READY) {
5203 mixerStatus = MIXER_TRACKS_ENABLED;
5204 }
5205 }
Andy Hungc0691382018-09-12 18:01:57 -07005206 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005207 }
5208
5209 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005210
5211 }
5212
jiabin245cdd92018-12-07 17:55:15 -08005213 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5214 // When there is no fast track playing haptic and FastMixer exists,
5215 // enabling the first FastTrack, which provides mixed data from normal
5216 // tracks, to play haptic data.
5217 FastTrack *fastTrack = &state->mFastTracks[0];
5218 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5219 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5220 didModify = true;
5221 }
5222 }
5223
Eric Laurent81784c32012-11-19 14:55:58 -08005224 // Push the new FastMixer state if necessary
5225 bool pauseAudioWatchdog = false;
5226 if (didModify) {
5227 state->mFastTracksGen++;
5228 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5229 if (kUseFastMixer == FastMixer_Dynamic &&
5230 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5231 state->mCommand = FastMixerState::COLD_IDLE;
5232 state->mColdFutexAddr = &mFastMixerFutex;
5233 state->mColdGen++;
5234 mFastMixerFutex = 0;
5235 if (kUseFastMixer == FastMixer_Dynamic) {
5236 mNormalSink = mOutputSink;
5237 }
5238 // If we go into cold idle, need to wait for acknowledgement
5239 // so that fast mixer stops doing I/O.
5240 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5241 pauseAudioWatchdog = true;
5242 }
Eric Laurent81784c32012-11-19 14:55:58 -08005243 }
5244 if (sq != NULL) {
5245 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005246 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5247 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5248 // when bringing the output sink into standby.)
5249 //
5250 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5251 //
5252 // This occurs with BT suspend when we idle the FastMixer with
5253 // active tracks, which may be added or removed.
5254 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005255 }
5256#ifdef AUDIO_WATCHDOG
5257 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5258 mAudioWatchdog->pause();
5259 }
5260#endif
5261
5262 // Now perform the deferred reset on fast tracks that have stopped
5263 while (resetMask != 0) {
5264 size_t i = __builtin_ctz(resetMask);
5265 ALOG_ASSERT(i < count);
5266 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005267 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005268 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5269 track->reset();
5270 }
5271
Andy Hung80d03d22018-04-10 10:32:11 -07005272 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5273 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5274 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5275 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5276 // See also the implementation of destroyTrack_l().
5277 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005278 const int trackId = track->id();
5279 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5280 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005281 }
5282 }
5283
Eric Laurent81784c32012-11-19 14:55:58 -08005284 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005285 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005286
Eric Laurent97d547d2014-09-02 14:45:53 -07005287 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5288 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005289 }
5290
5291 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005292 // as long as there are effects we should clear the effects buffer, to avoid
5293 // passing a non-clean buffer to the effect chain
5294 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005295 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005296 // sink or mix buffer must be cleared if all tracks are connected to an
5297 // effect chain as in this case the mixer will not write to the sink or mix buffer
5298 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005299 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5300 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005301 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005302 if (mMixerBufferValid) {
5303 memset(mMixerBuffer, 0, mMixerBufferSize);
5304 // TODO: In testing, mSinkBuffer below need not be cleared because
5305 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5306 // after mixing.
5307 //
5308 // To enforce this guarantee:
5309 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5310 // (mixedTracks == 0 && fastTracks > 0))
5311 // must imply MIXER_TRACKS_READY.
5312 // Later, we may clear buffers regardless, and skip much of this logic.
5313 }
Andy Hung98ef9782014-03-04 14:46:50 -08005314 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005315 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005316 }
5317
5318 // if any fast tracks, then status is ready
5319 mMixerStatusIgnoringFastTracks = mixerStatus;
5320 if (fastTracks > 0) {
5321 mixerStatus = MIXER_TRACKS_READY;
5322 }
5323 return mixerStatus;
5324}
5325
Eric Laurentad7dd962016-09-22 12:38:37 -07005326// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005327uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005328{
5329 uint32_t trackCount = 0;
5330 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005331 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005332 trackCount++;
5333 }
5334 }
5335 return trackCount;
5336}
5337
Andy Hung1bc088a2018-02-09 15:57:31 -08005338// isTrackAllowed_l() must be called with ThreadBase::mLock held
5339bool AudioFlinger::MixerThread::isTrackAllowed_l(
5340 audio_channel_mask_t channelMask, audio_format_t format,
5341 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005342{
Andy Hung1bc088a2018-02-09 15:57:31 -08005343 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5344 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005345 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005346 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005347 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005348 ALOGW("%s: invalid format: %#x", __func__, format);
5349 return false;
5350 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005351 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005352 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5353 return false;
5354 }
5355 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005356}
5357
Eric Laurent10351942014-05-08 18:49:52 -07005358// checkForNewParameter_l() must be called with ThreadBase::mLock held
5359bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5360 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005361{
Eric Laurent81784c32012-11-19 14:55:58 -08005362 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005363 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005364
Eric Laurent10351942014-05-08 18:49:52 -07005365 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005366
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005367 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005368
Eric Laurent10351942014-05-08 18:49:52 -07005369 AudioParameter param = AudioParameter(keyValuePair);
5370 int value;
5371 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5372 reconfig = true;
5373 }
5374 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005375 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005376 status = BAD_VALUE;
5377 } else {
5378 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005379 reconfig = true;
5380 }
Eric Laurent10351942014-05-08 18:49:52 -07005381 }
5382 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005383 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005384 status = BAD_VALUE;
5385 } else {
5386 // no need to save value, since it's constant
5387 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005388 }
Eric Laurent10351942014-05-08 18:49:52 -07005389 }
5390 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5391 // do not accept frame count changes if tracks are open as the track buffer
5392 // size depends on frame count and correct behavior would not be guaranteed
5393 // if frame count is changed after track creation
5394 if (!mTracks.isEmpty()) {
5395 status = INVALID_OPERATION;
5396 } else {
5397 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005398 }
Eric Laurent10351942014-05-08 18:49:52 -07005399 }
5400 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005401 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005402 }
Eric Laurent81784c32012-11-19 14:55:58 -08005403
Eric Laurent10351942014-05-08 18:49:52 -07005404 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005405 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005406 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005407 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005408 mStandby = true;
5409 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005410 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005411 }
Eric Laurent10351942014-05-08 18:49:52 -07005412 if (status == NO_ERROR && reconfig) {
5413 readOutputParameters_l();
5414 delete mAudioMixer;
5415 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005416 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005417 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005418 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005419 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005420 track->mChannelMask,
5421 track->mFormat,
5422 track->mSessionId);
5423 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005424 "%s(): AudioMixer cannot create track(%d)"
5425 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005426 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005427 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005428 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005429 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005430 }
Eric Laurent81784c32012-11-19 14:55:58 -08005431 }
5432
Eric Laurent42537be2016-01-08 17:16:42 -08005433 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005434}
5435
5436
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005437void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005438{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005439 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005440 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005441 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005442 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005443 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5444 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5445 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005446 if (hasFastMixer()) {
5447 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5448
5449 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5450 // while we are dumping it. It may be inconsistent, but it won't mutate!
5451 // This is a large object so we place it on the heap.
5452 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005453 const std::unique_ptr<FastMixerDumpState> copy =
5454 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005455 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005456
5457#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005458 // Similar for state queue
5459 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5460 observerCopy.dump(fd);
5461 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5462 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005463#endif
5464
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005465#ifdef AUDIO_WATCHDOG
5466 if (mAudioWatchdog != 0) {
5467 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5468 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5469 wdCopy.dump(fd);
5470 }
5471#endif
5472
5473 } else {
5474 dprintf(fd, " No FastMixer\n");
5475 }
Eric Laurent81784c32012-11-19 14:55:58 -08005476}
5477
5478uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5479{
5480 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5481}
5482
5483uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5484{
5485 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5486}
5487
5488void AudioFlinger::MixerThread::cacheParameters_l()
5489{
5490 PlaybackThread::cacheParameters_l();
5491
5492 // FIXME: Relaxed timing because of a certain device that can't meet latency
5493 // Should be reduced to 2x after the vendor fixes the driver issue
5494 // increase threshold again due to low power audio mode. The way this warning
5495 // threshold is calculated and its usefulness should be reconsidered anyway.
5496 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5497}
5498
5499// ----------------------------------------------------------------------------
5500
5501AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07005502 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5503 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005504{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005505 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005506}
5507
Eric Laurent81784c32012-11-19 14:55:58 -08005508AudioFlinger::DirectOutputThread::~DirectOutputThread()
5509{
5510}
5511
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005512void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005513{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005514 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005515 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5516 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5517}
5518
5519void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5520{
5521 Mutex::Autolock _l(mLock);
5522 if (mMasterBalance != balance) {
5523 mMasterBalance.store(balance);
5524 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5525 broadcast_l();
5526 }
5527}
5528
Eric Laurent5850c4c2016-11-10 13:04:31 -08005529void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005530{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005531 float left, right;
5532
Andy Hung333ab962019-05-28 20:23:35 -07005533 // Ensure volumeshaper state always advances even when muted.
5534 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5535 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5536 proxy->framesReleased());
5537 mVolumeShaperActive = shaperActive;
5538
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005539 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005540 left = right = 0;
5541 } else {
5542 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005543 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005544
Glenn Kastenc56f3422014-03-21 17:53:17 -07005545 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5546 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5547 if (left > GAIN_FLOAT_UNITY) {
5548 left = GAIN_FLOAT_UNITY;
5549 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005550 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005551 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5552 if (right > GAIN_FLOAT_UNITY) {
5553 right = GAIN_FLOAT_UNITY;
5554 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005555 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005556 }
5557
5558 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005559 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005560 if (left != mLeftVolFloat || right != mRightVolFloat) {
5561 mLeftVolFloat = left;
5562 mRightVolFloat = right;
5563
Eric Laurentbfb1b832013-01-07 09:53:42 -08005564 // Delegate volume control to effect in track effect chain if needed
5565 // only one effect chain can be present on DirectOutputThread, so if
5566 // there is one, the track is connected to it
5567 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005568 // if effect chain exists, volume is handled by it.
5569 // Convert volumes from float to 8.24
5570 uint32_t vl = (uint32_t)(left * (1 << 24));
5571 uint32_t vr = (uint32_t)(right * (1 << 24));
5572 // Direct/Offload effect chains set output volume in setVolume_l().
5573 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5574 } else {
5575 // otherwise we directly set the volume.
5576 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005577 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005578 }
5579 }
5580}
5581
Phil Burk43b4dcc2015-06-09 16:53:44 -07005582void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5583{
5584 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005585 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005586
Eric Laurent0f0631e2015-07-06 18:01:25 -07005587 if (previousTrack != 0 && latestTrack != 0) {
5588 if (mType == DIRECT) {
5589 if (previousTrack.get() != latestTrack.get()) {
5590 mFlushPending = true;
5591 }
5592 } else /* mType == OFFLOAD */ {
5593 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5594 mFlushPending = true;
5595 }
5596 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005597 } else if (previousTrack == 0) {
5598 // there could be an old track added back during track transition for direct
5599 // output, so always issues flush to flush data of the previous track if it
5600 // was already destroyed with HAL paused, then flush can resume the playback
5601 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005602 }
5603 PlaybackThread::onAddNewTrack_l();
5604}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005605
Eric Laurent81784c32012-11-19 14:55:58 -08005606AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5607 Vector< sp<Track> > *tracksToRemove
5608)
5609{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005610 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005611 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005612 bool doHwPause = false;
5613 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005614
5615 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005616 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005617 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005618 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005619 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005620 continue;
5621 }
5622
Eric Laurent5850c4c2016-11-10 13:04:31 -08005623 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005624#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005625 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005626#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005627 // Only consider last track started for volume and mixer state control.
5628 // In theory an older track could underrun and restart after the new one starts
5629 // but as we only care about the transition phase between two tracks on a
5630 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005631 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005632 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005633
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005634 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005635 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005636 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005637 doHwPause = true;
5638 mHwPaused = true;
5639 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005640 } else if (track->isFlushPending()) {
5641 track->flushAck();
5642 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005643 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005644 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005645 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005646 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005647 if (last) {
5648 mLeftVolFloat = mRightVolFloat = -1.0;
5649 if (mHwPaused) {
5650 doHwResume = true;
5651 mHwPaused = false;
5652 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005653 }
5654 }
5655
Eric Laurent81784c32012-11-19 14:55:58 -08005656 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005657 // for all its buffers to be filled before processing it.
5658 // Allow draining the buffer in case the client
5659 // app does not call stop() and relies on underrun to stop:
5660 // hence the test on (track->mRetryCount > 1).
5661 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005662 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005663 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005664 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005665 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005666 minFrames = mNormalFrameCount;
5667 } else {
5668 minFrames = 1;
5669 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005670
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005671 const size_t framesReady = track->framesReady();
5672 const int trackId = track->id();
5673 if (ATRACE_ENABLED()) {
5674 std::string traceName("nRdy");
5675 traceName += std::to_string(trackId);
5676 ATRACE_INT(traceName.c_str(), framesReady);
5677 }
5678 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07005679 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005680 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005681 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005682
5683 if (track->mFillingUpStatus == Track::FS_FILLED) {
5684 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005685 if (last) {
5686 // make sure processVolume_l() will apply new volume even if 0
5687 mLeftVolFloat = mRightVolFloat = -1.0;
5688 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005689 if (!mHwSupportsPause) {
5690 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005691 }
5692 }
5693
5694 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005695 processVolume_l(track, last);
5696 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005697 sp<Track> previousTrack = mPreviousTrack.promote();
5698 if (previousTrack != 0) {
5699 if (track != previousTrack.get()) {
5700 // Flush any data still being written from last track
5701 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005702 // Invalidate previous track to force a seek when resuming.
5703 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005704 }
5705 }
5706 mPreviousTrack = track;
5707
Eric Laurentd595b7c2013-04-03 17:27:56 -07005708 // reset retry count
5709 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005710 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005711 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005712 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005713 doHwResume = true;
5714 mHwPaused = false;
5715 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005716 }
Eric Laurent81784c32012-11-19 14:55:58 -08005717 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005718 // clear effect chain input buffer if the last active track started underruns
5719 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005720 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005721 mEffectChains[0]->clearInputBuffer();
5722 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005723 if (track->isStopping_1()) {
5724 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005725 if (last && mHwPaused) {
5726 doHwResume = true;
5727 mHwPaused = false;
5728 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005729 }
5730 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5731 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005732 // We have consumed all the buffers of this track.
5733 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005734 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005735 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005736 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5737 } else {
5738 audioHALFrames = 0;
5739 }
5740
Andy Hung818e7a32016-02-16 18:08:07 -08005741 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005742 if (mStandby || !last ||
Aniket Kumar Lata179a0742019-01-30 14:16:16 -08005743 track->presentationComplete(framesWritten, audioHALFrames) ||
5744 track->isPaused()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005745 if (track->isStopping_2()) {
5746 track->mState = TrackBase::STOPPED;
5747 }
Eric Laurent81784c32012-11-19 14:55:58 -08005748 if (track->isStopped()) {
5749 track->reset();
5750 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005751 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005752 }
5753 } else {
5754 // No buffers for this track. Give it a few chances to
5755 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005756 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005757 if (--(track->mRetryCount) <= 0) {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005758 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07005759 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005760 // indicate to client process that the track was disabled because of underrun;
5761 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005762 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005763 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005764 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5765 "minFrames = %u, mFormat = %#x",
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005766 framesReady, minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005767 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005768 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005769 doHwPause = true;
5770 mHwPaused = true;
5771 }
Eric Laurent81784c32012-11-19 14:55:58 -08005772 }
5773 }
5774 }
5775 }
5776
Eric Laurentd1f69b02014-12-15 14:33:13 -08005777 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005778 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005779 for (size_t i = 0; i < mTracks.size(); i++) {
5780 if (mTracks[i]->isFlushPending()) {
5781 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005782 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005783 }
5784 }
5785 }
5786
5787 // make sure the pause/flush/resume sequence is executed in the right order.
5788 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5789 // before flush and then resume HW. This can happen in case of pause/flush/resume
5790 // if resume is received before pause is executed.
5791 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005792 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005793 status_t result = mOutput->stream->pause();
5794 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005795 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005796 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005797 flushHw_l();
5798 }
5799 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005800 status_t result = mOutput->stream->resume();
5801 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005802 }
Eric Laurent81784c32012-11-19 14:55:58 -08005803 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005804 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005805
5806 return mixerStatus;
5807}
5808
5809void AudioFlinger::DirectOutputThread::threadLoop_mix()
5810{
Eric Laurent81784c32012-11-19 14:55:58 -08005811 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005812 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005813 // output audio to hardware
5814 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005815 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005816 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005817 status_t status = mActiveTrack->getNextBuffer(&buffer);
5818 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005819 // no need to pad with 0 for compressed audio
5820 if (audio_has_proportional_frames(mFormat)) {
5821 memset(curBuf, 0, frameCount * mFrameSize);
5822 }
Eric Laurent81784c32012-11-19 14:55:58 -08005823 break;
5824 }
5825 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5826 frameCount -= buffer.frameCount;
5827 curBuf += buffer.frameCount * mFrameSize;
5828 mActiveTrack->releaseBuffer(&buffer);
5829 }
Andy Hung2098f272014-02-27 14:00:06 -08005830 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005831 mSleepTimeUs = 0;
5832 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005833 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005834}
5835
5836void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5837{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005838 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005839 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005840 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005841 return;
5842 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005843 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005844 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005845 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005846 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005847 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005848 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005849 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005850 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005851 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005852 }
5853}
5854
Eric Laurentd1f69b02014-12-15 14:33:13 -08005855void AudioFlinger::DirectOutputThread::threadLoop_exit()
5856{
5857 {
5858 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005859 for (size_t i = 0; i < mTracks.size(); i++) {
5860 if (mTracks[i]->isFlushPending()) {
5861 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005862 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005863 }
5864 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005865 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005866 flushHw_l();
5867 }
5868 }
5869 PlaybackThread::threadLoop_exit();
5870}
5871
5872// must be called with thread mutex locked
5873bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5874{
5875 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005876 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005877
vivek mehta9cd7ad12016-03-17 00:18:29 -07005878 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5879 return !mStandby;
5880 }
5881
Eric Laurentd1f69b02014-12-15 14:33:13 -08005882 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5883 // after a timeout and we will enter standby then.
5884 if (mTracks.size() > 0) {
5885 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005886 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5887 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005888 }
5889
Eric Laurent5cff4032015-05-26 13:49:58 -07005890 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005891}
5892
Eric Laurent10351942014-05-08 18:49:52 -07005893// checkForNewParameter_l() must be called with ThreadBase::mLock held
5894bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5895 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005896{
5897 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005898 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005899
Eric Laurent10351942014-05-08 18:49:52 -07005900 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005901
Eric Laurent10351942014-05-08 18:49:52 -07005902 AudioParameter param = AudioParameter(keyValuePair);
5903 int value;
5904 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005905 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08005906 }
Eric Laurent10351942014-05-08 18:49:52 -07005907 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5908 // do not accept frame count changes if tracks are open as the track buffer
5909 // size depends on frame count and correct behavior would not be garantied
5910 // if frame count is changed after track creation
5911 if (!mTracks.isEmpty()) {
5912 status = INVALID_OPERATION;
5913 } else {
5914 reconfig = true;
5915 }
5916 }
5917 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005918 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005919 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005920 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005921 mStandby = true;
5922 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005923 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005924 }
5925 if (status == NO_ERROR && reconfig) {
5926 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005927 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005928 }
5929 }
5930
Eric Laurent42537be2016-01-08 17:16:42 -08005931 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005932}
5933
5934uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5935{
5936 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005937 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005938 time = PlaybackThread::activeSleepTimeUs();
5939 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005940 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005941 }
5942 return time;
5943}
5944
5945uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5946{
5947 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005948 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005949 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5950 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005951 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005952 }
5953 return time;
5954}
5955
5956uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5957{
5958 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005959 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005960 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5961 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005962 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005963 }
5964 return time;
5965}
5966
5967void AudioFlinger::DirectOutputThread::cacheParameters_l()
5968{
5969 PlaybackThread::cacheParameters_l();
5970
5971 // use shorter standby delay as on normal output to release
5972 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005973 // no delay on outputs with HW A/V sync
5974 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005975 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005976 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005977 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005978 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005979 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005980 }
Eric Laurent81784c32012-11-19 14:55:58 -08005981}
5982
Eric Laurente659ef42014-09-29 13:06:46 -07005983void AudioFlinger::DirectOutputThread::flushHw_l()
5984{
Phil Burk062e67a2015-02-11 13:40:50 -08005985 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005986 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005987 mFlushPending = false;
Andy Hungf3234512018-07-03 14:51:47 -07005988 mTimestampVerifier.discontinuity(); // DIRECT and OFFLOADED flush resets frame count.
Eric Laurente659ef42014-09-29 13:06:46 -07005989}
5990
Andy Hung10cbff12017-02-21 17:30:14 -08005991int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5992 // If a VolumeShaper is active, we must wake up periodically to update volume.
5993 const int64_t NS_PER_MS = 1000000;
5994 return mVolumeShaperActive ?
5995 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5996}
5997
Eric Laurent81784c32012-11-19 14:55:58 -08005998// ----------------------------------------------------------------------------
5999
Eric Laurentbfb1b832013-01-07 09:53:42 -08006000AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006001 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006002 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006003 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006004 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006005 mDrainSequence(0),
6006 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006007{
6008}
6009
6010AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6011{
6012}
6013
6014void AudioFlinger::AsyncCallbackThread::onFirstRef()
6015{
6016 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6017}
6018
6019bool AudioFlinger::AsyncCallbackThread::threadLoop()
6020{
6021 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006022 uint32_t writeAckSequence;
6023 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006024 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006025
6026 {
6027 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006028 while (!((mWriteAckSequence & 1) ||
6029 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006030 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006031 exitPending())) {
6032 mWaitWorkCV.wait(mLock);
6033 }
6034
Eric Laurentbfb1b832013-01-07 09:53:42 -08006035 if (exitPending()) {
6036 break;
6037 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006038 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6039 mWriteAckSequence, mDrainSequence);
6040 writeAckSequence = mWriteAckSequence;
6041 mWriteAckSequence &= ~1;
6042 drainSequence = mDrainSequence;
6043 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006044 asyncError = mAsyncError;
6045 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006046 }
6047 {
Eric Laurent4de95592013-09-26 15:28:21 -07006048 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6049 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006050 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006051 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006052 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006053 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006054 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006055 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006056 if (asyncError) {
6057 playbackThread->onAsyncError();
6058 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006059 }
6060 }
6061 }
6062 return false;
6063}
6064
6065void AudioFlinger::AsyncCallbackThread::exit()
6066{
6067 ALOGV("AsyncCallbackThread::exit");
6068 Mutex::Autolock _l(mLock);
6069 requestExit();
6070 mWaitWorkCV.broadcast();
6071}
6072
Eric Laurent3b4529e2013-09-05 18:09:19 -07006073void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006074{
6075 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006076 // bit 0 is cleared
6077 mWriteAckSequence = sequence << 1;
6078}
6079
6080void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6081{
6082 Mutex::Autolock _l(mLock);
6083 // ignore unexpected callbacks
6084 if (mWriteAckSequence & 2) {
6085 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006086 mWaitWorkCV.signal();
6087 }
6088}
6089
Eric Laurent3b4529e2013-09-05 18:09:19 -07006090void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006091{
6092 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006093 // bit 0 is cleared
6094 mDrainSequence = sequence << 1;
6095}
6096
6097void AudioFlinger::AsyncCallbackThread::resetDraining()
6098{
6099 Mutex::Autolock _l(mLock);
6100 // ignore unexpected callbacks
6101 if (mDrainSequence & 2) {
6102 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006103 mWaitWorkCV.signal();
6104 }
6105}
6106
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006107void AudioFlinger::AsyncCallbackThread::setAsyncError()
6108{
6109 Mutex::Autolock _l(mLock);
6110 mAsyncError = true;
6111 mWaitWorkCV.signal();
6112}
6113
Eric Laurentbfb1b832013-01-07 09:53:42 -08006114
6115// ----------------------------------------------------------------------------
6116AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006117 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6118 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006119 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6120 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006121{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006122 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006123 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006124 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006125}
6126
Eric Laurentbfb1b832013-01-07 09:53:42 -08006127void AudioFlinger::OffloadThread::threadLoop_exit()
6128{
6129 if (mFlushPending || mHwPaused) {
6130 // If a flush is pending or track was paused, just discard buffered data
6131 flushHw_l();
6132 } else {
6133 mMixerStatus = MIXER_DRAIN_ALL;
6134 threadLoop_drain();
6135 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006136 if (mUseAsyncWrite) {
6137 ALOG_ASSERT(mCallbackThread != 0);
6138 mCallbackThread->exit();
6139 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006140 PlaybackThread::threadLoop_exit();
6141}
6142
6143AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6144 Vector< sp<Track> > *tracksToRemove
6145)
6146{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006147 size_t count = mActiveTracks.size();
6148
6149 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006150 bool doHwPause = false;
6151 bool doHwResume = false;
6152
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006153 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006154
Eric Laurentbfb1b832013-01-07 09:53:42 -08006155 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006156 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006157 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006158#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006159 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006160#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006161 // Only consider last track started for volume and mixer state control.
6162 // In theory an older track could underrun and restart after the new one starts
6163 // but as we only care about the transition phase between two tracks on a
6164 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006165 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006166 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006167
Haynes Mathew George7844f672014-01-15 12:32:55 -08006168 if (track->isInvalid()) {
6169 ALOGW("An invalidated track shouldn't be in active list");
6170 tracksToRemove->add(track);
6171 continue;
6172 }
6173
6174 if (track->mState == TrackBase::IDLE) {
6175 ALOGW("An idle track shouldn't be in active list");
6176 continue;
6177 }
6178
Eric Laurentbfb1b832013-01-07 09:53:42 -08006179 if (track->isPausing()) {
6180 track->setPaused();
6181 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006182 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006183 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006184 mHwPaused = true;
6185 }
6186 // If we were part way through writing the mixbuffer to
6187 // the HAL we must save this until we resume
6188 // BUG - this will be wrong if a different track is made active,
6189 // in that case we want to discard the pending data in the
6190 // mixbuffer and tell the client to present it again when the
6191 // track is resumed
6192 mPausedWriteLength = mCurrentWriteLength;
6193 mPausedBytesRemaining = mBytesRemaining;
6194 mBytesRemaining = 0; // stop writing
6195 }
6196 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006197 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006198 if (track->isStopping_1()) {
6199 track->mRetryCount = kMaxTrackStopRetriesOffload;
6200 } else {
6201 track->mRetryCount = kMaxTrackRetriesOffload;
6202 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006203 track->flushAck();
6204 if (last) {
6205 mFlushPending = true;
6206 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006207 } else if (track->isResumePending()){
6208 track->resumeAck();
6209 if (last) {
6210 if (mPausedBytesRemaining) {
6211 // Need to continue write that was interrupted
6212 mCurrentWriteLength = mPausedWriteLength;
6213 mBytesRemaining = mPausedBytesRemaining;
6214 mPausedBytesRemaining = 0;
6215 }
6216 if (mHwPaused) {
6217 doHwResume = true;
6218 mHwPaused = false;
6219 // threadLoop_mix() will handle the case that we need to
6220 // resume an interrupted write
6221 }
6222 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006223 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006224
Eric Laurent3df841a2016-07-15 15:15:40 -07006225 mLeftVolFloat = mRightVolFloat = -1.0;
6226
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006227 // Do not handle new data in this iteration even if track->framesReady()
6228 mixerStatus = MIXER_TRACKS_ENABLED;
6229 }
6230 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006231 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006232 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006233 if (track->mFillingUpStatus == Track::FS_FILLED) {
6234 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006235 if (last) {
6236 // make sure processVolume_l() will apply new volume even if 0
6237 mLeftVolFloat = mRightVolFloat = -1.0;
6238 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006239 }
6240
6241 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006242 sp<Track> previousTrack = mPreviousTrack.promote();
6243 if (previousTrack != 0) {
6244 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006245 // Flush any data still being written from last track
6246 mBytesRemaining = 0;
6247 if (mPausedBytesRemaining) {
6248 // Last track was paused so we also need to flush saved
6249 // mixbuffer state and invalidate track so that it will
6250 // re-submit that unwritten data when it is next resumed
6251 mPausedBytesRemaining = 0;
6252 // Invalidate is a bit drastic - would be more efficient
6253 // to have a flag to tell client that some of the
6254 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006255 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006256 }
6257 // flush data already sent to the DSP if changing audio session as audio
6258 // comes from a different source. Also invalidate previous track to force a
6259 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006260 if (previousTrack->sessionId() != track->sessionId()) {
6261 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006262 }
6263 }
6264 }
6265 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006266 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006267 if (track->isStopping_1()) {
6268 track->mRetryCount = kMaxTrackStopRetriesOffload;
6269 } else {
6270 track->mRetryCount = kMaxTrackRetriesOffload;
6271 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006272 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006273 mixerStatus = MIXER_TRACKS_READY;
6274 }
6275 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006276 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006277 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006278 if (--(track->mRetryCount) <= 0) {
6279 // Hardware buffer can hold a large amount of audio so we must
6280 // wait for all current track's data to drain before we say
6281 // that the track is stopped.
6282 if (mBytesRemaining == 0) {
6283 // Only start draining when all data in mixbuffer
6284 // has been written
6285 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6286 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6287 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6288 if (last && !mStandby) {
6289 // do not modify drain sequence if we are already draining. This happens
6290 // when resuming from pause after drain.
6291 if ((mDrainSequence & 1) == 0) {
6292 mSleepTimeUs = 0;
6293 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6294 mixerStatus = MIXER_DRAIN_TRACK;
6295 mDrainSequence += 2;
6296 }
6297 if (mHwPaused) {
6298 // It is possible to move from PAUSED to STOPPING_1 without
6299 // a resume so we must ensure hardware is running
6300 doHwResume = true;
6301 mHwPaused = false;
6302 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006303 }
6304 }
Eric Laurente93cc032016-05-05 10:15:10 -07006305 } else if (last) {
6306 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6307 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006308 }
6309 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006310 // Drain has completed or we are in standby, signal presentation complete
6311 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006312 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006313 uint32_t latency = 0;
6314 status_t result = mOutput->stream->getLatency(&latency);
6315 ALOGE_IF(result != OK,
6316 "Error when retrieving output stream latency: %d", result);
6317 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006318 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006319 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006320 track->presentationComplete(framesWritten, audioHALFrames);
6321 track->reset();
6322 tracksToRemove->add(track);
Andy Hungf3234512018-07-03 14:51:47 -07006323 // DIRECT and OFFLOADED stop resets frame counts.
6324 if (!mUseAsyncWrite) {
6325 // If we don't get explicit drain notification we must
6326 // register discontinuity regardless of whether this is
6327 // the previous (!last) or the upcoming (last) track
6328 // to avoid skipping the discontinuity.
6329 mTimestampVerifier.discontinuity();
6330 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006331 }
6332 } else {
6333 // No buffers for this track. Give it a few chances to
6334 // fill a buffer, then remove it from active list.
6335 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006336 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006337 uint64_t position = 0;
6338 struct timespec unused;
6339 // The running check restarts the retry counter at least once.
6340 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6341 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6342 running = true;
6343 mOffloadUnderrunPosition = position;
6344 }
6345 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006346 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6347 (long long)position, (long long)mOffloadUnderrunPosition);
6348 }
6349 if (running) { // still running, give us more time.
6350 track->mRetryCount = kMaxTrackRetriesOffload;
6351 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006352 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6353 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006354 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006355 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006356 // it will then automatically call start() when data is available
6357 track->disable();
6358 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006359 } else if (last){
6360 mixerStatus = MIXER_TRACKS_ENABLED;
6361 }
6362 }
6363 }
6364 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006365 if (track->isReady()) { // check ready to prevent premature start.
6366 processVolume_l(track, last);
6367 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006368 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006369
Eric Laurentea0fade2013-10-04 16:23:48 -07006370 // make sure the pause/flush/resume sequence is executed in the right order.
6371 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6372 // before flush and then resume HW. This can happen in case of pause/flush/resume
6373 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006374 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006375 status_t result = mOutput->stream->pause();
6376 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006377 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006378 if (mFlushPending) {
6379 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006380 }
Eric Laurentfd477972013-10-25 18:10:40 -07006381 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006382 status_t result = mOutput->stream->resume();
6383 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006384 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006385
Eric Laurentbfb1b832013-01-07 09:53:42 -08006386 // remove all the tracks that need to be...
6387 removeTracks_l(*tracksToRemove);
6388
6389 return mixerStatus;
6390}
6391
Eric Laurentbfb1b832013-01-07 09:53:42 -08006392// must be called with thread mutex locked
6393bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6394{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006395 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6396 mWriteAckSequence, mDrainSequence);
6397 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006398 return true;
6399 }
6400 return false;
6401}
6402
Eric Laurentbfb1b832013-01-07 09:53:42 -08006403bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6404{
6405 Mutex::Autolock _l(mLock);
6406 return waitingAsyncCallback_l();
6407}
6408
6409void AudioFlinger::OffloadThread::flushHw_l()
6410{
Eric Laurente659ef42014-09-29 13:06:46 -07006411 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006412 // Flush anything still waiting in the mixbuffer
6413 mCurrentWriteLength = 0;
6414 mBytesRemaining = 0;
6415 mPausedWriteLength = 0;
6416 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006417 // reset bytes written count to reflect that DSP buffers are empty after flush.
6418 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006419 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006420
Eric Laurentbfb1b832013-01-07 09:53:42 -08006421 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006422 // discard any pending drain or write ack by incrementing sequence
6423 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6424 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006425 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006426 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6427 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006428 }
6429}
6430
Haynes Mathew George05317d22016-05-03 16:34:26 -07006431void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6432{
6433 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006434 if (PlaybackThread::invalidateTracks_l(streamType)) {
6435 mFlushPending = true;
6436 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006437}
6438
Eric Laurentbfb1b832013-01-07 09:53:42 -08006439// ----------------------------------------------------------------------------
6440
Eric Laurent81784c32012-11-19 14:55:58 -08006441AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006442 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07006443 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006444 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006445 mWaitTimeMs(UINT_MAX)
6446{
6447 addOutputTrack(mainThread);
6448}
6449
6450AudioFlinger::DuplicatingThread::~DuplicatingThread()
6451{
6452 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6453 mOutputTracks[i]->destroy();
6454 }
6455}
6456
6457void AudioFlinger::DuplicatingThread::threadLoop_mix()
6458{
6459 // mix buffers...
6460 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006461 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006462 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006463 if (mMixerBufferValid) {
6464 memset(mMixerBuffer, 0, mMixerBufferSize);
6465 } else {
6466 memset(mSinkBuffer, 0, mSinkBufferSize);
6467 }
Eric Laurent81784c32012-11-19 14:55:58 -08006468 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006469 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006470 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006471 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006472 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006473}
6474
6475void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6476{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006477 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006478 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006479 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006480 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006481 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006482 }
6483 } else if (mBytesWritten != 0) {
6484 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6485 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006486 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006487 } else {
6488 // flush remaining overflow buffers in output tracks
6489 writeFrames = 0;
6490 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006491 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006492 }
6493}
6494
Eric Laurentbfb1b832013-01-07 09:53:42 -08006495ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006496{
6497 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006498 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6499
6500 // Consider the first OutputTrack for timestamp and frame counting.
6501
6502 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6503 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6504 // we always claim success.
6505 if (i == 0) {
6506 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6507 ALOGD_IF(correction != 0 && writeFrames != 0,
6508 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6509 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6510 mFramesWritten -= correction;
6511 }
6512
6513 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006514 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006515 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006516 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006517}
6518
6519void AudioFlinger::DuplicatingThread::threadLoop_standby()
6520{
6521 // DuplicatingThread implements standby by stopping all tracks
6522 for (size_t i = 0; i < outputTracks.size(); i++) {
6523 outputTracks[i]->stop();
6524 }
6525}
6526
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006527void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006528{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006529 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006530
6531 std::stringstream ss;
6532 const size_t numTracks = mOutputTracks.size();
6533 ss << " " << numTracks << " OutputTracks";
6534 if (numTracks > 0) {
6535 ss << ":";
6536 for (const auto &track : mOutputTracks) {
6537 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006538 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006539 if (thread.get() != nullptr) {
6540 ss << thread.get() << ", " << thread->id();
6541 } else {
6542 ss << "null";
6543 }
6544 ss << ")";
6545 }
6546 }
6547 ss << "\n";
6548 std::string result = ss.str();
6549 write(fd, result.c_str(), result.size());
6550}
6551
Eric Laurent81784c32012-11-19 14:55:58 -08006552void AudioFlinger::DuplicatingThread::saveOutputTracks()
6553{
6554 outputTracks = mOutputTracks;
6555}
6556
6557void AudioFlinger::DuplicatingThread::clearOutputTracks()
6558{
6559 outputTracks.clear();
6560}
6561
6562void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6563{
6564 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006565 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6566 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6567 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6568 const size_t frameCount =
6569 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6570 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6571 // from different OutputTracks and their associated MixerThreads (e.g. one may
6572 // nearly empty and the other may be dropping data).
6573
6574 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006575 this,
6576 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006577 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006578 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006579 frameCount,
6580 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006581 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6582 if (status != NO_ERROR) {
6583 ALOGE("addOutputTrack() initCheck failed %d", status);
6584 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006585 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006586 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6587 mOutputTracks.add(outputTrack);
6588 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6589 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006590}
6591
6592void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6593{
6594 Mutex::Autolock _l(mLock);
6595 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6596 if (mOutputTracks[i]->thread() == thread) {
6597 mOutputTracks[i]->destroy();
6598 mOutputTracks.removeAt(i);
6599 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006600 if (thread->getOutput() == mOutput) {
6601 mOutput = NULL;
6602 }
Eric Laurent81784c32012-11-19 14:55:58 -08006603 return;
6604 }
6605 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006606 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006607}
6608
6609// caller must hold mLock
6610void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6611{
6612 mWaitTimeMs = UINT_MAX;
6613 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6614 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6615 if (strong != 0) {
6616 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6617 if (waitTimeMs < mWaitTimeMs) {
6618 mWaitTimeMs = waitTimeMs;
6619 }
6620 }
6621 }
6622}
6623
6624
6625bool AudioFlinger::DuplicatingThread::outputsReady(
6626 const SortedVector< sp<OutputTrack> > &outputTracks)
6627{
6628 for (size_t i = 0; i < outputTracks.size(); i++) {
6629 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6630 if (thread == 0) {
6631 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6632 outputTracks[i].get());
6633 return false;
6634 }
6635 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6636 // see note at standby() declaration
6637 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6638 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6639 thread.get());
6640 return false;
6641 }
6642 }
6643 return true;
6644}
6645
Kevin Rocard12381092018-04-11 09:19:59 -07006646void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6647 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006648{
Kevin Rocard12381092018-04-11 09:19:59 -07006649 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6650 outputTrack->setMetadatas(metadata.tracks);
6651 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006652}
6653
Eric Laurent81784c32012-11-19 14:55:58 -08006654uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6655{
6656 return (mWaitTimeMs * 1000) / 2;
6657}
6658
6659void AudioFlinger::DuplicatingThread::cacheParameters_l()
6660{
6661 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6662 updateWaitTime_l();
6663
6664 MixerThread::cacheParameters_l();
6665}
6666
Eric Laurent6acd1d42017-01-04 14:23:29 -08006667
Eric Laurent81784c32012-11-19 14:55:58 -08006668// ----------------------------------------------------------------------------
6669// Record
6670// ----------------------------------------------------------------------------
6671
6672AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6673 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006674 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006675 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006676 ) :
jiabinc52b1ff2019-10-31 17:20:42 -07006677 ThreadBase(audioFlinger, id, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006678 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07006679 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006680 mActiveTracks(&this->mLocalLog),
6681 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006682 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006683 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006684 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6685 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006686 // mFastCapture below
6687 , mFastCaptureFutex(0)
6688 // mInputSource
6689 // mPipeSink
6690 // mPipeSource
6691 , mPipeFramesP2(0)
6692 // mPipeMemory
6693 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006694 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006695 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006696{
Glenn Kastend7dca052015-03-05 16:05:54 -08006697 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6698 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006699
Andy Hungc8fddf32018-08-08 18:32:37 -07006700 if (mInput != nullptr && mInput->audioHwDev != nullptr) {
6701 mIsMsdDevice = strcmp(
6702 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6703 }
6704
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006705 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006706
Andy Hungc8fddf32018-08-08 18:32:37 -07006707 // TODO: We may also match on address as well as device type for
6708 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07006709 // TODO: This property should be ensure that only contains one single device type.
6710 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
6711 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07006712 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
6713 : AUDIO_DEVICE_NONE));
6714
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006715 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006716 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006717 size_t numCounterOffers = 0;
6718 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006719#if !LOG_NDEBUG
6720 ssize_t index =
6721#else
6722 (void)
6723#endif
6724 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006725 ALOG_ASSERT(index == 0);
6726
6727 // initialize fast capture depending on configuration
6728 bool initFastCapture;
6729 switch (kUseFastCapture) {
6730 case FastCapture_Never:
6731 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006732 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006733 break;
6734 case FastCapture_Always:
6735 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006736 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006737 break;
6738 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006739 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006740 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6741 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6742 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006743 break;
6744 // case FastCapture_Dynamic:
6745 }
6746
6747 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006748 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006749 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006750 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6751 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006752 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006753 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006754 const sp<MemoryDealer> roHeap(readOnlyHeap());
6755 sp<IMemory> pipeMemory;
6756 if ((roHeap == 0) ||
6757 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07006758 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006759 ALOGE("not enough memory for pipe buffer size=%zu; "
6760 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6761 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6762 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006763 goto failed;
6764 }
6765 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6766 memset(pipeBuffer, 0, pipeSize);
6767 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6768 const NBAIO_Format offers[1] = {format};
6769 size_t numCounterOffers = 0;
6770 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6771 ALOG_ASSERT(index == 0);
6772 mPipeSink = pipe;
6773 PipeReader *pipeReader = new PipeReader(*pipe);
6774 numCounterOffers = 0;
6775 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6776 ALOG_ASSERT(index == 0);
6777 mPipeSource = pipeReader;
6778 mPipeFramesP2 = pipeFramesP2;
6779 mPipeMemory = pipeMemory;
6780
6781 // create fast capture
6782 mFastCapture = new FastCapture();
6783 FastCaptureStateQueue *sq = mFastCapture->sq();
6784#ifdef STATE_QUEUE_DUMP
6785 // FIXME
6786#endif
6787 FastCaptureState *state = sq->begin();
6788 state->mCblk = NULL;
6789 state->mInputSource = mInputSource.get();
6790 state->mInputSourceGen++;
6791 state->mPipeSink = pipe;
6792 state->mPipeSinkGen++;
6793 state->mFrameCount = mFrameCount;
6794 state->mCommand = FastCaptureState::COLD_IDLE;
6795 // already done in constructor initialization list
6796 //mFastCaptureFutex = 0;
6797 state->mColdFutexAddr = &mFastCaptureFutex;
6798 state->mColdGen++;
6799 state->mDumpState = &mFastCaptureDumpState;
6800#ifdef TEE_SINK
6801 // FIXME
6802#endif
6803 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6804 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6805 sq->end();
6806 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6807
6808 // start the fast capture
6809 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6810 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07006811 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006812 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006813#ifdef AUDIO_WATCHDOG
6814 // FIXME
6815#endif
6816
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006817 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006818 }
Andy Hung8946a282018-04-19 20:04:56 -07006819#ifdef TEE_SINK
6820 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
6821 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
6822#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006823failed: ;
6824
6825 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006826}
6827
Eric Laurent81784c32012-11-19 14:55:58 -08006828AudioFlinger::RecordThread::~RecordThread()
6829{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006830 if (mFastCapture != 0) {
6831 FastCaptureStateQueue *sq = mFastCapture->sq();
6832 FastCaptureState *state = sq->begin();
6833 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6834 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6835 if (old == -1) {
6836 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6837 }
6838 }
6839 state->mCommand = FastCaptureState::EXIT;
6840 sq->end();
6841 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6842 mFastCapture->join();
6843 mFastCapture.clear();
6844 }
6845 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006846 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006847 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006848}
6849
6850void AudioFlinger::RecordThread::onFirstRef()
6851{
Glenn Kastend7dca052015-03-05 16:05:54 -08006852 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006853}
6854
Eric Laurent555530a2017-02-07 18:17:24 -08006855void AudioFlinger::RecordThread::preExit()
6856{
6857 ALOGV(" preExit()");
6858 Mutex::Autolock _l(mLock);
6859 for (size_t i = 0; i < mTracks.size(); i++) {
6860 sp<RecordTrack> track = mTracks[i];
6861 track->invalidate();
6862 }
6863 mActiveTracks.clear();
6864 mStartStopCond.broadcast();
6865}
6866
Eric Laurent81784c32012-11-19 14:55:58 -08006867bool AudioFlinger::RecordThread::threadLoop()
6868{
Eric Laurent81784c32012-11-19 14:55:58 -08006869 nsecs_t lastWarning = 0;
6870
6871 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006872
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006873reacquire_wakelock:
6874 sp<RecordTrack> activeTrack;
6875 {
6876 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006877 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006878 }
6879
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006880 // used to request a deferred sleep, to be executed later while mutex is unlocked
6881 uint32_t sleepUs = 0;
6882
Andy Hung446f4df2019-02-21 12:26:41 -08006883 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
6884
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006885 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08006886 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006887 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006888
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006889 // activeTracks accumulates a copy of a subset of mActiveTracks
6890 Vector< sp<RecordTrack> > activeTracks;
6891
Glenn Kasten735f45f2014-08-18 15:51:59 -07006892 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006893 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006894
Glenn Kasten735f45f2014-08-18 15:51:59 -07006895 // reference to a fast track which is about to be removed
6896 sp<RecordTrack> fastTrackToRemove;
6897
Eric Laurent81784c32012-11-19 14:55:58 -08006898 { // scope for mLock
6899 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006900
Eric Laurent021cf962014-05-13 10:18:14 -07006901 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006902
Eric Laurent000a4192014-01-29 15:17:32 -08006903 // check exitPending here because checkForNewParameters_l() and
6904 // checkForNewParameters_l() can temporarily release mLock
6905 if (exitPending()) {
6906 break;
6907 }
6908
Eric Laurent5c25d562016-07-13 17:17:45 -07006909 // sleep with mutex unlocked
6910 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006911 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006912 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6913 ATRACE_END();
6914 sleepUs = 0;
6915 continue;
6916 }
6917
Glenn Kasten2b806402013-11-20 16:37:38 -08006918 // if no active track(s), then standby and release wakelock
6919 size_t size = mActiveTracks.size();
6920 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006921 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006922 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006923 releaseWakeLock_l();
6924 ALOGV("RecordThread: loop stopping");
6925 // go to sleep
6926 mWaitWorkCV.wait(mLock);
6927 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006928 goto reacquire_wakelock;
6929 }
6930
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006931 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006932 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006933 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006934
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006935 activeTrack = mActiveTracks[i];
6936 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006937 if (activeTrack->isFastTrack()) {
6938 ALOG_ASSERT(fastTrackToRemove == 0);
6939 fastTrackToRemove = activeTrack;
6940 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006941 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006942 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006943 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006944 continue;
6945 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006946
6947 TrackBase::track_state activeTrackState = activeTrack->mState;
6948 switch (activeTrackState) {
6949
6950 case TrackBase::PAUSING:
6951 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07006952 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006953 doBroadcast = true;
6954 size--;
6955 continue;
6956
6957 case TrackBase::STARTING_1:
6958 sleepUs = 10000;
6959 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006960 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006961 continue;
6962
6963 case TrackBase::STARTING_2:
6964 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006965 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006966 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006967 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006968 break;
6969
6970 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006971 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006972 break;
6973
Andy Hungce685402018-10-05 17:23:27 -07006974 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
6975 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
6976 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006977 default:
Andy Hungce685402018-10-05 17:23:27 -07006978 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
6979 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07006980 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006981
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006982 activeTracks.add(activeTrack);
6983 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006984
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006985 if (activeTrack->isFastTrack()) {
6986 ALOG_ASSERT(!mFastTrackAvail);
6987 ALOG_ASSERT(fastTrack == 0);
6988 fastTrack = activeTrack;
6989 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006990 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006991
Andy Hungdae27702016-10-31 14:01:16 -07006992 mActiveTracks.updatePowerState(this);
6993
Kevin Rocard069c2712018-03-29 19:09:14 -07006994 updateMetadata_l();
6995
Eric Laurent5c25d562016-07-13 17:17:45 -07006996 if (allStopped) {
6997 standbyIfNotAlreadyInStandby();
6998 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006999 if (doBroadcast) {
7000 mStartStopCond.broadcast();
7001 }
7002
7003 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007004 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007005 if (sleepUs == 0) {
7006 sleepUs = kRecordThreadSleepUs;
7007 }
7008 continue;
7009 }
7010 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007011
Eric Laurent81784c32012-11-19 14:55:58 -08007012 lockEffectChains_l(effectChains);
7013 }
7014
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007015 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007016
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007017 size_t size = effectChains.size();
7018 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007019 // thread mutex is not locked, but effect chain is locked
7020 effectChains[i]->process_l();
7021 }
7022
Glenn Kasten735f45f2014-08-18 15:51:59 -07007023 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007024 if (mFastCapture != 0) {
7025 FastCaptureStateQueue *sq = mFastCapture->sq();
7026 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007027 bool didModify = false;
7028 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007029 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7030 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7031 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7032 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7033 if (old == -1) {
7034 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7035 }
7036 }
7037 state->mCommand = FastCaptureState::READ_WRITE;
7038#if 0 // FIXME
7039 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007040 FastThreadDumpState::kSamplingNforLowRamDevice :
7041 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007042#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007043 didModify = true;
7044 }
7045 audio_track_cblk_t *cblkOld = state->mCblk;
7046 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7047 if (cblkNew != cblkOld) {
7048 state->mCblk = cblkNew;
7049 // block until acked if removing a fast track
7050 if (cblkOld != NULL) {
7051 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7052 }
7053 didModify = true;
7054 }
jiabin01c8f562018-07-19 17:47:28 -07007055 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7056 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7057 if (state->mFastPatchRecordBufferProvider != abp) {
7058 state->mFastPatchRecordBufferProvider = abp;
7059 state->mFastPatchRecordFormat = fastTrack == 0 ?
7060 AUDIO_FORMAT_INVALID : fastTrack->format();
7061 didModify = true;
7062 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007063 sq->end(didModify);
7064 if (didModify) {
7065 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007066#if 0
7067 if (kUseFastCapture == FastCapture_Dynamic) {
7068 mNormalSource = mPipeSource;
7069 }
7070#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007071 }
7072 }
7073
Glenn Kasten735f45f2014-08-18 15:51:59 -07007074 // now run the fast track destructor with thread mutex unlocked
7075 fastTrackToRemove.clear();
7076
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007077 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7078 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7079 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7080 // If destination is non-contiguous, first read past the nominal end of buffer, then
7081 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007082
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007083 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007084 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007085 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007086
7087 // If an NBAIO source is present, use it to read the normal capture's data
7088 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007089 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007090
7091 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7092 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7093 // we immediately retry the read() to get data and prevent another overflow.
7094 for (int retries = 0; retries <= 2; ++retries) {
7095 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7096 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7097 framesToRead);
7098 if (framesRead != OVERRUN) break;
7099 }
7100
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007101 const ssize_t availableToRead = mPipeSource->availableToRead();
7102 if (availableToRead >= 0) {
7103 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
7104 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7105 "more frames to read than fifo size, %zd > %zu",
7106 availableToRead, mPipeFramesP2);
7107 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7108 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7109 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7110 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007111 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7112 }
7113 if (framesRead < 0) {
7114 status_t status = (status_t) framesRead;
7115 switch (status) {
7116 case OVERRUN:
7117 ALOGW("overrun on read from pipe");
7118 framesRead = 0;
7119 break;
7120 case NEGOTIATE:
7121 ALOGE("re-negotiation is needed");
7122 framesRead = -1; // Will cause an attempt to recover.
7123 break;
7124 default:
7125 ALOGE("unknown error %d on read from pipe", status);
7126 break;
7127 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007128 }
7129 // otherwise use the HAL / AudioStreamIn directly
7130 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007131 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007132 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007133 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007134 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007135 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007136 if (result < 0) {
7137 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007138 } else {
7139 framesRead = bytesRead / mFrameSize;
7140 }
7141 }
7142
Andy Hung446f4df2019-02-21 12:26:41 -08007143 const int64_t lastIoEndNs = systemTime(); // end IO timing
7144
Andy Hung3f0c9022016-01-15 17:49:46 -08007145 // Update server timestamp with server stats
7146 // systemTime() is optional if the hardware supports timestamps.
7147 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007148 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
Andy Hung3f0c9022016-01-15 17:49:46 -08007149
7150 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007151 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007152 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007153 if (mStandby) {
7154 mTimestampVerifier.discontinuity();
Mikhail Naganov2534b382019-09-25 13:05:02 -07007155 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007156 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7157
7158 mTimestampVerifier.add(position, time, mSampleRate);
7159
7160 // Correct timestamps
7161 if (isTimestampCorrectionEnabled()) {
7162 ALOGV("TS_BEFORE: %d %lld %lld",
7163 id(), (long long)time, (long long)position);
7164 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7165 position = correctedTimestamp.mFrames;
7166 time = correctedTimestamp.mTimeNs;
7167 ALOGV("TS_AFTER: %d %lld %lld",
7168 id(), (long long)time, (long long)position);
7169 }
7170
Andy Hung3f0c9022016-01-15 17:49:46 -08007171 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7172 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7173 // Note: In general record buffers should tend to be empty in
7174 // a properly running pipeline.
7175 //
7176 // Also, it is not advantageous to call get_presentation_position during the read
7177 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007178 } else {
7179 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007180 }
7181 }
Andy Hunge6c37112019-02-26 17:38:10 -08007182
7183 // From the timestamp, input read latency is negative output write latency.
7184 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7185 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7186 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7187 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7188 mLatencyMs.add(latencyMs);
7189 }
7190
Andy Hung3f0c9022016-01-15 17:49:46 -08007191 // Use this to track timestamp information
7192 // ALOGD("%s", mTimestamp.toString().c_str());
7193
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007194 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007195 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007196 // Force input into standby so that it tries to recover at next read attempt
7197 inputStandBy();
7198 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007199 }
7200 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007201 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007202 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007203 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007204 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007205
Andy Hung8946a282018-04-19 20:04:56 -07007206#ifdef TEE_SINK
7207 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7208#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007209 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007210 {
7211 size_t part1 = mRsmpInFramesP2 - rear;
7212 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007213 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007214 (framesRead - part1) * mFrameSize);
7215 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007216 }
7217 rear = mRsmpInRear += framesRead;
7218
7219 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007220
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007221 // loop over each active track
7222 for (size_t i = 0; i < size; i++) {
7223 activeTrack = activeTracks[i];
7224
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007225 // skip fast tracks, as those are handled directly by FastCapture
7226 if (activeTrack->isFastTrack()) {
7227 continue;
7228 }
7229
Andy Hung73c02e42015-03-29 01:13:58 -07007230 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007231 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7232
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007233 enum {
7234 OVERRUN_UNKNOWN,
7235 OVERRUN_TRUE,
7236 OVERRUN_FALSE
7237 } overrun = OVERRUN_UNKNOWN;
7238
7239 // loop over getNextBuffer to handle circular sink
7240 for (;;) {
7241
7242 activeTrack->mSink.frameCount = ~0;
7243 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7244 size_t framesOut = activeTrack->mSink.frameCount;
7245 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7246
Andy Hung73c02e42015-03-29 01:13:58 -07007247 // check available frames and handle overrun conditions
7248 // if the record track isn't draining fast enough.
7249 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007250 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007251 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7252 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007253 overrun = OVERRUN_TRUE;
7254 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007255 if (framesOut == 0 || framesIn == 0) {
7256 break;
7257 }
7258
Andy Hung6770c6f2015-04-07 13:43:36 -07007259 // Don't allow framesOut to be larger than what is possible with resampling
7260 // from framesIn.
7261 // This isn't strictly necessary but helps limit buffer resizing in
7262 // RecordBufferConverter. TODO: remove when no longer needed.
7263 framesOut = min(framesOut,
7264 destinationFramesPossible(
7265 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007266
7267 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007268 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007269 // straight from RecordThread buffer to RecordTrack buffer.
7270 AudioBufferProvider::Buffer buffer;
7271 buffer.frameCount = framesOut;
7272 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7273 if (status == OK && buffer.frameCount != 0) {
7274 ALOGV_IF(buffer.frameCount != framesOut,
7275 "%s() read less than expected (%zu vs %zu)",
7276 __func__, buffer.frameCount, framesOut);
7277 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007278 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007279 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7280 } else {
7281 framesOut = 0;
7282 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7283 __func__, status, buffer.frameCount);
7284 }
7285 } else {
7286 // process frames from the RecordThread buffer provider to the RecordTrack
7287 // buffer
7288 framesOut = activeTrack->mRecordBufferConverter->convert(
7289 activeTrack->mSink.raw,
7290 activeTrack->mResamplerBufferProvider,
7291 framesOut);
7292 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007293
7294 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7295 overrun = OVERRUN_FALSE;
7296 }
7297
7298 if (activeTrack->mFramesToDrop == 0) {
7299 if (framesOut > 0) {
7300 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007301 // Sanitize before releasing if the track has no access to the source data
7302 // An idle UID receives silence from non virtual devices until active
7303 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007304 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007305 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007306 activeTrack->releaseBuffer(&activeTrack->mSink);
7307 }
7308 } else {
7309 // FIXME could do a partial drop of framesOut
7310 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007311 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007312 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007313 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007314 }
7315 } else {
7316 activeTrack->mFramesToDrop += framesOut;
7317 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7318 activeTrack->mSyncStartEvent->isCancelled()) {
7319 ALOGW("Synced record %s, session %d, trigger session %d",
7320 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7321 activeTrack->sessionId(),
7322 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007323 activeTrack->mSyncStartEvent->triggerSession() :
7324 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007325 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007326 }
7327 }
7328 }
7329
7330 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007331 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007332 }
7333 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007334
7335 switch (overrun) {
7336 case OVERRUN_TRUE:
7337 // client isn't retrieving buffers fast enough
7338 if (!activeTrack->setOverflow()) {
7339 nsecs_t now = systemTime();
7340 // FIXME should lastWarning per track?
7341 if ((now - lastWarning) > kWarningThrottleNs) {
7342 ALOGW("RecordThread: buffer overflow");
7343 lastWarning = now;
7344 }
7345 }
7346 break;
7347 case OVERRUN_FALSE:
7348 activeTrack->clearOverflow();
7349 break;
7350 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007351 break;
7352 }
7353
Andy Hung3f0c9022016-01-15 17:49:46 -08007354 // update frame information and push timestamp out
7355 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007356 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007357 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7358 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007359 }
7360
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007361unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007362 // enable changes in effect chain
7363 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007364 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007365 if (audio_has_proportional_frames(mFormat)
7366 && loopCount == lastLoopCountRead + 1) {
7367 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7368 const double jitterMs =
7369 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7370 {framesRead, readPeriodNs},
7371 {0, 0} /* lastTimestamp */, mSampleRate);
7372 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7373
7374 Mutex::Autolock _l(mLock);
7375 mIoJitterMs.add(jitterMs);
7376 mProcessTimeMs.add(processMs);
7377 }
7378 // update timing info.
7379 mLastIoBeginNs = lastIoBeginNs;
7380 mLastIoEndNs = lastIoEndNs;
7381 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007382 }
7383
Glenn Kasten93e471f2013-08-19 08:40:07 -07007384 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007385
7386 {
7387 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007388 for (size_t i = 0; i < mTracks.size(); i++) {
7389 sp<RecordTrack> track = mTracks[i];
7390 track->invalidate();
7391 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007392 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007393 mStartStopCond.broadcast();
7394 }
7395
7396 releaseWakeLock();
7397
7398 ALOGV("RecordThread %p exiting", this);
7399 return false;
7400}
7401
Glenn Kasten93e471f2013-08-19 08:40:07 -07007402void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007403{
7404 if (!mStandby) {
7405 inputStandBy();
7406 mStandby = true;
7407 }
7408}
7409
7410void AudioFlinger::RecordThread::inputStandBy()
7411{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007412 // Idle the fast capture if it's currently running
7413 if (mFastCapture != 0) {
7414 FastCaptureStateQueue *sq = mFastCapture->sq();
7415 FastCaptureState *state = sq->begin();
7416 if (!(state->mCommand & FastCaptureState::IDLE)) {
7417 state->mCommand = FastCaptureState::COLD_IDLE;
7418 state->mColdFutexAddr = &mFastCaptureFutex;
7419 state->mColdGen++;
7420 mFastCaptureFutex = 0;
7421 sq->end();
7422 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7423 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7424#if 0
7425 if (kUseFastCapture == FastCapture_Dynamic) {
7426 // FIXME
7427 }
7428#endif
7429#ifdef AUDIO_WATCHDOG
7430 // FIXME
7431#endif
7432 } else {
7433 sq->end(false /*didModify*/);
7434 }
7435 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07007436 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007437 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007438
7439 // If going into standby, flush the pipe source.
7440 if (mPipeSource.get() != nullptr) {
7441 const ssize_t flushed = mPipeSource->flush();
7442 if (flushed > 0) {
7443 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7444 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7445 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7446 }
7447 }
Eric Laurent81784c32012-11-19 14:55:58 -08007448}
7449
Glenn Kasten05997e22014-03-13 15:08:33 -07007450// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007451sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007452 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007453 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007454 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007455 audio_format_t format,
7456 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007457 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007458 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007459 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007460 pid_t creatorPid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007461 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007462 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007463 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007464 status_t *status,
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007465 audio_port_handle_t portId,
7466 const String16& opPackageName)
Eric Laurent81784c32012-11-19 14:55:58 -08007467{
Glenn Kasten74935e42013-12-19 08:56:45 -08007468 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007469 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007470 sp<RecordTrack> track;
7471 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007472 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007473 audio_input_flags_t requestedFlags = *flags;
7474 uint32_t sampleRate;
7475
7476 lStatus = initCheck();
7477 if (lStatus != NO_ERROR) {
7478 ALOGE("createRecordTrack_l() audio driver not initialized");
7479 goto Exit;
7480 }
7481
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007482 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7483 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7484 lStatus = BAD_VALUE;
7485 goto Exit;
7486 }
7487
Eric Laurentf14db3c2017-12-08 14:20:36 -08007488 if (*pSampleRate == 0) {
7489 *pSampleRate = mSampleRate;
7490 }
7491 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007492
7493 // special case for FAST flag considered OK if fast capture is present
7494 if (hasFastCapture()) {
7495 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7496 }
7497
Eric Laurentf14db3c2017-12-08 14:20:36 -08007498 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007499 if ((*flags & inputFlags) != *flags) {
7500 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7501 " input flags (%08x)",
7502 *flags, inputFlags);
7503 *flags = (audio_input_flags_t)(*flags & inputFlags);
7504 }
Eric Laurent81784c32012-11-19 14:55:58 -08007505
Glenn Kasten90e58b12013-07-31 16:16:02 -07007506 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007507 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007508 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007509 // we formerly checked for a callback handler (non-0 tid),
7510 // but that is no longer required for TRANSFER_OBTAIN mode
7511 //
Phil Burk7ed66a12019-04-18 13:20:30 -07007512 // Frame count is not specified (0), or is less than or equal the pipe depth.
7513 // It is OK to provide a higher capacity than requested.
7514 // We will force it to mPipeFramesP2 below.
7515 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007516 // PCM data
7517 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007518 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007519 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007520 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007521 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007522 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007523 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007524 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007525 hasFastCapture() &&
7526 // there are sufficient fast track slots available
7527 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007528 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007529 // check compatibility with audio effects.
7530 Mutex::Autolock _l(mLock);
7531 // Do not accept FAST flag if the session has software effects
7532 sp<EffectChain> chain = getEffectChain_l(sessionId);
7533 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007534 audio_input_flags_t old = *flags;
7535 chain->checkInputFlagCompatibility(flags);
7536 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007537 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7538 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007539 }
7540 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007541 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007542 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7543 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007544 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007545 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7546 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007547 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007548 this, frameCount, mFrameCount, mPipeFramesP2,
7549 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007550 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007551 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007552 }
7553 }
7554
Eric Laurentf14db3c2017-12-08 14:20:36 -08007555 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7556 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7557 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7558 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7559 lStatus = BAD_TYPE;
7560 goto Exit;
7561 }
7562
Glenn Kasten74105912014-07-03 12:28:53 -07007563 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007564 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007565 // fast track: frame count is exactly the pipe depth
7566 frameCount = mPipeFramesP2;
7567 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007568 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007569 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007570 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7571 // or 20 ms if there is a fast capture
7572 // TODO This could be a roundupRatio inline, and const
7573 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7574 * sampleRate + mSampleRate - 1) / mSampleRate;
7575 // minimum number of notification periods is at least kMinNotifications,
7576 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7577 static const size_t kMinNotifications = 3;
7578 static const uint32_t kMinMs = 30;
7579 // TODO This could be a roundupRatio inline
7580 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7581 // TODO This could be a roundupRatio inline
7582 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7583 maxNotificationFrames;
7584 const size_t minFrameCount = maxNotificationFrames *
7585 max(kMinNotifications, minNotificationsByMs);
7586 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007587 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7588 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007589 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007590 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007591 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007592 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007593
7594 { // scope for mLock
7595 Mutex::Autolock _l(mLock);
7596
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007597 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007598 format, channelMask, frameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007599 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid, uid,
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007600 *flags, TrackBase::TYPE_DEFAULT, opPackageName, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007601
Glenn Kasten03003332013-08-06 15:40:54 -07007602 lStatus = track->initCheck();
7603 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007604 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007605 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007606 goto Exit;
7607 }
7608 mTracks.add(track);
7609
Eric Laurent05067782016-06-01 18:27:28 -07007610 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007611 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7612 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7613 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007614 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007615 }
Eric Laurent81784c32012-11-19 14:55:58 -08007616 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007617
Eric Laurent81784c32012-11-19 14:55:58 -08007618 lStatus = NO_ERROR;
7619
7620Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007621 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007622 return track;
7623}
7624
7625status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7626 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007627 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007628{
7629 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7630 sp<ThreadBase> strongMe = this;
7631 status_t status = NO_ERROR;
7632
7633 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007634 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007635 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007636 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007637 triggerSession,
7638 recordTrack->sessionId(),
7639 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007640 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007641 // Sync event can be cancelled by the trigger session if the track is not in a
7642 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007643 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007644 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007645 } else {
7646 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007647 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007648 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007649 }
7650 }
7651
7652 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007653 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007654 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007655 if (recordTrack->isInvalid()) {
7656 recordTrack->clearSyncStartEvent();
7657 return INVALID_OPERATION;
7658 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007659 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7660 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07007661 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
7662 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007663 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007664 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007665 } else {
7666 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007667 }
7668 return status;
7669 }
7670
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007671 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7672 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7673 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007674 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007675 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007676 status_t status = NO_ERROR;
7677 if (recordTrack->isExternalTrack()) {
7678 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08007679 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007680 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07007681 if (recordTrack->isInvalid()) {
7682 recordTrack->clearSyncStartEvent();
7683 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
7684 recordTrack->mState = TrackBase::STARTING_2;
7685 // STARTING_2 forces destroy to call stopInput.
7686 }
7687 return INVALID_OPERATION;
7688 }
7689 if (recordTrack->mState != TrackBase::STARTING_1) {
7690 ALOGW("%s(%d): unsynchronized mState:%d change",
7691 __func__, recordTrack->id(), recordTrack->mState);
7692 // Someone else has changed state, let them take over,
7693 // leave mState in the new state.
7694 recordTrack->clearSyncStartEvent();
7695 return INVALID_OPERATION;
7696 }
7697 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07007698 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07007699 ALOGW("%s(%d): startInput failed, status %d",
7700 __func__, recordTrack->id(), status);
7701 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
7702 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07007703 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007704 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07007705 return status;
7706 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07007707 sendIoConfigEvent_l(
7708 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08007709 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007710 // Catch up with current buffer indices if thread is already running.
7711 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7712 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7713 // see previously buffered data before it called start(), but with greater risk of overrun.
7714
Andy Hung73c02e42015-03-29 01:13:58 -07007715 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007716 if (!recordTrack->isDirect()) {
7717 // clear any converter state as new data will be discontinuous
7718 recordTrack->mRecordBufferConverter->reset();
7719 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007720 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007721 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007722 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007723 return status;
7724 }
Eric Laurent81784c32012-11-19 14:55:58 -08007725}
7726
Eric Laurent81784c32012-11-19 14:55:58 -08007727void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7728{
7729 sp<SyncEvent> strongEvent = event.promote();
7730
7731 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007732 sp<RefBase> ptr = strongEvent->cookie().promote();
7733 if (ptr != 0) {
7734 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7735 recordTrack->handleSyncStartEvent(strongEvent);
7736 }
Eric Laurent81784c32012-11-19 14:55:58 -08007737 }
7738}
7739
Glenn Kastena8356f62013-07-25 14:37:52 -07007740bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007741 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007742 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007743 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007744 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007745 return false;
7746 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007747 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007748 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07007749
Andy Hungabfab202019-03-07 19:45:54 -08007750 // NOTE: Waiting here is important to keep stop synchronous.
7751 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07007752 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
7753 mWaitWorkCV.broadcast(); // signal thread to stop
7754 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08007755 }
Andy Hungce685402018-10-05 17:23:27 -07007756
7757 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08007758 ALOGV("Record stopped OK");
7759 return true;
7760 }
Andy Hungce685402018-10-05 17:23:27 -07007761
7762 // don't handle anything - we've been invalidated or restarted and in a different state
7763 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
7764 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007765 return false;
7766}
7767
Glenn Kasten0f11b512014-01-31 16:18:54 -08007768bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007769{
7770 return false;
7771}
7772
Glenn Kasten0f11b512014-01-31 16:18:54 -08007773status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007774{
7775#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7776 if (!isValidSyncEvent(event)) {
7777 return BAD_VALUE;
7778 }
7779
Glenn Kastend848eb42016-03-08 13:42:11 -08007780 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007781 status_t ret = NAME_NOT_FOUND;
7782
7783 Mutex::Autolock _l(mLock);
7784
7785 for (size_t i = 0; i < mTracks.size(); i++) {
7786 sp<RecordTrack> track = mTracks[i];
7787 if (eventSession == track->sessionId()) {
7788 (void) track->setSyncEvent(event);
7789 ret = NO_ERROR;
7790 }
7791 }
7792 return ret;
7793#else
7794 return BAD_VALUE;
7795#endif
7796}
7797
jiabin653cc0a2018-01-17 17:54:10 -08007798status_t AudioFlinger::RecordThread::getActiveMicrophones(
7799 std::vector<media::MicrophoneInfo>* activeMicrophones)
7800{
7801 ALOGV("RecordThread::getActiveMicrophones");
7802 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007803 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7804 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007805}
7806
Paul McLean12340082019-03-19 09:35:05 -06007807status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
7808 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07007809{
Paul McLean12340082019-03-19 09:35:05 -06007810 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007811 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06007812 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007813}
7814
Paul McLean12340082019-03-19 09:35:05 -06007815status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07007816{
Paul McLean12340082019-03-19 09:35:05 -06007817 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007818 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06007819 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007820}
7821
Kevin Rocard069c2712018-03-29 19:09:14 -07007822void AudioFlinger::RecordThread::updateMetadata_l()
7823{
7824 if (mInput == nullptr || mInput->stream == nullptr ||
7825 !mActiveTracks.readAndClearHasChanged()) {
7826 return;
7827 }
7828 StreamInHalInterface::SinkMetadata metadata;
7829 for (const sp<RecordTrack> &track : mActiveTracks) {
7830 // No track is invalid as this is called after prepareTrack_l in the same critical section
7831 metadata.tracks.push_back({
7832 .source = track->attributes().source,
7833 .gain = 1, // capture tracks do not have volumes
7834 });
7835 }
7836 mInput->stream->updateSinkMetadata(metadata);
7837}
7838
Eric Laurent81784c32012-11-19 14:55:58 -08007839// destroyTrack_l() must be called with ThreadBase::mLock held
7840void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7841{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007842 track->terminate();
7843 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007844 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007845 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007846 removeTrack_l(track);
7847 }
7848}
7849
7850void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7851{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007852 String8 result;
7853 track->appendDump(result, false /* active */);
7854 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7855
Eric Laurent81784c32012-11-19 14:55:58 -08007856 mTracks.remove(track);
7857 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007858 if (track->isFastTrack()) {
7859 ALOG_ASSERT(!mFastTrackAvail);
7860 mFastTrackAvail = true;
7861 }
Eric Laurent81784c32012-11-19 14:55:58 -08007862}
7863
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007864void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007865{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007866 AudioStreamIn *input = mInput;
7867 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7868 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08007869 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07007870 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07007871 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007872 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007873 }
Andy Hungbfa64962017-06-12 14:43:19 -07007874
7875 if (input != nullptr) {
7876 dprintf(fd, " Hal stream dump:\n");
7877 (void)input->stream->dump(fd);
7878 }
7879
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007880 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007881 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007882
Glenn Kasten2f90c512015-12-02 11:40:09 -08007883 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7884 // while we are dumping it. It may be inconsistent, but it won't mutate!
7885 // This is a large object so we place it on the heap.
7886 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07007887 const std::unique_ptr<FastCaptureDumpState> copy =
7888 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08007889 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08007890}
7891
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007892void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007893{
Eric Laurent81784c32012-11-19 14:55:58 -08007894 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007895 size_t numtracks = mTracks.size();
7896 size_t numactive = mActiveTracks.size();
7897 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007898 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007899 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007900 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007901 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007902 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007903 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007904 for (size_t i = 0; i < numtracks ; ++i) {
7905 sp<RecordTrack> track = mTracks[i];
7906 if (track != 0) {
7907 bool active = mActiveTracks.indexOf(track) >= 0;
7908 if (active) {
7909 numactiveseen++;
7910 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007911 result.append(prefix);
7912 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007913 }
Eric Laurent81784c32012-11-19 14:55:58 -08007914 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007915 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007916 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007917 }
7918
Marco Nelissenb2208842014-02-07 14:00:50 -08007919 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007920 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007921 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007922 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007923 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007924 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007925 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007926 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007927 result.append(prefix);
7928 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007929 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007930 }
Eric Laurent81784c32012-11-19 14:55:58 -08007931
7932 }
7933 write(fd, result.string(), result.size());
7934}
7935
Eric Laurent5ada82e2019-08-29 17:53:54 -07007936void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007937{
7938 Mutex::Autolock _l(mLock);
7939 for (size_t i = 0; i < mTracks.size() ; i++) {
7940 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07007941 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007942 track->setSilenced(silenced);
7943 }
7944 }
7945}
Andy Hung73c02e42015-03-29 01:13:58 -07007946
7947void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7948{
7949 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7950 RecordThread *recordThread = (RecordThread *) threadBase.get();
7951 mRsmpInFront = recordThread->mRsmpInRear;
7952 mRsmpInUnrel = 0;
7953}
7954
7955void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7956 size_t *framesAvailable, bool *hasOverrun)
7957{
7958 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7959 RecordThread *recordThread = (RecordThread *) threadBase.get();
7960 const int32_t rear = recordThread->mRsmpInRear;
7961 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07007962 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07007963
7964 size_t framesIn;
7965 bool overrun = false;
7966 if (filled < 0) {
7967 // should not happen, but treat like a massive overrun and re-sync
7968 framesIn = 0;
7969 mRsmpInFront = rear;
7970 overrun = true;
7971 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7972 framesIn = (size_t) filled;
7973 } else {
7974 // client is not keeping up with server, but give it latest data
7975 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07007976 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
7977 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07007978 overrun = true;
7979 }
7980 if (framesAvailable != NULL) {
7981 *framesAvailable = framesIn;
7982 }
7983 if (hasOverrun != NULL) {
7984 *hasOverrun = overrun;
7985 }
7986}
7987
Eric Laurent81784c32012-11-19 14:55:58 -08007988// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007989status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007990 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007991{
Andy Hung73c02e42015-03-29 01:13:58 -07007992 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007993 if (threadBase == 0) {
7994 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007995 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007996 return NOT_ENOUGH_DATA;
7997 }
7998 RecordThread *recordThread = (RecordThread *) threadBase.get();
7999 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008000 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008001 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008002 // FIXME should not be P2 (don't want to increase latency)
8003 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008004 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008005 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008006 front &= recordThread->mRsmpInFramesP2 - 1;
8007 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008008 if (part1 > (size_t) filled) {
8009 part1 = filled;
8010 }
8011 size_t ask = buffer->frameCount;
8012 ALOG_ASSERT(ask > 0);
8013 if (part1 > ask) {
8014 part1 = ask;
8015 }
8016 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008017 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008018 buffer->raw = NULL;
8019 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008020 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008021 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008022 }
8023
Andy Hung57446612015-04-19 23:56:46 -07008024 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008025 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008026 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008027 return NO_ERROR;
8028}
8029
8030// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008031void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8032 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008033{
Hongwei Wang95e37682019-04-12 11:13:36 -07008034 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008035 if (stepCount == 0) {
8036 return;
8037 }
Andy Hung73c02e42015-03-29 01:13:58 -07008038 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8039 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008040 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008041 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008042 buffer->frameCount = 0;
8043}
8044
Eric Laurentd8365c52017-07-16 15:27:05 -07008045void AudioFlinger::RecordThread::checkBtNrec()
8046{
8047 Mutex::Autolock _l(mLock);
8048 checkBtNrec_l();
8049}
8050
8051void AudioFlinger::RecordThread::checkBtNrec_l()
8052{
8053 // disable AEC and NS if the device is a BT SCO headset supporting those
8054 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07008055 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008056 mAudioFlinger->btNrecIsOff();
8057 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8058 for (size_t i = 0; i < mEffectChains.size(); i++) {
8059 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8060 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8061 }
8062 }
8063}
8064
Andy Hung97a893e2015-03-29 01:03:07 -07008065
Eric Laurent10351942014-05-08 18:49:52 -07008066bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8067 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008068{
8069 bool reconfig = false;
8070
Eric Laurent10351942014-05-08 18:49:52 -07008071 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008072
Eric Laurent10351942014-05-08 18:49:52 -07008073 audio_format_t reqFormat = mFormat;
8074 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008075 // 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 -07008076 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8077
8078 AudioParameter param = AudioParameter(keyValuePair);
8079 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008080
8081 // scope for AutoPark extends to end of method
8082 AutoPark<FastCapture> park(mFastCapture);
8083
Eric Laurent10351942014-05-08 18:49:52 -07008084 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8085 // channel count change can be requested. Do we mandate the first client defines the
8086 // HAL sampling rate and channel count or do we allow changes on the fly?
8087 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8088 samplingRate = value;
8089 reconfig = true;
8090 }
8091 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008092 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008093 status = BAD_VALUE;
8094 } else {
8095 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008096 reconfig = true;
8097 }
Eric Laurent10351942014-05-08 18:49:52 -07008098 }
8099 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8100 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008101 if (!audio_is_input_channel(mask) ||
8102 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07008103 status = BAD_VALUE;
8104 } else {
8105 channelMask = mask;
8106 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008107 }
Eric Laurent10351942014-05-08 18:49:52 -07008108 }
8109 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8110 // do not accept frame count changes if tracks are open as the track buffer
8111 // size depends on frame count and correct behavior would not be guaranteed
8112 // if frame count is changed after track creation
8113 if (mActiveTracks.size() > 0) {
8114 status = INVALID_OPERATION;
8115 } else {
8116 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008117 }
Eric Laurent10351942014-05-08 18:49:52 -07008118 }
8119 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008120 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008121 }
8122 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8123 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07008124 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008125 }
Glenn Kastene198c362013-08-13 09:13:36 -07008126
Eric Laurent10351942014-05-08 18:49:52 -07008127 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008128 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008129 if (status == INVALID_OPERATION) {
8130 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008131 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008132 }
8133 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008134 if (status == BAD_VALUE) {
8135 uint32_t sRate;
8136 audio_channel_mask_t channelMask;
8137 audio_format_t format;
8138 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
8139 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
8140 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
8141 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
8142 status = NO_ERROR;
8143 }
Eric Laurent81784c32012-11-19 14:55:58 -08008144 }
Eric Laurent10351942014-05-08 18:49:52 -07008145 if (status == NO_ERROR) {
8146 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008147 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008148 }
8149 }
Eric Laurent81784c32012-11-19 14:55:58 -08008150 }
Eric Laurent10351942014-05-08 18:49:52 -07008151
Eric Laurent81784c32012-11-19 14:55:58 -08008152 return reconfig;
8153}
8154
8155String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8156{
Eric Laurent81784c32012-11-19 14:55:58 -08008157 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008158 if (initCheck() == NO_ERROR) {
8159 String8 out_s8;
8160 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8161 return out_s8;
8162 }
Eric Laurent81784c32012-11-19 14:55:58 -08008163 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008164 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008165}
8166
Eric Laurent09f1ed22019-04-24 17:45:17 -07008167void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8168 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008169 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8170
8171 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008172
8173 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008174 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008175 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008176 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008177 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008178 desc->mChannelMask = mChannelMask;
8179 desc->mSamplingRate = mSampleRate;
8180 desc->mFormat = mFormat;
8181 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008182 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008183 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008184 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008185 case AUDIO_CLIENT_STARTED:
8186 desc->mPatch = mPatch;
8187 desc->mPortId = portId;
8188 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008189 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008190 default:
8191 break;
8192 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008193 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008194}
8195
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008196void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008197{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008198 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8199 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008200 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008201 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8202 if (audio_is_linear_pcm(mFormat)) {
8203 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
8204 mChannelCount, FCC_8);
8205 } else {
8206 // Can have more that FCC_8 channels in encoded streams.
8207 ALOGI("HAL format %#x is not linear pcm", mFormat);
8208 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008209 result = mInput->stream->getFrameSize(&mFrameSize);
8210 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8211 result = mInput->stream->getBufferSize(&mBufferSize);
8212 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008213 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008214 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
8215 "mBufferSize=%lld, mFrameCount=%lld",
8216 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
8217 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008218 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08008219 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
Glenn Kasten85948432013-08-19 12:09:05 -07008220 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08008221 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008222 // A larger value should allow more old data to be read after a track calls start(),
8223 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07008224 //
8225 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08008226 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07008227 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07008228 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07008229 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008230
8231 // TODO optimize audio capture buffer sizes ...
8232 // Here we calculate the size of the sliding buffer used as a source
8233 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8234 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8235 // be better to have it derived from the pipe depth in the long term.
8236 // The current value is higher than necessary. However it should not add to latency.
8237
Glenn Kasten85948432013-08-19 12:09:05 -07008238 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07008239 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8240 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08008241 // if posix_memalign fails, will segv here.
8242 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08008243
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008244 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8245 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08008246}
8247
Glenn Kasten5f972c02014-01-13 09:59:31 -08008248uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008249{
8250 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008251 uint32_t result;
8252 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8253 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008254 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008255 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008256}
8257
Glenn Kastend848eb42016-03-08 13:42:11 -08008258KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008259{
Glenn Kastend848eb42016-03-08 13:42:11 -08008260 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008261 Mutex::Autolock _l(mLock);
8262 for (size_t j = 0; j < mTracks.size(); ++j) {
8263 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008264 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008265 if (ids.indexOfKey(sessionId) < 0) {
8266 ids.add(sessionId, true);
8267 }
8268 }
8269 return ids;
8270}
8271
8272AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8273{
8274 Mutex::Autolock _l(mLock);
8275 AudioStreamIn *input = mInput;
8276 mInput = NULL;
8277 return input;
8278}
8279
8280// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008281sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008282{
8283 if (mInput == NULL) {
8284 return NULL;
8285 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008286 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008287}
8288
8289status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8290{
Eric Laurent81784c32012-11-19 14:55:58 -08008291 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008292 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008293 chain->setInBuffer(NULL);
8294 chain->setOutBuffer(NULL);
8295
8296 checkSuspendOnAddEffectChain_l(chain);
8297
Eric Laurent1b928682014-10-02 19:41:47 -07008298 // make sure enabled pre processing effects state is communicated to the HAL as we
8299 // just moved them to a new input stream.
8300 chain->syncHalEffectsState();
8301
Eric Laurent81784c32012-11-19 14:55:58 -08008302 mEffectChains.add(chain);
8303
8304 return NO_ERROR;
8305}
8306
8307size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8308{
8309 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008310
8311 for (size_t i = 0; i < mEffectChains.size(); i++) {
8312 if (chain == mEffectChains[i]) {
8313 mEffectChains.removeAt(i);
8314 break;
8315 }
Eric Laurent81784c32012-11-19 14:55:58 -08008316 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008317 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008318}
8319
Eric Laurent1c333e22014-05-20 10:48:17 -07008320status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8321 audio_patch_handle_t *handle)
8322{
8323 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008324
8325 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07008326 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
8327 mInDeviceTypeAddr.mAddress = patch->sources[0].ext.device.address;
François Gaffie0c280aa2018-07-25 10:02:15 +02008328 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07008329 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008330 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07008331 }
8332
Eric Laurentd8365c52017-07-16 15:27:05 -07008333 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008334
8335 // store new source and send to effects
8336 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8337 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008338 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008339 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008340 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008341 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008342
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008343 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008344 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8345 status = hwDevice->createAudioPatch(patch->num_sources,
8346 patch->sources,
8347 patch->num_sinks,
8348 patch->sinks,
8349 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008350 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008351 char *address;
8352 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8353 address = audio_device_address_to_parameter(
8354 patch->sources[0].ext.device.type,
8355 patch->sources[0].ext.device.address);
8356 } else {
8357 address = (char *)calloc(1, 1);
8358 }
8359 AudioParameter param = AudioParameter(String8(address));
8360 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008361 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008362 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008363 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008364 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008365 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008366 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008367 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008368
jiabinc52b1ff2019-10-31 17:20:42 -07008369 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008370 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07008371 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07008372 }
Eric Laurent296fb132015-05-01 11:38:42 -07008373
Eric Laurent1c333e22014-05-20 10:48:17 -07008374 return status;
8375}
8376
8377status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8378{
8379 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008380
jiabinc52b1ff2019-10-31 17:20:42 -07008381 mPatch = audio_patch{};
8382 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07008383
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008384 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008385 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8386 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008387 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008388 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008389 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008390 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008391 }
8392 return status;
8393}
8394
jiabinc52b1ff2019-10-31 17:20:42 -07008395void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
8396{
8397 mOutDevices = outDevices;
8398 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
8399 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008400 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07008401 }
8402}
8403
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008404void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008405{
8406 Mutex::Autolock _l(mLock);
8407 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008408 if (record->getSource()) {
8409 mSource = record->getSource();
8410 }
Eric Laurent83b88082014-06-20 18:31:16 -07008411}
8412
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008413void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008414{
8415 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008416 if (mSource == record->getSource()) {
8417 mSource = mInput;
8418 }
Eric Laurent83b88082014-06-20 18:31:16 -07008419 destroyTrack_l(record);
8420}
8421
Mikhail Naganovdc769682018-05-04 15:34:08 -07008422void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008423{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008424 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008425 config->role = AUDIO_PORT_ROLE_SINK;
8426 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8427 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008428 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8429 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8430 config->flags.input = mInput->flags;
8431 }
Eric Laurent83b88082014-06-20 18:31:16 -07008432}
Eric Laurent1c333e22014-05-20 10:48:17 -07008433
Eric Laurent6acd1d42017-01-04 14:23:29 -08008434// ----------------------------------------------------------------------------
8435// Mmap
8436// ----------------------------------------------------------------------------
8437
8438AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8439 : mThread(thread)
8440{
Phil Burk9fabbf82017-08-03 12:02:00 -07008441 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008442}
8443
8444AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8445{
Phil Burk9fabbf82017-08-03 12:02:00 -07008446 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008447}
8448
8449status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8450 struct audio_mmap_buffer_info *info)
8451{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008452 return mThread->createMmapBuffer(minSizeFrames, info);
8453}
8454
8455status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8456{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008457 return mThread->getMmapPosition(position);
8458}
8459
Eric Laurenta54f1282017-07-01 19:39:32 -07008460status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08008461 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008462
8463{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008464 return mThread->start(client, handle);
8465}
8466
8467status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8468{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008469 return mThread->stop(handle);
8470}
8471
Eric Laurent18b57012017-02-13 16:23:52 -08008472status_t AudioFlinger::MmapThreadHandle::standby()
8473{
Eric Laurent18b57012017-02-13 16:23:52 -08008474 return mThread->standby();
8475}
8476
Eric Laurent6acd1d42017-01-04 14:23:29 -08008477
8478AudioFlinger::MmapThread::MmapThread(
8479 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07008480 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady)
8481 : ThreadBase(audioFlinger, id, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008482 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02008483 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008484 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008485 mActiveTracks(&this->mLocalLog),
8486 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8487 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008488{
Eric Laurent18b57012017-02-13 16:23:52 -08008489 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008490 readHalParameters_l();
8491}
8492
8493AudioFlinger::MmapThread::~MmapThread()
8494{
Eric Laurent18b57012017-02-13 16:23:52 -08008495 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008496}
8497
8498void AudioFlinger::MmapThread::onFirstRef()
8499{
8500 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8501}
8502
8503void AudioFlinger::MmapThread::disconnect()
8504{
Eric Laurent331679c2018-04-16 17:03:16 -07008505 ActiveTracks<MmapTrack> activeTracks;
8506 {
8507 Mutex::Autolock _l(mLock);
8508 for (const sp<MmapTrack> &t : mActiveTracks) {
8509 activeTracks.add(t);
8510 }
8511 }
8512 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008513 stop(t->portId());
8514 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008515 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008516 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008517 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008518 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008519 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008520 }
8521}
8522
8523
8524void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8525 audio_stream_type_t streamType __unused,
8526 audio_session_t sessionId,
8527 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008528 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008529 audio_port_handle_t portId)
8530{
8531 mAttr = *attr;
8532 mSessionId = sessionId;
8533 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008534 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008535 mPortId = portId;
8536}
8537
8538status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8539 struct audio_mmap_buffer_info *info)
8540{
8541 if (mHalStream == 0) {
8542 return NO_INIT;
8543 }
Eric Laurent18b57012017-02-13 16:23:52 -08008544 mStandby = true;
8545 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008546 return mHalStream->createMmapBuffer(minSizeFrames, info);
8547}
8548
8549status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8550{
8551 if (mHalStream == 0) {
8552 return NO_INIT;
8553 }
8554 return mHalStream->getMmapPosition(position);
8555}
8556
Eric Laurent331679c2018-04-16 17:03:16 -07008557status_t AudioFlinger::MmapThread::exitStandby()
8558{
8559 status_t ret = mHalStream->start();
8560 if (ret != NO_ERROR) {
8561 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8562 return ret;
8563 }
8564 mStandby = false;
8565 return NO_ERROR;
8566}
8567
Eric Laurenta54f1282017-07-01 19:39:32 -07008568status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008569 audio_port_handle_t *handle)
8570{
Eric Laurenta54f1282017-07-01 19:39:32 -07008571 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8572 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008573 if (mHalStream == 0) {
8574 return NO_INIT;
8575 }
8576
8577 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008578
Eric Laurenta54f1282017-07-01 19:39:32 -07008579 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008580 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008581 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008582 }
8583
8584 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8585
8586 audio_io_handle_t io = mId;
8587 if (isOutput()) {
8588 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8589 config.sample_rate = mSampleRate;
8590 config.channel_mask = mChannelMask;
8591 config.format = mFormat;
8592 audio_stream_type_t stream = streamType();
8593 audio_output_flags_t flags =
8594 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008595 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08008596 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07008597 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8598 mSessionId,
8599 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008600 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008601 client.clientUid,
8602 &config,
8603 flags,
8604 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08008605 &portId,
8606 &secondaryOutputs);
8607 ALOGD_IF(!secondaryOutputs.empty(),
8608 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008609 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008610 audio_config_base_t config;
8611 config.sample_rate = mSampleRate;
8612 config.channel_mask = mChannelMask;
8613 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008614 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008615 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07008616 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07008617 mSessionId,
8618 client.clientPid,
8619 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008620 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008621 &config,
8622 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8623 &deviceId,
8624 &portId);
8625 }
8626 // APM should not chose a different input or output stream for the same set of attributes
8627 // and audo configuration
8628 if (ret != NO_ERROR || io != mId) {
8629 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8630 __FUNCTION__, ret, io, mId);
8631 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008632 }
8633
8634 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008635 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008636 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08008637 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008638 }
8639
Eric Laurent331679c2018-04-16 17:03:16 -07008640 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008641 // abort if start is rejected by audio policy manager
8642 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008643 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07008644 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07008645 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008646 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008647 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008648 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008649 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008650 }
Eric Laurent331679c2018-04-16 17:03:16 -07008651 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008652 } else {
8653 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008654 }
8655 return PERMISSION_DENIED;
8656 }
8657
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008658 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8659 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008660 isOutput(), client.clientUid, client.clientPid,
8661 IPCThreadState::self()->getCallingPid(), portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008662
Eric Laurent4eb58f12018-12-07 16:41:02 -08008663 if (isOutput()) {
8664 // force volume update when a new track is added
8665 mHalVolFloat = -1.0f;
8666 } else if (!track->isSilenced_l()) {
8667 for (const sp<MmapTrack> &t : mActiveTracks) {
8668 if (t->isSilenced_l() && t->uid() != client.clientUid)
8669 t->invalidate();
8670 }
8671 }
8672
8673
Eric Laurent6acd1d42017-01-04 14:23:29 -08008674 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008675 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008676 if (chain != 0) {
8677 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8678 chain->incTrackCnt();
8679 chain->incActiveTrackCnt();
8680 }
8681
8682 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008683 broadcast_l();
8684
Eric Laurenta54f1282017-07-01 19:39:32 -07008685 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008686
8687 return NO_ERROR;
8688}
8689
8690status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8691{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008692 ALOGV("%s handle %d", __FUNCTION__, handle);
8693
8694 if (mHalStream == 0) {
8695 return NO_INIT;
8696 }
8697
Eric Laurenta54f1282017-07-01 19:39:32 -07008698 if (handle == mPortId) {
8699 mHalStream->stop();
8700 return NO_ERROR;
8701 }
8702
Eric Laurent331679c2018-04-16 17:03:16 -07008703 Mutex::Autolock _l(mLock);
8704
Eric Laurent6acd1d42017-01-04 14:23:29 -08008705 sp<MmapTrack> track;
8706 for (const sp<MmapTrack> &t : mActiveTracks) {
8707 if (handle == t->portId()) {
8708 track = t;
8709 break;
8710 }
8711 }
8712 if (track == 0) {
8713 return BAD_VALUE;
8714 }
8715
8716 mActiveTracks.remove(track);
8717
Eric Laurent331679c2018-04-16 17:03:16 -07008718 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008719 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008720 AudioSystem::stopOutput(track->portId());
8721 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008722 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008723 AudioSystem::stopInput(track->portId());
8724 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008725 }
Eric Laurent331679c2018-04-16 17:03:16 -07008726 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008727
8728 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8729 if (chain != 0) {
8730 chain->decActiveTrackCnt();
8731 chain->decTrackCnt();
8732 }
8733
8734 broadcast_l();
8735
Eric Laurent6acd1d42017-01-04 14:23:29 -08008736 return NO_ERROR;
8737}
8738
Eric Laurent18b57012017-02-13 16:23:52 -08008739status_t AudioFlinger::MmapThread::standby()
8740{
8741 ALOGV("%s", __FUNCTION__);
8742
8743 if (mHalStream == 0) {
8744 return NO_INIT;
8745 }
Eric Tan39ec8d62018-07-24 09:49:29 -07008746 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08008747 return INVALID_OPERATION;
8748 }
8749 mHalStream->standby();
8750 mStandby = true;
8751 releaseWakeLock();
8752 return NO_ERROR;
8753}
8754
Eric Laurent6acd1d42017-01-04 14:23:29 -08008755
8756void AudioFlinger::MmapThread::readHalParameters_l()
8757{
8758 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8759 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8760 mFormat = mHALFormat;
8761 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8762 result = mHalStream->getFrameSize(&mFrameSize);
8763 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8764 result = mHalStream->getBufferSize(&mBufferSize);
8765 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8766 mFrameCount = mBufferSize / mFrameSize;
8767}
8768
8769bool AudioFlinger::MmapThread::threadLoop()
8770{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008771 checkSilentMode_l();
8772
8773 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8774
8775 while (!exitPending())
8776 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008777 Vector< sp<EffectChain> > effectChains;
8778
Andy Hung13850be2019-03-14 11:33:09 -07008779 { // under Thread lock
8780 Mutex::Autolock _l(mLock);
8781
Eric Laurent6acd1d42017-01-04 14:23:29 -08008782 if (mSignalPending) {
8783 // A signal was raised while we were unlocked
8784 mSignalPending = false;
8785 } else {
8786 if (mConfigEvents.isEmpty()) {
8787 // we're about to wait, flush the binder command buffer
8788 IPCThreadState::self()->flushCommands();
8789
8790 if (exitPending()) {
8791 break;
8792 }
8793
Eric Laurent6acd1d42017-01-04 14:23:29 -08008794 // wait until we have something to do...
8795 ALOGV("%s going to sleep", myName.string());
8796 mWaitWorkCV.wait(mLock);
8797 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008798
8799 checkSilentMode_l();
8800
8801 continue;
8802 }
8803 }
8804
8805 processConfigEvents_l();
8806
8807 processVolume_l();
8808
8809 checkInvalidTracks_l();
8810
8811 mActiveTracks.updatePowerState(this);
8812
Kevin Rocard069c2712018-03-29 19:09:14 -07008813 updateMetadata_l();
8814
Eric Laurent6acd1d42017-01-04 14:23:29 -08008815 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07008816 } // release Thread lock
8817
Eric Laurent6acd1d42017-01-04 14:23:29 -08008818 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07008819 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08008820 }
Andy Hung13850be2019-03-14 11:33:09 -07008821
8822 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008823 unlockEffectChains(effectChains);
8824 // Effect chains will be actually deleted here if they were removed from
8825 // mEffectChains list during mixing or effects processing
8826 }
8827
8828 threadLoop_exit();
8829
8830 if (!mStandby) {
8831 threadLoop_standby();
8832 mStandby = true;
8833 }
8834
Eric Laurent6acd1d42017-01-04 14:23:29 -08008835 ALOGV("Thread %p type %d exiting", this, mType);
8836 return false;
8837}
8838
8839// checkForNewParameter_l() must be called with ThreadBase::mLock held
8840bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8841 status_t& status)
8842{
8843 AudioParameter param = AudioParameter(keyValuePair);
8844 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008845 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008846 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008847 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008848 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008849 if (sendToHal) {
8850 status = mHalStream->setParameters(keyValuePair);
8851 } else {
8852 status = NO_ERROR;
8853 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008854
8855 return false;
8856}
8857
8858String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8859{
8860 Mutex::Autolock _l(mLock);
8861 String8 out_s8;
8862 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8863 return out_s8;
8864 }
8865 return String8();
8866}
8867
Eric Laurent09f1ed22019-04-24 17:45:17 -07008868void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8869 audio_port_handle_t portId __unused) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008870 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8871
8872 desc->mIoHandle = mId;
8873
8874 switch (event) {
8875 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008876 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008877 case AUDIO_INPUT_CONFIG_CHANGED:
8878 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008879 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008880 case AUDIO_OUTPUT_CONFIG_CHANGED:
8881 desc->mPatch = mPatch;
8882 desc->mChannelMask = mChannelMask;
8883 desc->mSamplingRate = mSampleRate;
8884 desc->mFormat = mFormat;
8885 desc->mFrameCount = mFrameCount;
8886 desc->mFrameCountHAL = mFrameCount;
8887 desc->mLatency = 0;
8888 break;
8889
8890 case AUDIO_INPUT_CLOSED:
8891 case AUDIO_OUTPUT_CLOSED:
8892 default:
8893 break;
8894 }
8895 mAudioFlinger->ioConfigChanged(event, desc, pid);
8896}
8897
8898status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8899 audio_patch_handle_t *handle)
8900{
8901 status_t status = NO_ERROR;
8902
8903 // store new device and send to effects
8904 audio_devices_t type = AUDIO_DEVICE_NONE;
8905 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -07008906 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
8907 AudioDeviceTypeAddr sourceDeviceTypeAddr;
8908 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008909 if (isOutput()) {
8910 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07008911 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
8912 && !mAudioHwDev->supportsAudioPatches(),
8913 "Enumerated device type(%#x) must not be used "
8914 "as it does not support audio patches",
8915 patch->sinks[i].ext.device.type);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008916 type |= patch->sinks[i].ext.device.type;
jiabinc52b1ff2019-10-31 17:20:42 -07008917 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
8918 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08008919 }
8920 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07008921 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008922 } else {
8923 type = patch->sources[0].ext.device.type;
8924 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07008925 numDevices = mPatch.num_sources;
8926 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
8927 sourceDeviceTypeAddr.mAddress = patch->sources[0].ext.device.address;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008928 }
8929
8930 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008931 if (isOutput()) {
8932 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
8933 } else {
8934 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
8935 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008936 }
8937
jiabinc52b1ff2019-10-31 17:20:42 -07008938 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008939 // store new source and send to effects
8940 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8941 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8942 for (size_t i = 0; i < mEffectChains.size(); i++) {
8943 mEffectChains[i]->setAudioSource_l(mAudioSource);
8944 }
8945 }
8946 }
8947
8948 if (mAudioHwDev->supportsAudioPatches()) {
8949 status = mHalDevice->createAudioPatch(patch->num_sources,
8950 patch->sources,
8951 patch->num_sinks,
8952 patch->sinks,
8953 handle);
8954 } else {
8955 char *address;
8956 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8957 //FIXME: we only support address on first sink with HAL version < 3.0
8958 address = audio_device_address_to_parameter(
8959 patch->sinks[0].ext.device.type,
8960 patch->sinks[0].ext.device.address);
8961 } else {
8962 address = (char *)calloc(1, 1);
8963 }
8964 AudioParameter param = AudioParameter(String8(address));
8965 free(address);
8966 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8967 if (!isOutput()) {
8968 param.addInt(String8(AudioParameter::keyInputSource),
8969 (int)patch->sinks[0].ext.mix.usecase.source);
8970 }
8971 status = mHalStream->setParameters(param.toString());
8972 *handle = AUDIO_PATCH_HANDLE_NONE;
8973 }
8974
jiabinc52b1ff2019-10-31 17:20:42 -07008975 if (numDevices == 0 || mDeviceId != deviceId) {
8976 if (isOutput()) {
8977 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
8978 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
8979 } else {
8980 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
8981 mInDeviceTypeAddr = sourceDeviceTypeAddr;
8982 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08008983 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008984 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008985 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008986 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008987 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008988 }
jiabinc52b1ff2019-10-31 17:20:42 -07008989 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008990 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008991 }
8992 return status;
8993}
8994
8995status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8996{
8997 status_t status = NO_ERROR;
8998
jiabinc52b1ff2019-10-31 17:20:42 -07008999 mPatch = audio_patch{};
9000 mOutDeviceTypeAddrs.clear();
9001 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009002
9003 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9004 supportsAudioPatches : false;
9005
9006 if (supportsAudioPatches) {
9007 status = mHalDevice->releaseAudioPatch(handle);
9008 } else {
9009 AudioParameter param;
9010 param.addInt(String8(AudioParameter::keyRouting), 0);
9011 status = mHalStream->setParameters(param.toString());
9012 }
9013 return status;
9014}
9015
Mikhail Naganovdc769682018-05-04 15:34:08 -07009016void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009017{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009018 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009019 if (isOutput()) {
9020 config->role = AUDIO_PORT_ROLE_SOURCE;
9021 config->ext.mix.hw_module = mAudioHwDev->handle();
9022 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9023 } else {
9024 config->role = AUDIO_PORT_ROLE_SINK;
9025 config->ext.mix.hw_module = mAudioHwDev->handle();
9026 config->ext.mix.usecase.source = mAudioSource;
9027 }
9028}
9029
9030status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9031{
9032 audio_session_t session = chain->sessionId();
9033
9034 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9035 // Attach all tracks with same session ID to this chain.
9036 // indicate all active tracks in the chain
9037 for (const sp<MmapTrack> &track : mActiveTracks) {
9038 if (session == track->sessionId()) {
9039 chain->incTrackCnt();
9040 chain->incActiveTrackCnt();
9041 }
9042 }
9043
9044 chain->setThread(this);
9045 chain->setInBuffer(nullptr);
9046 chain->setOutBuffer(nullptr);
9047 chain->syncHalEffectsState();
9048
9049 mEffectChains.add(chain);
9050 checkSuspendOnAddEffectChain_l(chain);
9051 return NO_ERROR;
9052}
9053
9054size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9055{
9056 audio_session_t session = chain->sessionId();
9057
9058 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9059
9060 for (size_t i = 0; i < mEffectChains.size(); i++) {
9061 if (chain == mEffectChains[i]) {
9062 mEffectChains.removeAt(i);
9063 // detach all active tracks from the chain
9064 // detach all tracks with same session ID from this chain
9065 for (const sp<MmapTrack> &track : mActiveTracks) {
9066 if (session == track->sessionId()) {
9067 chain->decActiveTrackCnt();
9068 chain->decTrackCnt();
9069 }
9070 }
9071 break;
9072 }
9073 }
9074 return mEffectChains.size();
9075}
9076
Eric Laurent6acd1d42017-01-04 14:23:29 -08009077void AudioFlinger::MmapThread::threadLoop_standby()
9078{
9079 mHalStream->standby();
9080}
9081
9082void AudioFlinger::MmapThread::threadLoop_exit()
9083{
Phil Burk7dce7282017-09-27 13:51:41 -07009084 // Do not call callback->onTearDown() because it is redundant for thread exit
9085 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009086}
9087
9088status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9089{
9090 return BAD_VALUE;
9091}
9092
9093bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9094{
9095 return false;
9096}
9097
9098status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9099 const effect_descriptor_t *desc, audio_session_t sessionId)
9100{
9101 // No global effect sessions on mmap threads
9102 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
9103 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
9104 desc->name, mThreadName);
9105 return BAD_VALUE;
9106 }
9107
9108 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9109 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9110 desc->name);
9111 return BAD_VALUE;
9112 }
9113 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009114 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9115 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009116 return BAD_VALUE;
9117 }
9118
9119 // Only allow effects without processing load or latency
9120 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9121 return BAD_VALUE;
9122 }
9123
9124 return NO_ERROR;
9125
9126}
9127
9128void AudioFlinger::MmapThread::checkInvalidTracks_l()
9129{
9130 for (const sp<MmapTrack> &track : mActiveTracks) {
9131 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009132 sp<MmapStreamCallback> callback = mCallback.promote();
9133 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009134 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009135 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009136 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009137 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9138 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9139 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009140 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009141 }
9142 }
9143}
9144
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009145void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009146{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009147 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9148 mAttr.content_type, mAttr.usage, mAttr.source);
9149 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009150 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009151 dprintf(fd, " No active clients\n");
9152 }
9153}
9154
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009155void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009156{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009157 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009158 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009159 dprintf(fd, " %zu Tracks\n", numtracks);
9160 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009161 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009162 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009163 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009164 for (size_t i = 0; i < numtracks ; ++i) {
9165 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009166 result.append(prefix);
9167 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009168 }
9169 } else {
9170 dprintf(fd, "\n");
9171 }
9172 write(fd, result.string(), result.size());
9173}
9174
9175AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9176 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009177 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
9178 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009179 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009180 mStreamVolume(1.0),
9181 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009182 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009183{
9184 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9185 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9186 mMasterVolume = audioFlinger->masterVolume_l();
9187 mMasterMute = audioFlinger->masterMute_l();
9188 if (mAudioHwDev) {
9189 if (mAudioHwDev->canSetMasterVolume()) {
9190 mMasterVolume = 1.0;
9191 }
9192
9193 if (mAudioHwDev->canSetMasterMute()) {
9194 mMasterMute = false;
9195 }
9196 }
9197}
9198
9199void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9200 audio_stream_type_t streamType,
9201 audio_session_t sessionId,
9202 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009203 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009204 audio_port_handle_t portId)
9205{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009206 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009207 mStreamType = streamType;
9208}
9209
9210AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9211{
9212 Mutex::Autolock _l(mLock);
9213 AudioStreamOut *output = mOutput;
9214 mOutput = NULL;
9215 return output;
9216}
9217
9218void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9219{
9220 Mutex::Autolock _l(mLock);
9221 // Don't apply master volume in SW if our HAL can do it for us.
9222 if (mAudioHwDev &&
9223 mAudioHwDev->canSetMasterVolume()) {
9224 mMasterVolume = 1.0;
9225 } else {
9226 mMasterVolume = value;
9227 }
9228}
9229
9230void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9231{
9232 Mutex::Autolock _l(mLock);
9233 // Don't apply master mute in SW if our HAL can do it for us.
9234 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9235 mMasterMute = false;
9236 } else {
9237 mMasterMute = muted;
9238 }
9239}
9240
9241void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9242{
9243 Mutex::Autolock _l(mLock);
9244 if (stream == mStreamType) {
9245 mStreamVolume = value;
9246 broadcast_l();
9247 }
9248}
9249
9250float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9251{
9252 Mutex::Autolock _l(mLock);
9253 if (stream == mStreamType) {
9254 return mStreamVolume;
9255 }
9256 return 0.0f;
9257}
9258
9259void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9260{
9261 Mutex::Autolock _l(mLock);
9262 if (stream == mStreamType) {
9263 mStreamMute= muted;
9264 broadcast_l();
9265 }
9266}
9267
9268void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9269{
9270 Mutex::Autolock _l(mLock);
9271 if (streamType == mStreamType) {
9272 for (const sp<MmapTrack> &track : mActiveTracks) {
9273 track->invalidate();
9274 }
9275 broadcast_l();
9276 }
9277}
9278
9279void AudioFlinger::MmapPlaybackThread::processVolume_l()
9280{
9281 float volume;
9282
9283 if (mMasterMute || mStreamMute) {
9284 volume = 0;
9285 } else {
9286 volume = mMasterVolume * mStreamVolume;
9287 }
9288
9289 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009290
9291 // Convert volumes from float to 8.24
9292 uint32_t vol = (uint32_t)(volume * (1 << 24));
9293
9294 // Delegate volume control to effect in track effect chain if needed
9295 // only one effect chain can be present on DirectOutputThread, so if
9296 // there is one, the track is connected to it
9297 if (!mEffectChains.isEmpty()) {
9298 mEffectChains[0]->setVolume_l(&vol, &vol);
9299 volume = (float)vol / (1 << 24);
9300 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009301 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009302 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9303 mHalVolFloat = volume; // HW volume control worked, so update value.
9304 mNoCallbackWarningCount = 0;
9305 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009306 sp<MmapStreamCallback> callback = mCallback.promote();
9307 if (callback != 0) {
9308 int channelCount;
9309 if (isOutput()) {
9310 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9311 } else {
9312 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9313 }
9314 Vector<float> values;
9315 for (int i = 0; i < channelCount; i++) {
9316 values.add(volume);
9317 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009318 mHalVolFloat = volume; // SW volume control worked, so update value.
9319 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009320 mLock.unlock();
9321 callback->onVolumeChanged(mChannelMask, values);
9322 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009323 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009324 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9325 ALOGW("Could not set MMAP stream volume: no volume callback!");
9326 mNoCallbackWarningCount++;
9327 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009328 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009329 }
9330 }
9331}
9332
Kevin Rocard069c2712018-03-29 19:09:14 -07009333void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9334{
9335 if (mOutput == nullptr || mOutput->stream == nullptr ||
9336 !mActiveTracks.readAndClearHasChanged()) {
9337 return;
9338 }
9339 StreamOutHalInterface::SourceMetadata metadata;
9340 for (const sp<MmapTrack> &track : mActiveTracks) {
9341 // No track is invalid as this is called after prepareTrack_l in the same critical section
9342 metadata.tracks.push_back({
9343 .usage = track->attributes().usage,
9344 .content_type = track->attributes().content_type,
9345 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
9346 });
9347 }
9348 mOutput->stream->updateSourceMetadata(metadata);
9349}
9350
Eric Laurent6acd1d42017-01-04 14:23:29 -08009351void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9352{
9353 if (!mMasterMute) {
9354 char value[PROPERTY_VALUE_MAX];
9355 if (property_get("ro.audio.silent", value, "0") > 0) {
9356 char *endptr;
9357 unsigned long ul = strtoul(value, &endptr, 0);
9358 if (*endptr == '\0' && ul != 0) {
9359 ALOGD("Silence is golden");
9360 // The setprop command will not allow a property to be changed after
9361 // the first time it is set, so we don't have to worry about un-muting.
9362 setMasterMute_l(true);
9363 }
9364 }
9365 }
9366}
9367
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009368void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9369{
9370 MmapThread::toAudioPortConfig(config);
9371 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9372 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9373 config->flags.output = mOutput->flags;
9374 }
9375}
9376
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009377void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009378{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009379 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009380
Glenn Kastend3bb6452016-12-05 18:14:37 -08009381 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9382 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009383 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9384}
9385
9386AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9387 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009388 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
9389 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009390 mInput(input)
9391{
9392 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9393 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9394}
9395
Eric Laurent331679c2018-04-16 17:03:16 -07009396status_t AudioFlinger::MmapCaptureThread::exitStandby()
9397{
Phil Burkf054fc32018-12-06 09:45:59 -08009398 {
9399 // mInput might have been cleared by clearInput()
9400 Mutex::Autolock _l(mLock);
9401 if (mInput != nullptr && mInput->stream != nullptr) {
9402 mInput->stream->setGain(1.0f);
9403 }
9404 }
Eric Laurent331679c2018-04-16 17:03:16 -07009405 return MmapThread::exitStandby();
9406}
9407
Eric Laurent6acd1d42017-01-04 14:23:29 -08009408AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9409{
9410 Mutex::Autolock _l(mLock);
9411 AudioStreamIn *input = mInput;
9412 mInput = NULL;
9413 return input;
9414}
Kevin Rocard069c2712018-03-29 19:09:14 -07009415
Eric Laurent331679c2018-04-16 17:03:16 -07009416
9417void AudioFlinger::MmapCaptureThread::processVolume_l()
9418{
9419 bool changed = false;
9420 bool silenced = false;
9421
9422 sp<MmapStreamCallback> callback = mCallback.promote();
9423 if (callback == 0) {
9424 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9425 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9426 mNoCallbackWarningCount++;
9427 }
9428 }
9429
9430 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9431 // track is silenced and unmute otherwise
9432 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9433 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9434 changed = true;
9435 silenced = mActiveTracks[i]->isSilenced_l();
9436 }
9437 }
9438
9439 if (changed) {
9440 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9441 }
9442}
9443
Kevin Rocard069c2712018-03-29 19:09:14 -07009444void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9445{
9446 if (mInput == nullptr || mInput->stream == nullptr ||
9447 !mActiveTracks.readAndClearHasChanged()) {
9448 return;
9449 }
9450 StreamInHalInterface::SinkMetadata metadata;
9451 for (const sp<MmapTrack> &track : mActiveTracks) {
9452 // No track is invalid as this is called after prepareTrack_l in the same critical section
9453 metadata.tracks.push_back({
9454 .source = track->attributes().source,
9455 .gain = 1, // capture tracks do not have volumes
9456 });
9457 }
9458 mInput->stream->updateSinkMetadata(metadata);
9459}
9460
Eric Laurent5ada82e2019-08-29 17:53:54 -07009461void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -07009462{
9463 Mutex::Autolock _l(mLock);
9464 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07009465 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -07009466 mActiveTracks[i]->setSilenced_l(silenced);
9467 broadcast_l();
9468 }
9469 }
9470}
9471
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009472void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9473{
9474 MmapThread::toAudioPortConfig(config);
9475 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9476 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9477 config->flags.input = mInput->flags;
9478 }
9479}
9480
Glenn Kasten63238ef2015-03-02 15:50:29 -08009481} // namespace android