blob: e70c77697e33654f30a09b188bc264c98a9d0440 [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
Eric Laurent3fd6a2c2019-12-13 00:33:32 +00001149void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1150 bool enabled,
1151 audio_session_t sessionId)
1152{
1153 Mutex::Autolock _l(mLock);
1154 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1155}
Eric Laurent81784c32012-11-19 14:55:58 -08001156
Eric Laurent3fd6a2c2019-12-13 00:33:32 +00001157void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1158 bool enabled,
1159 audio_session_t sessionId)
1160{
Eric Laurent81784c32012-11-19 14:55:58 -08001161 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
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001167 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001168 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1169 }
1170 }
1171
Eric Laurent3fd6a2c2019-12-13 00:33:32 +00001172 sp<EffectChain> chain = getEffectChain_l(sessionId);
1173 if (chain != 0) {
1174 chain->checkSuspendOnEffectEnabled(effect, enabled);
Eric Laurent81784c32012-11-19 14:55:58 -08001175 }
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{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001182 // No global output effect sessions on record threads
1183 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1184 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001185 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1186 desc->name, mThreadName);
1187 return BAD_VALUE;
1188 }
1189 // only pre processing effects on record thread
1190 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1191 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1192 desc->name, mThreadName);
1193 return BAD_VALUE;
1194 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001195
1196 // always allow effects without processing load or latency
1197 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1198 return NO_ERROR;
1199 }
1200
Eric Laurent4c415062016-06-17 16:14:16 -07001201 audio_input_flags_t flags = mInput->flags;
1202 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1203 if (flags & AUDIO_INPUT_FLAG_RAW) {
1204 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1205 desc->name, mThreadName);
1206 return BAD_VALUE;
1207 }
1208 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1209 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1210 desc->name, mThreadName);
1211 return BAD_VALUE;
1212 }
1213 }
1214 return NO_ERROR;
1215}
1216
1217// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1218status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1219 const effect_descriptor_t *desc, audio_session_t sessionId)
1220{
1221 // no preprocessing on playback threads
1222 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1223 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1224 " thread %s", desc->name, mThreadName);
1225 return BAD_VALUE;
1226 }
1227
Eric Laurent3e4de772017-07-16 16:55:08 -07001228 // always allow effects without processing load or latency
1229 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1230 return NO_ERROR;
1231 }
1232
Eric Laurent4c415062016-06-17 16:14:16 -07001233 switch (mType) {
1234 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001235#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001236 // Reject any effect on mixer multichannel sinks.
1237 // TODO: fix both format and multichannel issues with effects.
1238 if (mChannelCount != FCC_2) {
1239 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1240 " thread %s", desc->name, mChannelCount, mThreadName);
1241 return BAD_VALUE;
1242 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001243#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001244 audio_output_flags_t flags = mOutput->flags;
1245 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1246 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1247 // global effects are applied only to non fast tracks if they are SW
1248 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1249 break;
1250 }
1251 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1252 // only post processing on output stage session
1253 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1254 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1255 " on output stage session", desc->name);
1256 return BAD_VALUE;
1257 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001258 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1259 // only post processing on output stage session
1260 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1261 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1262 " on device session", desc->name);
1263 return BAD_VALUE;
1264 }
Eric Laurent4c415062016-06-17 16:14:16 -07001265 } else {
1266 // no restriction on effects applied on non fast tracks
1267 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1268 break;
1269 }
1270 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001271
Eric Laurent4c415062016-06-17 16:14:16 -07001272 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1273 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1274 desc->name);
1275 return BAD_VALUE;
1276 }
1277 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1278 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1279 " in fast mode", desc->name);
1280 return BAD_VALUE;
1281 }
1282 }
1283 } break;
1284 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001285 // nothing actionable on offload threads, if the effect:
1286 // - is offloadable: the effect can be created
1287 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1288 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001289 break;
1290 case DIRECT:
1291 // Reject any effect on Direct output threads for now, since the format of
1292 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1293 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1294 desc->name, mThreadName);
1295 return BAD_VALUE;
1296 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001297#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001298 // Reject any effect on mixer multichannel sinks.
1299 // TODO: fix both format and multichannel issues with effects.
1300 if (mChannelCount != FCC_2) {
1301 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1302 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1303 return BAD_VALUE;
1304 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001305#endif
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001306 if (audio_is_global_session(sessionId)) {
Eric Laurent4c415062016-06-17 16:14:16 -07001307 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1308 " thread %s", desc->name, mThreadName);
1309 return BAD_VALUE;
1310 }
1311 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1312 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1313 " DUPLICATING thread %s", desc->name, mThreadName);
1314 return BAD_VALUE;
1315 }
1316 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1317 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1318 " DUPLICATING thread %s", desc->name, mThreadName);
1319 return BAD_VALUE;
1320 }
1321 break;
1322 default:
1323 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1324 }
1325
1326 return NO_ERROR;
1327}
1328
Eric Laurent81784c32012-11-19 14:55:58 -08001329// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1330sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1331 const sp<AudioFlinger::Client>& client,
1332 const sp<IEffectClient>& effectClient,
1333 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001334 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001335 effect_descriptor_t *desc,
1336 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001337 status_t *status,
1338 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001339{
1340 sp<EffectModule> effect;
1341 sp<EffectHandle> handle;
1342 status_t lStatus;
1343 sp<EffectChain> chain;
1344 bool chainCreated = false;
1345 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001346 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001347
1348 lStatus = initCheck();
1349 if (lStatus != NO_ERROR) {
1350 ALOGW("createEffect_l() Audio driver not initialized.");
1351 goto Exit;
1352 }
1353
Eric Laurent81784c32012-11-19 14:55:58 -08001354 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1355
1356 { // scope for mLock
1357 Mutex::Autolock _l(mLock);
1358
Eric Laurent4c415062016-06-17 16:14:16 -07001359 lStatus = checkEffectCompatibility_l(desc, sessionId);
1360 if (lStatus != NO_ERROR) {
1361 goto Exit;
1362 }
1363
Eric Laurent81784c32012-11-19 14:55:58 -08001364 // check for existing effect chain with the requested audio session
1365 chain = getEffectChain_l(sessionId);
1366 if (chain == 0) {
1367 // create a new chain for this session
1368 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1369 chain = new EffectChain(this, sessionId);
1370 addEffectChain_l(chain);
1371 chain->setStrategy(getStrategyForSession_l(sessionId));
1372 chainCreated = true;
1373 } else {
1374 effect = chain->getEffectFromDesc_l(desc);
1375 }
1376
1377 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1378
1379 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001380 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001381 // create a new effect module if none present in the chain
Eric Laurent3fd6a2c2019-12-13 00:33:32 +00001382 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001383 if (lStatus != NO_ERROR) {
1384 goto Exit;
1385 }
1386 effectCreated = true;
1387
jiabinc52b1ff2019-10-31 17:20:42 -07001388 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001389 effect->setDevices(outDeviceTypeAddrs());
1390 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001391 effect->setMode(mAudioFlinger->getMode());
1392 effect->setAudioSource(mAudioSource);
1393 }
1394 // create effect handle and connect it to effect module
1395 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001396 lStatus = handle->initCheck();
1397 if (lStatus == OK) {
1398 lStatus = effect->addHandle(handle.get());
1399 }
Eric Laurent81784c32012-11-19 14:55:58 -08001400 if (enabled != NULL) {
1401 *enabled = (int)effect->isEnabled();
1402 }
1403 }
1404
1405Exit:
1406 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1407 Mutex::Autolock _l(mLock);
1408 if (effectCreated) {
1409 chain->removeEffect_l(effect);
1410 }
Eric Laurent81784c32012-11-19 14:55:58 -08001411 if (chainCreated) {
1412 removeEffectChain_l(chain);
1413 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001414 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001415 }
1416
Glenn Kasten9156ef32013-08-06 15:39:08 -07001417 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001418 return handle;
1419}
1420
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001421void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1422 bool unpinIfLast)
1423{
1424 bool remove = false;
1425 sp<EffectModule> effect;
1426 {
1427 Mutex::Autolock _l(mLock);
1428
1429 effect = handle->effect().promote();
Eric Laurent3fd6a2c2019-12-13 00:33:32 +00001430 if (effect == 0) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001431 return;
1432 }
1433 // restore suspended effects if the disconnected handle was enabled and the last one.
1434 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1435 if (remove) {
1436 removeEffect_l(effect, true);
1437 }
1438 }
1439 if (remove) {
1440 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001441 if (handle->enabled()) {
Eric Laurent3fd6a2c2019-12-13 00:33:32 +00001442 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001443 }
1444 }
1445}
1446
Glenn Kastend848eb42016-03-08 13:42:11 -08001447sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1448 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001449{
1450 Mutex::Autolock _l(mLock);
1451 return getEffect_l(sessionId, effectId);
1452}
1453
Glenn Kastend848eb42016-03-08 13:42:11 -08001454sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1455 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001456{
1457 sp<EffectChain> chain = getEffectChain_l(sessionId);
1458 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1459}
1460
Eric Laurent6c796322019-04-09 14:13:17 -07001461std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1462{
1463 sp<EffectChain> chain = getEffectChain_l(sessionId);
1464 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1465}
1466
Eric Laurent81784c32012-11-19 14:55:58 -08001467// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1468// PlaybackThread::mLock held
1469status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1470{
1471 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001472 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001473 sp<EffectChain> chain = getEffectChain_l(sessionId);
1474 bool chainCreated = false;
1475
Eric Laurent5baf2af2013-09-12 17:37:00 -07001476 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001477 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001478 this, effect->desc().name, effect->desc().flags);
1479
Eric Laurent81784c32012-11-19 14:55:58 -08001480 if (chain == 0) {
1481 // create a new chain for this session
1482 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1483 chain = new EffectChain(this, sessionId);
1484 addEffectChain_l(chain);
1485 chain->setStrategy(getStrategyForSession_l(sessionId));
1486 chainCreated = true;
1487 }
1488 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1489
1490 if (chain->getEffectFromId_l(effect->id()) != 0) {
1491 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1492 this, effect->desc().name, chain.get());
1493 return BAD_VALUE;
1494 }
1495
Eric Laurent5baf2af2013-09-12 17:37:00 -07001496 effect->setOffloaded(mType == OFFLOAD, mId);
1497
Eric Laurent81784c32012-11-19 14:55:58 -08001498 status_t status = chain->addEffect_l(effect);
1499 if (status != NO_ERROR) {
1500 if (chainCreated) {
1501 removeEffectChain_l(chain);
1502 }
1503 return status;
1504 }
1505
jiabin8f278ee2019-11-11 12:16:27 -08001506 effect->setDevices(outDeviceTypeAddrs());
1507 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001508 effect->setMode(mAudioFlinger->getMode());
1509 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001510
Eric Laurent81784c32012-11-19 14:55:58 -08001511 return NO_ERROR;
1512}
1513
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001514void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001515
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001516 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001517 effect_descriptor_t desc = effect->desc();
1518 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1519 detachAuxEffect_l(effect->id());
1520 }
1521
Eric Laurent3fd6a2c2019-12-13 00:33:32 +00001522 sp<EffectChain> chain = effect->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001523 if (chain != 0) {
1524 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001525 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001526 removeEffectChain_l(chain);
1527 }
1528 } else {
1529 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1530 }
1531}
1532
1533void AudioFlinger::ThreadBase::lockEffectChains_l(
1534 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1535{
1536 effectChains = mEffectChains;
1537 for (size_t i = 0; i < mEffectChains.size(); i++) {
1538 mEffectChains[i]->lock();
1539 }
1540}
1541
1542void AudioFlinger::ThreadBase::unlockEffectChains(
1543 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1544{
1545 for (size_t i = 0; i < effectChains.size(); i++) {
1546 effectChains[i]->unlock();
1547 }
1548}
1549
Glenn Kastend848eb42016-03-08 13:42:11 -08001550sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001551{
1552 Mutex::Autolock _l(mLock);
1553 return getEffectChain_l(sessionId);
1554}
1555
Glenn Kastend848eb42016-03-08 13:42:11 -08001556sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1557 const
Eric Laurent81784c32012-11-19 14:55:58 -08001558{
1559 size_t size = mEffectChains.size();
1560 for (size_t i = 0; i < size; i++) {
1561 if (mEffectChains[i]->sessionId() == sessionId) {
1562 return mEffectChains[i];
1563 }
1564 }
1565 return 0;
1566}
1567
1568void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1569{
1570 Mutex::Autolock _l(mLock);
1571 size_t size = mEffectChains.size();
1572 for (size_t i = 0; i < size; i++) {
1573 mEffectChains[i]->setMode_l(mode);
1574 }
1575}
1576
Mikhail Naganovdc769682018-05-04 15:34:08 -07001577void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001578{
1579 config->type = AUDIO_PORT_TYPE_MIX;
1580 config->ext.mix.handle = mId;
1581 config->sample_rate = mSampleRate;
1582 config->format = mFormat;
1583 config->channel_mask = mChannelMask;
1584 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1585 AUDIO_PORT_CONFIG_FORMAT;
1586}
1587
Eric Laurent72e3f392015-05-20 14:43:50 -07001588void AudioFlinger::ThreadBase::systemReady()
1589{
1590 Mutex::Autolock _l(mLock);
1591 if (mSystemReady) {
1592 return;
1593 }
1594 mSystemReady = true;
1595
1596 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1597 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1598 }
1599 mPendingConfigEvents.clear();
1600}
1601
Andy Hungdae27702016-10-31 14:01:16 -07001602template <typename T>
1603ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1604 ssize_t index = mActiveTracks.indexOf(track);
1605 if (index >= 0) {
1606 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1607 return index;
1608 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001609 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001610 mActiveTracksGeneration++;
1611 mLatestActiveTrack = track;
1612 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001613 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001614 return mActiveTracks.add(track);
1615}
1616
1617template <typename T>
1618ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1619 ssize_t index = mActiveTracks.remove(track);
1620 if (index < 0) {
1621 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1622 return index;
1623 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001624 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001625 mActiveTracksGeneration++;
1626 --mBatteryCounter[track->uid()].second;
1627 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001628 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001629#ifdef TEE_SINK
1630 track->dumpTee(-1 /* fd */, "_REMOVE");
1631#endif
Andy Hungdae27702016-10-31 14:01:16 -07001632 return index;
1633}
1634
1635template <typename T>
1636void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1637 for (const sp<T> &track : mActiveTracks) {
1638 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001639 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001640 }
1641 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001642 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001643 mActiveTracks.clear();
1644 mLatestActiveTrack.clear();
1645 mBatteryCounter.clear();
1646}
1647
1648template <typename T>
1649void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1650 sp<ThreadBase> thread, bool force) {
1651 // Updates ActiveTracks client uids to the thread wakelock.
1652 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1653 thread->updateWakeLockUids_l(getWakeLockUids());
1654 mLastActiveTracksGeneration = mActiveTracksGeneration;
1655 }
1656
1657 // Updates BatteryNotifier uids
1658 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1659 const uid_t uid = it->first;
1660 ssize_t &previous = it->second.first;
1661 ssize_t &current = it->second.second;
1662 if (current > 0) {
1663 if (previous == 0) {
1664 BatteryNotifier::getInstance().noteStartAudio(uid);
1665 }
1666 previous = current;
1667 ++it;
1668 } else if (current == 0) {
1669 if (previous > 0) {
1670 BatteryNotifier::getInstance().noteStopAudio(uid);
1671 }
1672 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1673 } else /* (current < 0) */ {
1674 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1675 }
1676 }
1677}
Eric Laurent83b88082014-06-20 18:31:16 -07001678
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001679template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001680bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1681 const bool hasChanged = mHasChanged;
1682 mHasChanged = false;
1683 return hasChanged;
1684}
1685
1686template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001687void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1688 const char *funcName, const sp<T> &track) const {
1689 if (mLocalLog != nullptr) {
1690 String8 result;
1691 track->appendDump(result, false /* active */);
1692 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1693 }
1694}
1695
Eric Laurent6acd1d42017-01-04 14:23:29 -08001696void AudioFlinger::ThreadBase::broadcast_l()
1697{
1698 // Thread could be blocked waiting for async
1699 // so signal it to handle state changes immediately
1700 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1701 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1702 mSignalPending = true;
1703 mWaitWorkCV.broadcast();
1704}
1705
Andy Hungd0979812019-02-21 15:51:44 -08001706// Call only from threadLoop() or when it is idle.
1707// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1708void AudioFlinger::ThreadBase::sendStatistics(bool force)
1709{
1710 // Do not log if we have no stats.
1711 // We choose the timestamp verifier because it is the most likely item to be present.
1712 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1713 if (nstats == 0) {
1714 return;
1715 }
1716
1717 // Don't log more frequently than once per 12 hours.
1718 // We use BOOTTIME to include suspend time.
1719 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1720 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1721 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1722 return;
1723 }
1724
1725 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1726 mLastRecordedTimeNs = timeNs;
1727
1728 std::unique_ptr<MediaAnalyticsItem> item(MediaAnalyticsItem::create("audiothread"));
1729
1730#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1731
1732 // thread configuration
1733 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1734 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1735 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1736 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1737 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1738 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1739 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001740 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1741 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001742
1743 // thread statistics
1744 if (mIoJitterMs.getN() > 0) {
1745 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1746 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1747 }
1748 if (mProcessTimeMs.getN() > 0) {
1749 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1750 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1751 }
1752 const auto tsjitter = mTimestampVerifier.getJitterMs();
1753 if (tsjitter.getN() > 0) {
1754 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1755 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1756 }
1757 if (mLatencyMs.getN() > 0) {
1758 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1759 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1760 }
1761
1762 item->selfrecord();
1763}
1764
Eric Laurent81784c32012-11-19 14:55:58 -08001765// ----------------------------------------------------------------------------
1766// Playback
1767// ----------------------------------------------------------------------------
1768
1769AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1770 AudioStreamOut* output,
1771 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001772 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001773 bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07001774 : ThreadBase(audioFlinger, id, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001775 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001776 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001777 mMixerBuffer(NULL),
1778 mMixerBufferSize(0),
1779 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1780 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001781 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001782 mEffectBuffer(NULL),
1783 mEffectBufferSize(0),
1784 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1785 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001786 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001787 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001788 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001789 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001790 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001791 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001792 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001793 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001794 mMixerStatus(MIXER_IDLE),
1795 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001796 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001797 mBytesRemaining(0),
1798 mCurrentWriteLength(0),
1799 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001800 mWriteAckSequence(0),
1801 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001802 mScreenState(AudioFlinger::mScreenState),
1803 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001804 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001805 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1806 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001807{
Glenn Kastend7dca052015-03-05 16:05:54 -08001808 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1809 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001810
1811 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1812 // it would be safer to explicitly pass initial masterVolume/masterMute as
1813 // parameter.
1814 //
1815 // If the HAL we are using has support for master volume or master mute,
1816 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1817 // and the mute set to false).
1818 mMasterVolume = audioFlinger->masterVolume_l();
1819 mMasterMute = audioFlinger->masterMute_l();
1820 if (mOutput && mOutput->audioHwDev) {
1821 if (mOutput->audioHwDev->canSetMasterVolume()) {
1822 mMasterVolume = 1.0;
1823 }
1824
1825 if (mOutput->audioHwDev->canSetMasterMute()) {
1826 mMasterMute = false;
1827 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001828 mIsMsdDevice = strcmp(
1829 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001830 }
1831
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001832 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001833
Andy Hungc8fddf32018-08-08 18:32:37 -07001834 // TODO: We may also match on address as well as device type for
1835 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11001836 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07001837 // TODO: This property should be ensure that only contains one single device type.
1838 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
1839 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07001840 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1841 : AUDIO_DEVICE_NONE));
1842 }
1843
Eric Laurent223fd5c2014-11-11 13:43:36 -08001844 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001845 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001846 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001847 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001848 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1849 }
Eric Laurent98e38192018-02-15 18:31:53 -08001850 // Audio patch volume is always max
1851 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1852 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001853}
1854
1855AudioFlinger::PlaybackThread::~PlaybackThread()
1856{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001857 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001858 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001859 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001860 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001861}
1862
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001863// Thread virtuals
1864
1865void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08001866{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001867 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001868}
1869
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001870// ThreadBase virtuals
1871void AudioFlinger::PlaybackThread::preExit()
1872{
1873 ALOGV(" preExit()");
1874 // FIXME this is using hard-coded strings but in the future, this functionality will be
1875 // converted to use audio HAL extensions required to support tunneling
1876 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1877 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
1878}
1879
1880void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001881{
Eric Laurent81784c32012-11-19 14:55:58 -08001882 String8 result;
1883
Marco Nelissenb2208842014-02-07 14:00:50 -08001884 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001885 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1886 const stream_type_t *st = &mStreamTypes[i];
1887 if (i > 0) {
1888 result.appendFormat(", ");
1889 }
1890 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1891 if (st->mute) {
1892 result.append("M");
1893 }
1894 }
1895 result.append("\n");
1896 write(fd, result.string(), result.length());
1897 result.clear();
1898
Eric Laurent81784c32012-11-19 14:55:58 -08001899 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1900 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001901 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001902 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001903
1904 size_t numtracks = mTracks.size();
1905 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001906 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001907 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001908 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001909 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001910 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001911 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001912 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001913 for (size_t i = 0; i < numtracks; ++i) {
1914 sp<Track> track = mTracks[i];
1915 if (track != 0) {
1916 bool active = mActiveTracks.indexOf(track) >= 0;
1917 if (active) {
1918 numactiveseen++;
1919 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001920 result.append(prefix);
1921 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001922 }
1923 }
1924 } else {
1925 result.append("\n");
1926 }
1927 if (numactiveseen != numactive) {
1928 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001929 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001930 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001931 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001932 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001933 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001934 sp<Track> track = mActiveTracks[i];
1935 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001936 result.append(prefix);
1937 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001938 }
1939 }
1940 }
1941
1942 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001943}
1944
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001945void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001946{
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07001947 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
jiabin245cdd92018-12-07 17:55:15 -08001948 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
1949 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
1950 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
1951 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001952 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001953 dprintf(fd, " Total writes: %d\n", mNumWrites);
1954 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1955 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1956 dprintf(fd, " Suspend count: %d\n", mSuspended);
1957 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1958 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1959 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1960 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001961 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001962 AudioStreamOut *output = mOutput;
1963 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001964 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08001965 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001966 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1967 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1968 if (mPipeSink.get() != nullptr) {
1969 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1970 }
1971 if (output != nullptr) {
1972 dprintf(fd, " Hal stream dump:\n");
1973 (void)output->stream->dump(fd);
1974 }
Eric Laurent81784c32012-11-19 14:55:58 -08001975}
1976
Eric Laurent81784c32012-11-19 14:55:58 -08001977// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1978sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1979 const sp<AudioFlinger::Client>& client,
1980 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001981 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08001982 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001983 audio_format_t format,
1984 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001985 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001986 size_t *pNotificationFrameCount,
1987 uint32_t notificationsPerBuffer,
1988 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001989 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001990 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001991 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07001992 pid_t creatorPid,
Eric Laurent81784c32012-11-19 14:55:58 -08001993 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001994 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001995 status_t *status,
1996 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001997{
Glenn Kasten74935e42013-12-19 08:56:45 -08001998 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001999 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002000 sp<Track> track;
2001 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002002 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002003 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002004 uint32_t sampleRate;
2005
2006 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2007 lStatus = BAD_VALUE;
2008 goto Exit;
2009 }
Eric Laurent21da6472017-11-09 16:29:26 -08002010
2011 if (*pSampleRate == 0) {
2012 *pSampleRate = mSampleRate;
2013 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002014 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002015
2016 // special case for FAST flag considered OK if fast mixer is present
2017 if (hasFastMixer()) {
2018 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2019 }
2020
2021 // Check if requested flags are compatible with output stream flags
2022 if ((*flags & outputFlags) != *flags) {
2023 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2024 *flags, outputFlags);
2025 *flags = (audio_output_flags_t)(*flags & outputFlags);
2026 }
Eric Laurent81784c32012-11-19 14:55:58 -08002027
Eric Laurent81784c32012-11-19 14:55:58 -08002028 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002029 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002030 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002031 // PCM data
2032 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002033 // TODO: extract as a data library function that checks that a computationally
2034 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002035 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002036 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2037 (channelMask == AUDIO_CHANNEL_OUT_MONO
2038 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002039 // hardware sample rate
2040 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002041 // normal mixer has an associated fast mixer
2042 hasFastMixer() &&
2043 // there are sufficient fast track slots available
2044 (mFastTrackAvailMask != 0)
2045 // FIXME test that MixerThread for this fast track has a capable output HAL
2046 // FIXME add a permission test also?
2047 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002048 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2049 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002050 // read the fast track multiplier property the first time it is needed
2051 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2052 if (ok != 0) {
2053 ALOGE("%s pthread_once failed: %d", __func__, ok);
2054 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002055 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002056 }
Eric Laurent4c415062016-06-17 16:14:16 -07002057
2058 // check compatibility with audio effects.
2059 { // scope for mLock
2060 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002061 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002062 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002063 AUDIO_SESSION_OUTPUT_STAGE,
2064 AUDIO_SESSION_OUTPUT_MIX,
2065 sessionId,
2066 }) {
2067 sp<EffectChain> chain = getEffectChain_l(session);
2068 if (chain.get() != nullptr) {
2069 audio_output_flags_t old = *flags;
2070 chain->checkOutputFlagCompatibility(flags);
2071 if (old != *flags) {
2072 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2073 (int)session, (int)old, (int)*flags);
2074 }
Eric Laurent4c415062016-06-17 16:14:16 -07002075 }
2076 }
2077 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002078 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002079 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2080 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002081 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002082 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2083 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002084 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002085 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002086 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08002087 audio_is_linear_pcm(format),
2088 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002089 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002090 }
2091 }
Eric Laurent21da6472017-11-09 16:29:26 -08002092
2093 if (!audio_has_proportional_frames(format)) {
2094 if (sharedBuffer != 0) {
2095 // Same comment as below about ignoring frameCount parameter for set()
2096 frameCount = sharedBuffer->size();
2097 } else if (frameCount == 0) {
2098 frameCount = mNormalFrameCount;
2099 }
2100 if (notificationFrameCount != frameCount) {
2101 notificationFrameCount = frameCount;
2102 }
2103 } else if (sharedBuffer != 0) {
2104 // FIXME: Ensure client side memory buffers need
2105 // not have additional alignment beyond sample
2106 // (e.g. 16 bit stereo accessed as 32 bit frame).
2107 size_t alignment = audio_bytes_per_sample(format);
2108 if (alignment & 1) {
2109 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2110 alignment = 1;
2111 }
2112 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2113 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2114 if (channelCount > 1) {
2115 // More than 2 channels does not require stronger alignment than stereo
2116 alignment <<= 1;
2117 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002118 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002119 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002120 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002121 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002122 goto Exit;
2123 }
Eric Laurent21da6472017-11-09 16:29:26 -08002124
2125 // When initializing a shared buffer AudioTrack via constructors,
2126 // there's no frameCount parameter.
2127 // But when initializing a shared buffer AudioTrack via set(),
2128 // there _is_ a frameCount parameter. We silently ignore it.
2129 frameCount = sharedBuffer->size() / frameSize;
2130 } else {
2131 size_t minFrameCount = 0;
2132 // For fast tracks we try to respect the application's request for notifications per buffer.
2133 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2134 if (notificationsPerBuffer > 0) {
2135 // Avoid possible arithmetic overflow during multiplication.
2136 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2137 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2138 notificationsPerBuffer, mFrameCount);
2139 } else {
2140 minFrameCount = mFrameCount * notificationsPerBuffer;
2141 }
2142 }
2143 } else {
2144 // For normal PCM streaming tracks, update minimum frame count.
2145 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2146 // cover audio hardware latency.
2147 // This is probably too conservative, but legacy application code may depend on it.
2148 // If you change this calculation, also review the start threshold which is related.
2149 uint32_t latencyMs = latency_l();
2150 if (latencyMs == 0) {
2151 ALOGE("Error when retrieving output stream latency");
2152 lStatus = UNKNOWN_ERROR;
2153 goto Exit;
2154 }
2155
2156 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2157 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2158
Eric Laurent81784c32012-11-19 14:55:58 -08002159 }
Eric Laurent21da6472017-11-09 16:29:26 -08002160 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002161 frameCount = minFrameCount;
2162 }
Eric Laurent81784c32012-11-19 14:55:58 -08002163 }
Eric Laurent21da6472017-11-09 16:29:26 -08002164
2165 // Make sure that application is notified with sufficient margin before underrun.
2166 // The client can divide the AudioTrack buffer into sub-buffers,
2167 // and expresses its desire to server as the notification frame count.
2168 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2169 size_t maxNotificationFrames;
2170 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2171 // notify every HAL buffer, regardless of the size of the track buffer
2172 maxNotificationFrames = mFrameCount;
2173 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002174 // Triple buffer the notification period for a triple buffered mixer period;
2175 // otherwise, double buffering for the notification period is fine.
2176 //
2177 // TODO: This should be moved to AudioTrack to modify the notification period
2178 // on AudioTrack::setBufferSizeInFrames() changes.
2179 const int nBuffering =
2180 (uint64_t{frameCount} * mSampleRate)
2181 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2182
Eric Laurent21da6472017-11-09 16:29:26 -08002183 maxNotificationFrames = frameCount / nBuffering;
2184 // If client requested a fast track but this was denied, then use the smaller maximum.
2185 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2186 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2187 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2188 maxNotificationFrames = maxNotificationFramesFastDenied;
2189 }
2190 }
2191 }
2192 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2193 if (notificationFrameCount == 0) {
2194 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2195 maxNotificationFrames, frameCount);
2196 } else {
2197 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2198 notificationFrameCount, maxNotificationFrames, frameCount);
2199 }
2200 notificationFrameCount = maxNotificationFrames;
2201 }
2202 }
2203
Glenn Kasten74935e42013-12-19 08:56:45 -08002204 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002205 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002206
Glenn Kastenc3df8382014-03-13 15:05:25 -07002207 switch (mType) {
2208
2209 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002210 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002211 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002212 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2213 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002214 sampleRate, format, channelMask, mOutput, mFormat);
2215 lStatus = BAD_VALUE;
2216 goto Exit;
2217 }
2218 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002219 break;
2220
2221 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002222 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002223 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2224 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002225 sampleRate, format, channelMask, mOutput, mFormat);
2226 lStatus = BAD_VALUE;
2227 goto Exit;
2228 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002229 break;
2230
2231 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002232 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002233 ALOGE("createTrack_l() Bad parameter: format %#x \""
2234 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002235 format, mOutput, mFormat);
2236 lStatus = BAD_VALUE;
2237 goto Exit;
2238 }
Andy Hungcd044842014-08-07 11:04:34 -07002239 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002240 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2241 lStatus = BAD_VALUE;
2242 goto Exit;
2243 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002244 break;
2245
Eric Laurent81784c32012-11-19 14:55:58 -08002246 }
2247
2248 lStatus = initCheck();
2249 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002250 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002251 goto Exit;
2252 }
2253
2254 { // scope for mLock
2255 Mutex::Autolock _l(mLock);
2256
2257 // all tracks in same audio session must share the same routing strategy otherwise
2258 // conflicts will happen when tracks are moved from one output to another by audio policy
2259 // manager
2260 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2261 for (size_t i = 0; i < mTracks.size(); ++i) {
2262 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002263 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002264 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2265 if (sessionId == t->sessionId() && strategy != actual) {
2266 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2267 strategy, actual);
2268 lStatus = BAD_VALUE;
2269 goto Exit;
2270 }
2271 }
2272 }
2273
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002274 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002275 channelMask, frameCount,
2276 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002277 sessionId, creatorPid, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002278
Glenn Kasten03003332013-08-06 15:40:54 -07002279 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2280 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002281 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002282 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002283 goto Exit;
2284 }
2285 mTracks.add(track);
2286
2287 sp<EffectChain> chain = getEffectChain_l(sessionId);
2288 if (chain != 0) {
2289 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2290 track->setMainBuffer(chain->inBuffer());
2291 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2292 chain->incTrackCnt();
2293 }
2294
Eric Laurent05067782016-06-01 18:27:28 -07002295 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002296 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2297 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2298 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002299 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002300 }
2301 }
2302
2303 lStatus = NO_ERROR;
2304
2305Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002306 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002307 return track;
2308}
2309
Andy Hung1bc088a2018-02-09 15:57:31 -08002310template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002311ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2312{
Andy Hungc0691382018-09-12 18:01:57 -07002313 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002314 const ssize_t index = mTracks.remove(track);
2315 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002316 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002317 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002318 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002319 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002320 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002321 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002322 }
2323 return index;
2324}
2325
Eric Laurent81784c32012-11-19 14:55:58 -08002326uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2327{
2328 return latency;
2329}
2330
2331uint32_t AudioFlinger::PlaybackThread::latency() const
2332{
2333 Mutex::Autolock _l(mLock);
2334 return latency_l();
2335}
2336uint32_t AudioFlinger::PlaybackThread::latency_l() const
2337{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002338 uint32_t latency;
2339 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2340 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002341 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002342 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002343}
2344
2345void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2346{
2347 Mutex::Autolock _l(mLock);
2348 // Don't apply master volume in SW if our HAL can do it for us.
2349 if (mOutput && mOutput->audioHwDev &&
2350 mOutput->audioHwDev->canSetMasterVolume()) {
2351 mMasterVolume = 1.0;
2352 } else {
2353 mMasterVolume = value;
2354 }
2355}
2356
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002357void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2358{
2359 mMasterBalance.store(balance);
2360}
2361
Eric Laurent81784c32012-11-19 14:55:58 -08002362void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2363{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002364 if (isDuplicating()) {
2365 return;
2366 }
Eric Laurent81784c32012-11-19 14:55:58 -08002367 Mutex::Autolock _l(mLock);
2368 // Don't apply master mute in SW if our HAL can do it for us.
2369 if (mOutput && mOutput->audioHwDev &&
2370 mOutput->audioHwDev->canSetMasterMute()) {
2371 mMasterMute = false;
2372 } else {
2373 mMasterMute = muted;
2374 }
2375}
2376
2377void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2378{
2379 Mutex::Autolock _l(mLock);
2380 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002381 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002382}
2383
2384void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2385{
2386 Mutex::Autolock _l(mLock);
2387 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002388 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002389}
2390
2391float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2392{
2393 Mutex::Autolock _l(mLock);
2394 return mStreamTypes[stream].volume;
2395}
2396
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002397void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2398{
2399 mOutput->stream->setVolume(left, right);
2400}
2401
Eric Laurent81784c32012-11-19 14:55:58 -08002402// addTrack_l() must be called with ThreadBase::mLock held
2403status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2404{
2405 status_t status = ALREADY_EXISTS;
2406
Eric Laurent81784c32012-11-19 14:55:58 -08002407 if (mActiveTracks.indexOf(track) < 0) {
2408 // the track is newly added, make sure it fills up all its
2409 // buffers before playing. This is to ensure the client will
2410 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002411 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002412 TrackBase::track_state state = track->mState;
2413 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002414 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002415 mLock.lock();
2416 // abort track was stopped/paused while we released the lock
2417 if (state != track->mState) {
2418 if (status == NO_ERROR) {
2419 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002420 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002421 mLock.lock();
2422 }
2423 return INVALID_OPERATION;
2424 }
2425 // abort if start is rejected by audio policy manager
2426 if (status != NO_ERROR) {
2427 return PERMISSION_DENIED;
2428 }
2429#ifdef ADD_BATTERY_DATA
2430 // to track the speaker usage
2431 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2432#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002433 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002434 }
2435
Eric Laurent51716182016-02-29 18:00:56 -08002436 // set retry count for buffer fill
2437 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002438 if (track->isStopping_1()) {
2439 track->mRetryCount = kMaxTrackStopRetriesOffload;
2440 } else {
2441 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2442 }
2443 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002444 } else {
2445 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002446 track->mFillingUpStatus =
2447 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002448 }
2449
jiabin245cdd92018-12-07 17:55:15 -08002450 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2451 && mHapticChannelMask != AUDIO_CHANNEL_NONE) {
jiabin57303cc2018-12-18 15:45:57 -08002452 // Unlock due to VibratorService will lock for this call and will
2453 // call Tracks.mute/unmute which also require thread's lock.
2454 mLock.unlock();
2455 const int intensity = AudioFlinger::onExternalVibrationStart(
2456 track->getExternalVibration());
2457 mLock.lock();
jiabinbf6b0ec2019-02-12 12:30:12 -08002458 track->setHapticIntensity(static_cast<AudioMixer::haptic_intensity_t>(intensity));
jiabin57303cc2018-12-18 15:45:57 -08002459 // Haptic playback should be enabled by vibrator service.
2460 if (track->getHapticPlaybackEnabled()) {
2461 // Disable haptic playback of all active track to ensure only
2462 // one track playing haptic if current track should play haptic.
2463 for (const auto &t : mActiveTracks) {
2464 t->setHapticPlaybackEnabled(false);
2465 }
jiabin245cdd92018-12-07 17:55:15 -08002466 }
jiabin245cdd92018-12-07 17:55:15 -08002467 }
2468
Eric Laurent81784c32012-11-19 14:55:58 -08002469 track->mResetDone = false;
2470 track->mPresentationCompleteFrames = 0;
2471 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002472 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2473 if (chain != 0) {
2474 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2475 track->sessionId());
2476 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002477 }
2478
2479 status = NO_ERROR;
2480 }
2481
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002482 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002483 return status;
2484}
2485
Eric Laurentbfb1b832013-01-07 09:53:42 -08002486bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002487{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002488 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002489 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002490 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2491 track->mState = TrackBase::STOPPED;
2492 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002493 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002494 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002495 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002496 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002497
2498 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002499}
2500
2501void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2502{
2503 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002504
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002505 String8 result;
2506 track->appendDump(result, false /* active */);
2507 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002508
Eric Laurent81784c32012-11-19 14:55:58 -08002509 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002510 if (track->isFastTrack()) {
2511 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002512 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002513 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2514 mFastTrackAvailMask |= 1 << index;
2515 // redundant as track is about to be destroyed, for dumpsys only
2516 track->mFastIndex = -1;
2517 }
2518 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2519 if (chain != 0) {
2520 chain->decTrackCnt();
2521 }
2522}
2523
2524String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2525{
Eric Laurent81784c32012-11-19 14:55:58 -08002526 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002527 String8 out_s8;
2528 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2529 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002530 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002531 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002532}
2533
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002534status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2535 Mutex::Autolock _l(mLock);
2536 if (mOutput == nullptr || mOutput->stream == nullptr) {
2537 return NO_INIT;
2538 }
2539 return mOutput->stream->selectPresentation(presentationId, programId);
2540}
2541
Eric Laurent09f1ed22019-04-24 17:45:17 -07002542void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
2543 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002544 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2545 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002546
Eric Laurent73e26b62015-04-27 16:55:58 -07002547 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002548
2549 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002550 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002551 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002552 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002553 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002554 desc->mChannelMask = mChannelMask;
2555 desc->mSamplingRate = mSampleRate;
2556 desc->mFormat = mFormat;
2557 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002558 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002559 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002560 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002561 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002562 case AUDIO_CLIENT_STARTED:
2563 desc->mPatch = mPatch;
2564 desc->mPortId = portId;
2565 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002566 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002567 default:
2568 break;
2569 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002570 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002571}
2572
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002573void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002574{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002575 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002576}
2577
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002578void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002579{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002580 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002581}
2582
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002583void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002584{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002585 mCallbackThread->setAsyncError();
2586}
2587
Eric Laurent3b4529e2013-09-05 18:09:19 -07002588void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002589{
2590 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002591 // reject out of sequence requests
2592 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2593 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002594 mWaitWorkCV.signal();
2595 }
2596}
2597
Eric Laurent3b4529e2013-09-05 18:09:19 -07002598void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002599{
2600 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002601 // reject out of sequence requests
2602 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002603 // Register discontinuity when HW drain is completed because that can cause
2604 // the timestamp frame position to reset to 0 for direct and offload threads.
2605 // (Out of sequence requests are ignored, since the discontinuity would be handled
2606 // elsewhere, e.g. in flush).
2607 mTimestampVerifier.discontinuity();
Eric Laurent3b4529e2013-09-05 18:09:19 -07002608 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002609 mWaitWorkCV.signal();
2610 }
2611}
2612
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002613void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002614{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002615 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002616 mSampleRate = mOutput->getSampleRate();
2617 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002618 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002619 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002620 }
Andy Hung9a592762014-07-21 21:56:01 -07002621 if ((mType == MIXER || mType == DUPLICATING)
2622 && !isValidPcmSinkChannelMask(mChannelMask)) {
2623 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2624 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002625 }
Andy Hunge5412692014-05-16 11:25:07 -07002626 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002627 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002628
2629 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002630 status_t result = mOutput->stream->getFormat(&mHALFormat);
2631 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002632 // Get format from the shim, which will be different than the HAL format
2633 // if playing compressed audio over HDMI passthrough.
2634 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002635 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002636 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002637 }
Andy Hung6146c082014-03-18 11:56:15 -07002638 if ((mType == MIXER || mType == DUPLICATING)
2639 && !isValidPcmSinkFormat(mFormat)) {
2640 LOG_FATAL("HAL format %#x not supported for mixed output",
2641 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002642 }
Phil Burk062e67a2015-02-11 13:40:50 -08002643 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002644 result = mOutput->stream->getBufferSize(&mBufferSize);
2645 LOG_ALWAYS_FATAL_IF(result != OK,
2646 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002647 mFrameCount = mBufferSize / mFrameSize;
Dean Wheatley77cbebd2019-04-23 14:18:44 +10002648 if ((mType == MIXER || mType == DUPLICATING) && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002649 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002650 mFrameCount);
2651 }
2652
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002653 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2654 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002655 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002656 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002657 }
2658 }
2659
Eric Laurentd1f69b02014-12-15 14:33:13 -08002660 mHwSupportsPause = false;
2661 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002662 bool supportsPause = false, supportsResume = false;
2663 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2664 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002665 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002666 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002667 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002668 } else if (supportsResume) {
2669 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002670 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002671 }
2672 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002673 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2674 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2675 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002676
Andy Hungfbfc3952015-01-15 13:33:51 -08002677 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2678 // For best precision, we use float instead of the associated output
2679 // device format (typically PCM 16 bit).
2680
2681 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2682 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2683 mBufferSize = mFrameSize * mFrameCount;
2684
2685 // TODO: We currently use the associated output device channel mask and sample rate.
2686 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2687 // (if a valid mask) to avoid premature downmix.
2688 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2689 // instead of the output device sample rate to avoid loss of high frequency information.
2690 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2691 }
2692
Andy Hung09a50072014-02-27 14:30:47 -08002693 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002694 double multiplier = 1.0;
2695 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2696 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002697 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2698 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002699
Eric Laurent81784c32012-11-19 14:55:58 -08002700 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2701 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2702 maxNormalFrameCount = maxNormalFrameCount & ~15;
2703 if (maxNormalFrameCount < minNormalFrameCount) {
2704 maxNormalFrameCount = minNormalFrameCount;
2705 }
2706 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2707 if (multiplier <= 1.0) {
2708 multiplier = 1.0;
2709 } else if (multiplier <= 2.0) {
2710 if (2 * mFrameCount <= maxNormalFrameCount) {
2711 multiplier = 2.0;
2712 } else {
2713 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2714 }
2715 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002716 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002717 }
2718 }
2719 mNormalFrameCount = multiplier * mFrameCount;
2720 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002721 if (mType == MIXER || mType == DUPLICATING) {
2722 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2723 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002724 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002725 mNormalFrameCount);
2726
Andy Hung08fb1742015-05-31 23:22:10 -07002727 // Check if we want to throttle the processing to no more than 2x normal rate
2728 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002729 mThreadThrottleTimeMs = 0;
2730 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002731 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2732
Andy Hung010a1a12014-03-13 13:57:33 -07002733 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2734 // Originally this was int16_t[] array, need to remove legacy implications.
2735 free(mSinkBuffer);
2736 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002737 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2738 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2739 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002740 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002741
Andy Hung69aed5f2014-02-25 17:24:40 -08002742 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2743 // drives the output.
2744 free(mMixerBuffer);
2745 mMixerBuffer = NULL;
2746 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002747 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Andy Hung69aed5f2014-02-25 17:24:40 -08002748 mMixerBufferSize = mNormalFrameCount * mChannelCount
2749 * audio_bytes_per_sample(mMixerBufferFormat);
2750 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2751 }
Andy Hung98ef9782014-03-04 14:46:50 -08002752 free(mEffectBuffer);
2753 mEffectBuffer = NULL;
2754 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002755 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002756 mEffectBufferSize = mNormalFrameCount * mChannelCount
2757 * audio_bytes_per_sample(mEffectBufferFormat);
2758 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2759 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002760
jiabin245cdd92018-12-07 17:55:15 -08002761 mHapticChannelMask = mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL;
2762 mChannelMask &= ~mHapticChannelMask;
2763 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2764 mChannelCount -= mHapticChannelCount;
2765
Eric Laurent81784c32012-11-19 14:55:58 -08002766 // force reconfiguration of effect chains and engines to take new buffer size and audio
2767 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002768 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002769 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2770 // matter.
2771 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2772 Vector< sp<EffectChain> > effectChains = mEffectChains;
2773 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07002774 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
2775 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08002776 }
2777}
2778
Kevin Rocard069c2712018-03-29 19:09:14 -07002779void AudioFlinger::PlaybackThread::updateMetadata_l()
2780{
Kevin Rocard12381092018-04-11 09:19:59 -07002781 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2782 return; // That should not happen
2783 }
2784 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2785 for (const sp<Track> &track : mActiveTracks) {
2786 // Do not short-circuit as all hasChanged states must be reset
2787 // as all the metadata are going to be sent
2788 hasChanged |= track->readAndClearHasChanged();
2789 }
2790 if (!hasChanged) {
2791 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002792 }
2793 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002794 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002795 for (const sp<Track> &track : mActiveTracks) {
2796 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002797 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002798 }
Kevin Rocard12381092018-04-11 09:19:59 -07002799 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002800}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002801
Kevin Rocard12381092018-04-11 09:19:59 -07002802void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2803 const StreamOutHalInterface::SourceMetadata& metadata)
2804{
2805 mOutput->stream->updateSourceMetadata(metadata);
2806};
2807
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002808status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002809{
2810 if (halFrames == NULL || dspFrames == NULL) {
2811 return BAD_VALUE;
2812 }
2813 Mutex::Autolock _l(mLock);
2814 if (initCheck() != NO_ERROR) {
2815 return INVALID_OPERATION;
2816 }
Andy Hung818e7a32016-02-16 18:08:07 -08002817 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002818 *halFrames = framesWritten;
2819
2820 if (isSuspended()) {
2821 // return an estimation of rendered frames when the output is suspended
2822 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002823 *dspFrames = (uint32_t)
2824 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002825 return NO_ERROR;
2826 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002827 status_t status;
2828 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002829 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002830 *dspFrames = (size_t)frames;
2831 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002832 }
2833}
2834
Glenn Kastend848eb42016-03-08 13:42:11 -08002835uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002836{
2837 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2838 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2839 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2840 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2841 }
2842 for (size_t i = 0; i < mTracks.size(); i++) {
2843 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002844 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002845 return AudioSystem::getStrategyForStream(track->streamType());
2846 }
2847 }
2848 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2849}
2850
2851
Phil Burk062e67a2015-02-11 13:40:50 -08002852AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002853{
2854 Mutex::Autolock _l(mLock);
2855 return mOutput;
2856}
2857
Phil Burk062e67a2015-02-11 13:40:50 -08002858AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002859{
2860 Mutex::Autolock _l(mLock);
2861 AudioStreamOut *output = mOutput;
2862 mOutput = NULL;
2863 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2864 // must push a NULL and wait for ack
2865 mOutputSink.clear();
2866 mPipeSink.clear();
2867 mNormalSink.clear();
2868 return output;
2869}
2870
2871// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002872sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002873{
2874 if (mOutput == NULL) {
2875 return NULL;
2876 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002877 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002878}
2879
2880uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2881{
2882 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2883}
2884
2885status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2886{
2887 if (!isValidSyncEvent(event)) {
2888 return BAD_VALUE;
2889 }
2890
2891 Mutex::Autolock _l(mLock);
2892
2893 for (size_t i = 0; i < mTracks.size(); ++i) {
2894 sp<Track> track = mTracks[i];
2895 if (event->triggerSession() == track->sessionId()) {
2896 (void) track->setSyncEvent(event);
2897 return NO_ERROR;
2898 }
2899 }
2900
2901 return NAME_NOT_FOUND;
2902}
2903
2904bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2905{
2906 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2907}
2908
2909void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2910 const Vector< sp<Track> >& tracksToRemove)
2911{
Andy Hungfe726a62018-09-27 15:17:25 -07002912 // Miscellaneous track cleanup when removed from the active list,
2913 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002914#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07002915 for (const auto& track : tracksToRemove) {
2916 if (track->isExternalTrack()) {
2917 // to track the speaker usage
2918 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08002919 }
2920 }
Andy Hungfe726a62018-09-27 15:17:25 -07002921#else
2922 (void)tracksToRemove; // suppress unused warning
2923#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002924}
2925
2926void AudioFlinger::PlaybackThread::checkSilentMode_l()
2927{
2928 if (!mMasterMute) {
2929 char value[PROPERTY_VALUE_MAX];
jiabinc52b1ff2019-10-31 17:20:42 -07002930 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002931 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2932 return;
2933 }
Eric Laurent81784c32012-11-19 14:55:58 -08002934 if (property_get("ro.audio.silent", value, "0") > 0) {
2935 char *endptr;
2936 unsigned long ul = strtoul(value, &endptr, 0);
2937 if (*endptr == '\0' && ul != 0) {
2938 ALOGD("Silence is golden");
2939 // The setprop command will not allow a property to be changed after
2940 // the first time it is set, so we don't have to worry about un-muting.
2941 setMasterMute_l(true);
2942 }
2943 }
2944 }
2945}
2946
2947// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002948ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002949{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002950 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002951 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002952 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002953 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002954
2955 // If an NBAIO sink is present, use it to write the normal mixer's submix
2956 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002957
Andy Hung010a1a12014-03-13 13:57:33 -07002958 const size_t count = mBytesRemaining / mFrameSize;
2959
Simon Wilson2d590962012-11-29 15:18:50 -08002960 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002961 // update the setpoint when AudioFlinger::mScreenState changes
2962 uint32_t screenState = AudioFlinger::mScreenState;
2963 if (screenState != mScreenState) {
2964 mScreenState = screenState;
2965 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2966 if (pipe != NULL) {
2967 pipe->setAvgFrames((mScreenState & 1) ?
2968 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2969 }
2970 }
Andy Hung010a1a12014-03-13 13:57:33 -07002971 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002972 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002973 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002974 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07002975#ifdef TEE_SINK
2976 mTee.write((char *)mSinkBuffer + offset, framesWritten);
2977#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002978 } else {
2979 bytesWritten = framesWritten;
2980 }
2981 // otherwise use the HAL / AudioStreamOut directly
2982 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002983 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002984
Eric Laurentbfb1b832013-01-07 09:53:42 -08002985 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002986 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2987 mWriteAckSequence += 2;
2988 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002989 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002990 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002991 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07002992 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07002993 // FIXME We should have an implementation of timestamps for direct output threads.
2994 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002995 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07002996 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08002997
Eric Laurentbfb1b832013-01-07 09:53:42 -08002998 if (mUseAsyncWrite &&
2999 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3000 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003001 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003002 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003003 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003004 }
Eric Laurent81784c32012-11-19 14:55:58 -08003005 }
3006
Eric Laurent81784c32012-11-19 14:55:58 -08003007 mNumWrites++;
3008 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07003009 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003010 return bytesWritten;
3011}
3012
3013void AudioFlinger::PlaybackThread::threadLoop_drain()
3014{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003015 bool supportsDrain = false;
3016 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003017 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3018 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003019 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3020 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003021 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003022 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003023 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003024 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003025 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003026 }
3027}
3028
3029void AudioFlinger::PlaybackThread::threadLoop_exit()
3030{
Eric Laurent275e8e92014-11-30 15:14:47 -08003031 {
3032 Mutex::Autolock _l(mLock);
3033 for (size_t i = 0; i < mTracks.size(); i++) {
3034 sp<Track> track = mTracks[i];
3035 track->invalidate();
3036 }
Andy Hungdae27702016-10-31 14:01:16 -07003037 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3038 // After we exit there are no more track changes sent to BatteryNotifier
3039 // because that requires an active threadLoop.
3040 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3041 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003042 }
Eric Laurent81784c32012-11-19 14:55:58 -08003043}
3044
3045/*
3046The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003047 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003048 - mActiveSleepTimeUs from activeSleepTimeUs()
3049 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003050 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3051 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003052 - maxPeriod from frame count and sample rate (MIXER only)
3053
3054The parameters that affect these derived values are:
3055 - frame count
3056 - frame size
3057 - sample rate
3058 - device type: A2DP or not
3059 - device latency
3060 - format: PCM or not
3061 - active sleep time
3062 - idle sleep time
3063*/
3064
3065void AudioFlinger::PlaybackThread::cacheParameters_l()
3066{
Andy Hung25c2dac2014-02-27 14:56:00 -08003067 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003068 mActiveSleepTimeUs = activeSleepTimeUs();
3069 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003070
3071 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3072 // truncating audio when going to standby.
3073 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003074 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003075 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3076 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3077 }
3078 }
Eric Laurent81784c32012-11-19 14:55:58 -08003079}
3080
Eric Laurent13084622016-05-17 10:51:49 -07003081bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003082{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003083 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003084 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003085 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003086 size_t size = mTracks.size();
3087 for (size_t i = 0; i < size; i++) {
3088 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003089 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003090 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003091 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003092 }
3093 }
Eric Laurent13084622016-05-17 10:51:49 -07003094 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003095}
3096
Haynes Mathew George05317d22016-05-03 16:34:26 -07003097void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3098{
3099 Mutex::Autolock _l(mLock);
3100 invalidateTracks_l(streamType);
3101}
3102
Eric Laurent81784c32012-11-19 14:55:58 -08003103status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3104{
Glenn Kastend848eb42016-03-08 13:42:11 -08003105 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003106 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003107 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003108 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3109 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3110 &halInBuffer);
3111 if (result != OK) return result;
3112 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003113 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003114 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003115 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003116 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003117 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003118 if (mType != DIRECT) {
jiabin245cdd92018-12-07 17:55:15 -08003119 size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003120 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003121 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003122 &halInBuffer);
3123 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003124#ifdef FLOAT_EFFECT_CHAIN
3125 buffer = halInBuffer->audioBuffer()->f32;
3126#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003127 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003128#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003129 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3130 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003131 }
3132
3133 // Attach all tracks with same session ID to this chain.
3134 for (size_t i = 0; i < mTracks.size(); ++i) {
3135 sp<Track> track = mTracks[i];
3136 if (session == track->sessionId()) {
3137 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3138 buffer);
3139 track->setMainBuffer(buffer);
3140 chain->incTrackCnt();
3141 }
3142 }
3143
3144 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003145 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003146 if (session == track->sessionId()) {
3147 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3148 chain->incActiveTrackCnt();
3149 }
3150 }
3151 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003152 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003153 chain->setInBuffer(halInBuffer);
3154 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003155 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3156 // chains list in order to be processed last as it contains output device effects.
3157 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3158 // processing effects specific to an output stream before effects applied to all streams
3159 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003160 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3161 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003162 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003163 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003164 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003165 // Effect chain for other sessions are inserted at beginning of effect
3166 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003167 // sessions is not important.
3168 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003169 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3170 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003171 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003172 size_t size = mEffectChains.size();
3173 size_t i = 0;
3174 for (i = 0; i < size; i++) {
3175 if (mEffectChains[i]->sessionId() < session) {
3176 break;
3177 }
3178 }
3179 mEffectChains.insertAt(chain, i);
3180 checkSuspendOnAddEffectChain_l(chain);
3181
3182 return NO_ERROR;
3183}
3184
3185size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3186{
Glenn Kastend848eb42016-03-08 13:42:11 -08003187 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003188
3189 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3190
3191 for (size_t i = 0; i < mEffectChains.size(); i++) {
3192 if (chain == mEffectChains[i]) {
3193 mEffectChains.removeAt(i);
3194 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003195 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003196 if (session == track->sessionId()) {
3197 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3198 chain.get(), session);
3199 chain->decActiveTrackCnt();
3200 }
3201 }
3202
3203 // detach all tracks with same session ID from this chain
3204 for (size_t i = 0; i < mTracks.size(); ++i) {
3205 sp<Track> track = mTracks[i];
3206 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003207 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003208 chain->decTrackCnt();
3209 }
3210 }
3211 break;
3212 }
3213 }
3214 return mEffectChains.size();
3215}
3216
3217status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003218 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003219{
3220 Mutex::Autolock _l(mLock);
3221 return attachAuxEffect_l(track, EffectId);
3222}
3223
3224status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003225 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003226{
3227 status_t status = NO_ERROR;
3228
3229 if (EffectId == 0) {
3230 track->setAuxBuffer(0, NULL);
3231 } else {
3232 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3233 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3234 if (effect != 0) {
3235 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3236 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3237 } else {
3238 status = INVALID_OPERATION;
3239 }
3240 } else {
3241 status = BAD_VALUE;
3242 }
3243 }
3244 return status;
3245}
3246
3247void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3248{
3249 for (size_t i = 0; i < mTracks.size(); ++i) {
3250 sp<Track> track = mTracks[i];
3251 if (track->auxEffectId() == effectId) {
3252 attachAuxEffect_l(track, 0);
3253 }
3254 }
3255}
3256
3257bool AudioFlinger::PlaybackThread::threadLoop()
3258{
Glenn Kasten388d5712017-04-07 14:38:41 -07003259 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003260
Eric Laurent81784c32012-11-19 14:55:58 -08003261 Vector< sp<Track> > tracksToRemove;
3262
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003263 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003264 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
3265 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003266
3267 // MIXER
3268 nsecs_t lastWarning = 0;
3269
3270 // DUPLICATING
3271 // FIXME could this be made local to while loop?
3272 writeFrames = 0;
3273
3274 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003275 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003276
3277 if (mType == MIXER) {
3278 sleepTimeShift = 0;
3279 }
3280
3281 CpuStats cpuStats;
3282 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3283
3284 acquireWakeLock();
3285
Glenn Kasteneef598c2017-04-03 14:41:13 -07003286 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3287 // thread associated with this PlaybackThread.
3288 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3289 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003290 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3291 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003292 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003293 const char *logString = NULL;
3294
rago1bb90822017-05-02 18:31:48 -07003295 // Estimated time for next buffer to be written to hal. This is used only on
3296 // suspended mode (for now) to help schedule the wait time until next iteration.
3297 nsecs_t timeLoopNextNs = 0;
3298
Eric Laurent664539d2013-09-23 18:24:31 -07003299 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003300
Andy Hungf3234512018-07-03 14:51:47 -07003301 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
3302 // TODO: add confirmation checks:
3303 // 1) DIRECT threads and linear PCM format really resets to 0?
3304 // 2) Is frame count really valid if not linear pcm?
3305 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
3306 if (mType == OFFLOAD || mType == DIRECT) {
3307 mTimestampVerifier.setDiscontinuityMode(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
3308 }
Andy Hung2dbffc22018-08-08 18:50:41 -07003309 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003310
Andy Hung446f4df2019-02-21 12:26:41 -08003311 // loopCount is used for statistics and diagnostics.
3312 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003313 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003314 // Log merge requests are performed during AudioFlinger binder transactions, but
3315 // that does not cover audio playback. It's requested here for that reason.
3316 mAudioFlinger->requestLogMerge();
3317
Eric Laurent81784c32012-11-19 14:55:58 -08003318 cpuStats.sample(myName);
3319
3320 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003321 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003322 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003323
Andy Hung2dbffc22018-08-08 18:50:41 -07003324 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3325 //
jiabinc52b1ff2019-10-31 17:20:42 -07003326 // Note: we access outDeviceTypes() outside of mLock.
3327 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003328 // Here, we try for the AF lock, but do not block on it as the latency
3329 // is more informational.
3330 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3331 std::vector<PatchPanel::SoftwarePatch> swPatches;
3332 double latencyMs;
3333 status_t status = INVALID_OPERATION;
3334 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3335 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3336 && swPatches.size() > 0) {
3337 status = swPatches[0].getLatencyMs_l(&latencyMs);
3338 downstreamPatchHandle = swPatches[0].getPatchHandle();
3339 }
3340 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003341 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003342 lastDownstreamPatchHandle = downstreamPatchHandle;
3343 }
3344 if (status == OK) {
3345 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003346 // latency of 5 seconds).
3347 const double minLatency = 0., maxLatency = 5000.;
3348 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003349 ALOGV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003350 } else {
3351 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003352 if (latencyMs < minLatency) latencyMs = minLatency;
3353 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003354 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003355 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003356 }
3357 mAudioFlinger->mLock.unlock();
3358 }
3359 } else {
3360 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3361 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003362 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003363 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3364 }
3365 }
3366
Eric Laurent81784c32012-11-19 14:55:58 -08003367 { // scope for mLock
3368
3369 Mutex::Autolock _l(mLock);
3370
Eric Laurent021cf962014-05-13 10:18:14 -07003371 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003372
Glenn Kasteneef598c2017-04-03 14:41:13 -07003373 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003374 if (logString != NULL) {
3375 mNBLogWriter->logTimestamp();
3376 mNBLogWriter->log(logString);
3377 logString = NULL;
3378 }
3379
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003380 // Collect timestamp statistics for the Playback Thread types that support it.
3381 if (mType == MIXER
3382 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07003383 || mType == DIRECT
3384 || mType == OFFLOAD) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003385 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003386 // and associate with the sink frames written out. We need
3387 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003388 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003389 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003390 if (mStandby) {
3391 mTimestampVerifier.discontinuity();
3392 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3393 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3394 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3395 mSampleRate);
Andy Hungc8fddf32018-08-08 18:32:37 -07003396
3397 if (isTimestampCorrectionEnabled()) {
3398 ALOGV("TS_BEFORE: %d %lld %lld", id(),
3399 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3400 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
3401 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
3402 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3403 = correctedTimestamp.mFrames;
3404 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
3405 = correctedTimestamp.mTimeNs;
3406 ALOGV("TS_AFTER: %d %lld %lld", id(),
3407 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3408 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
Andy Hung2dbffc22018-08-08 18:50:41 -07003409
3410 // Note: Downstream latency only added if timestamp correction enabled.
Dean Wheatley30d28422018-11-06 10:27:40 +11003411 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
Andy Hung2dbffc22018-08-08 18:50:41 -07003412 const int64_t newPosition =
3413 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
Dean Wheatley30d28422018-11-06 10:27:40 +11003414 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
Andy Hung2dbffc22018-08-08 18:50:41 -07003415 // prevent retrograde
3416 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
3417 newPosition,
3418 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3419 - mSuspendedFrames));
3420 }
Andy Hungc8fddf32018-08-08 18:32:37 -07003421 }
3422
Andy Hung818e7a32016-02-16 18:08:07 -08003423 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003424 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003425
3426 // We keep track of the last valid kernel position in case we are in underrun
3427 // and the normal mixer period is the same as the fast mixer period, or there
3428 // is some error from the HAL.
3429 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3430 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3431 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3432 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3433 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3434
3435 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3436 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3437 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3438 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003439 }
3440
3441 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3442 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003443 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003444 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003445 }
3446
Andy Hung818e7a32016-02-16 18:08:07 -08003447 // copy over kernel info
3448 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003449 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3450 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003451 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3452 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003453 } else {
3454 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003455 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003456
Andy Hungc54b1ff2016-02-23 14:07:07 -08003457 // mFramesWritten for non-offloaded tracks are contiguous
3458 // even after standby() is called. This is useful for the track frame
3459 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003460 bool serverLocationUpdate = false;
3461 if (mFramesWritten != lastFramesWritten) {
3462 serverLocationUpdate = true;
3463 lastFramesWritten = mFramesWritten;
3464 }
3465 // Only update timestamps if there is a meaningful change.
3466 // Either the kernel timestamp must be valid or we have written something.
3467 if (kernelLocationUpdate || serverLocationUpdate) {
3468 if (serverLocationUpdate) {
3469 // use the time before we called the HAL write - it is a bit more accurate
3470 // to when the server last read data than the current time here.
3471 //
Andy Hung446f4df2019-02-21 12:26:41 -08003472 // If we haven't written anything, mLastIoBeginNs will be -1
Andy Hung69488c42016-05-16 18:43:33 -07003473 // and we use systemTime().
3474 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
Andy Hung446f4df2019-02-21 12:26:41 -08003475 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
3476 ? systemTime() : mLastIoBeginNs;
Andy Hung69488c42016-05-16 18:43:33 -07003477 }
Andy Hungdae27702016-10-31 14:01:16 -07003478
3479 for (const sp<Track> &t : mActiveTracks) {
3480 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003481 t->updateTrackFrameInfo(
3482 t->mAudioTrackServerProxy->framesReleased(),
3483 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003484 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003485 mTimestamp);
3486 }
Andy Hunge10393e2015-06-12 13:59:33 -07003487 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003488 }
Andy Hunge6c37112019-02-26 17:38:10 -08003489
3490 if (audio_has_proportional_frames(mFormat)) {
3491 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
3492 if (latencyMs != 0.) { // note 0. means timestamp is empty.
3493 mLatencyMs.add(latencyMs);
3494 }
3495 }
3496
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003497 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003498#if 0
3499 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003500 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003501 timespec ts;
3502 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003503 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003504 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003505 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003506 }
3507 ++z;
3508#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003509 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003510 if (mSignalPending) {
3511 // A signal was raised while we were unlocked
3512 mSignalPending = false;
3513 } else if (waitingAsyncCallback_l()) {
3514 if (exitPending()) {
3515 break;
3516 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003517 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003518 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003519 releaseWakeLock_l();
3520 released = true;
3521 }
Andy Hung10cbff12017-02-21 17:30:14 -08003522
3523 const int64_t waitNs = computeWaitTimeNs_l();
3524 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3525 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3526 if (status == TIMED_OUT) {
3527 mSignalPending = true; // if timeout recheck everything
3528 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003529 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003530 if (released) {
3531 acquireWakeLock_l();
3532 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003533 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3534 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003535
3536 continue;
3537 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003538 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003539 isSuspended()) {
3540 // put audio hardware into standby after short delay
3541 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003542
3543 threadLoop_standby();
3544
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003545 // This is where we go into standby
3546 if (!mStandby) {
3547 LOG_AUDIO_STATE();
3548 }
Eric Laurent81784c32012-11-19 14:55:58 -08003549 mStandby = true;
Andy Hungd0979812019-02-21 15:51:44 -08003550 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003551 }
3552
Eric Tan39ec8d62018-07-24 09:49:29 -07003553 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003554 // we're about to wait, flush the binder command buffer
3555 IPCThreadState::self()->flushCommands();
3556
3557 clearOutputTracks();
3558
3559 if (exitPending()) {
3560 break;
3561 }
3562
3563 releaseWakeLock_l();
3564 // wait until we have something to do...
3565 ALOGV("%s going to sleep", myName.string());
3566 mWaitWorkCV.wait(mLock);
3567 ALOGV("%s waking up", myName.string());
3568 acquireWakeLock_l();
3569
3570 mMixerStatus = MIXER_IDLE;
3571 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3572 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003573 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003574 checkSilentMode_l();
3575
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003576 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3577 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003578 if (mType == MIXER) {
3579 sleepTimeShift = 0;
3580 }
3581
3582 continue;
3583 }
3584 }
Eric Laurent81784c32012-11-19 14:55:58 -08003585 // mMixerStatusIgnoringFastTracks is also updated internally
3586 mMixerStatus = prepareTracks_l(&tracksToRemove);
3587
Andy Hungdae27702016-10-31 14:01:16 -07003588 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003589
Kevin Rocard069c2712018-03-29 19:09:14 -07003590 updateMetadata_l();
3591
Eric Laurent81784c32012-11-19 14:55:58 -08003592 // prevent any changes in effect chain list and in each effect chain
3593 // during mixing and effect process as the audio buffers could be deleted
3594 // or modified if an effect is created or deleted
3595 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003596
3597 // Determine which session to pick up haptic data.
3598 // This must be done under the same lock as prepareTracks_l().
3599 // TODO: Write haptic data directly to sink buffer when mixing.
3600 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3601 for (const auto& track : mActiveTracks) {
3602 if (track->getHapticPlaybackEnabled()) {
3603 activeHapticSessionId = track->sessionId();
3604 break;
3605 }
3606 }
3607 }
3608
Andy Hungc1646382019-04-30 16:12:10 -07003609 // Acquire a local copy of active tracks with lock (release w/o lock).
3610 //
3611 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3612 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3613 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3614 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003615 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003616
Eric Laurentbfb1b832013-01-07 09:53:42 -08003617 if (mBytesRemaining == 0) {
3618 mCurrentWriteLength = 0;
3619 if (mMixerStatus == MIXER_TRACKS_READY) {
3620 // threadLoop_mix() sets mCurrentWriteLength
3621 threadLoop_mix();
3622 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3623 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003624 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003625 // must be written to HAL
3626 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003627 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003628 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003629
3630 // Tally underrun frames as we are inserting 0s here.
3631 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003632 if (track->mFillingUpStatus == Track::FS_ACTIVE
3633 && !track->isStopped()
3634 && !track->isPaused()
3635 && !track->isTerminated()) {
3636 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3637 __func__, track->id(), track->getTrackStateAsString(),
3638 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003639 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3640 }
3641 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003642 }
3643 }
Andy Hung98ef9782014-03-04 14:46:50 -08003644 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003645 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003646 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3647 // or mSinkBuffer (if there are no effects).
3648 //
3649 // This is done pre-effects computation; if effects change to
3650 // support higher precision, this needs to move.
3651 //
3652 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003653 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003654 if (mMixerBufferValid) {
3655 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3656 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3657
Andy Hung2ddee192015-12-18 17:34:44 -08003658 // mono blend occurs for mixer threads only (not direct or offloaded)
3659 // and is handled here if we're going directly to the sink.
3660 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003661 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3662 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003663 }
3664
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003665 if (!hasFastMixer()) {
3666 // Balance must take effect after mono conversion.
3667 // We do it here if there is no FastMixer.
3668 // mBalance detects zero balance within the class for speed (not needed here).
3669 mBalance.setBalance(mMasterBalance.load());
3670 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3671 }
3672
Andy Hung98ef9782014-03-04 14:46:50 -08003673 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003674 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3675
3676 // If we're going directly to the sink and there are haptic channels,
3677 // we should adjust channels as the sample data is partially interleaved
3678 // in this case.
3679 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3680 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3681 mChannelCount + mHapticChannelCount,
3682 audio_bytes_per_sample(format),
3683 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3684 }
Andy Hung98ef9782014-03-04 14:46:50 -08003685 }
3686
Eric Laurentbfb1b832013-01-07 09:53:42 -08003687 mBytesRemaining = mCurrentWriteLength;
3688 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003689 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3690 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3691 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3692 mBytesWritten += mBytesRemaining;
3693 mFramesWritten += framesRemaining;
3694 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003695 mBytesRemaining = 0;
3696 }
Eric Laurent81784c32012-11-19 14:55:58 -08003697
Eric Laurentbfb1b832013-01-07 09:53:42 -08003698 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003699 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003700 for (size_t i = 0; i < effectChains.size(); i ++) {
3701 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003702 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003703 if (activeHapticSessionId != AUDIO_SESSION_NONE
3704 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003705 // Haptic data is active in this case, copy it directly from
3706 // in buffer to out buffer.
3707 const size_t audioBufferSize = mNormalFrameCount
3708 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3709 memcpy_by_audio_format(
3710 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3711 EFFECT_BUFFER_FORMAT,
3712 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3713 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3714 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003715 }
Eric Laurent81784c32012-11-19 14:55:58 -08003716 }
3717 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003718 // Process effect chains for offloaded thread even if no audio
3719 // was read from audio track: process only updates effect state
3720 // and thus does have to be synchronized with audio writes but may have
3721 // to be called while waiting for async write callback
3722 if (mType == OFFLOAD) {
3723 for (size_t i = 0; i < effectChains.size(); i ++) {
3724 effectChains[i]->process_l();
3725 }
3726 }
Eric Laurent81784c32012-11-19 14:55:58 -08003727
Andy Hung98ef9782014-03-04 14:46:50 -08003728 // Only if the Effects buffer is enabled and there is data in the
3729 // Effects buffer (buffer valid), we need to
3730 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003731 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003732 if (mEffectBufferValid) {
3733 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003734
3735 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003736 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3737 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003738 }
3739
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003740 if (!hasFastMixer()) {
3741 // Balance must take effect after mono conversion.
3742 // We do it here if there is no FastMixer.
3743 // mBalance detects zero balance within the class for speed (not needed here).
3744 mBalance.setBalance(mMasterBalance.load());
3745 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3746 }
3747
Andy Hung98ef9782014-03-04 14:46:50 -08003748 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003749 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3750 // The sample data is partially interleaved when haptic channels exist,
3751 // we need to adjust channels here.
3752 if (mHapticChannelCount > 0) {
3753 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3754 mChannelCount + mHapticChannelCount,
3755 audio_bytes_per_sample(mFormat),
3756 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3757 }
Andy Hung98ef9782014-03-04 14:46:50 -08003758 }
3759
Eric Laurent81784c32012-11-19 14:55:58 -08003760 // enable changes in effect chain
3761 unlockEffectChains(effectChains);
3762
Eric Laurentbfb1b832013-01-07 09:53:42 -08003763 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003764 // mSleepTimeUs == 0 means we must write to audio hardware
3765 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003766 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003767 // writePeriodNs is updated >= 0 when ret > 0.
3768 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003769 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003770 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003771 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003772 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003773 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003774 if (ret < 0) {
3775 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003776 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003777 mBytesWritten += ret;
3778 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003779 const int64_t frames = ret / mFrameSize;
3780 mFramesWritten += frames;
3781
3782 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3783 // process information relating to write time.
3784 if (audio_has_proportional_frames(mFormat)) {
3785 // we are in a continuous mixing cycle
3786 if (mMixerStatus == MIXER_TRACKS_READY &&
3787 loopCount == lastLoopCountWritten + 1) {
3788
3789 const double jitterMs =
3790 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3791 {frames, writePeriodNs},
3792 {0, 0} /* lastTimestamp */, mSampleRate);
3793 const double processMs =
3794 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3795
3796 Mutex::Autolock _l(mLock);
3797 mIoJitterMs.add(jitterMs);
3798 mProcessTimeMs.add(processMs);
3799 }
3800
3801 // write blocked detection
3802 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3803 if (mType == MIXER && deltaWriteNs > maxPeriod) {
3804 mNumDelayedWrites++;
3805 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3806 ATRACE_NAME("underrun");
3807 ALOGW("write blocked for %lld msecs, "
3808 "%d delayed writes, thread %d",
3809 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3810 mNumDelayedWrites, mId);
3811 lastWarning = lastIoEndNs;
3812 }
3813 }
3814 }
3815 // update timing info.
3816 mLastIoBeginNs = lastIoBeginNs;
3817 mLastIoEndNs = lastIoEndNs;
3818 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003819 }
3820 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3821 (mMixerStatus == MIXER_DRAIN_ALL)) {
3822 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003823 }
Andy Hung08fb1742015-05-31 23:22:10 -07003824 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07003825
3826 if (mThreadThrottle
3827 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08003828 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07003829 // Limit MixerThread data processing to no more than twice the
3830 // expected processing rate.
3831 //
3832 // This helps prevent underruns with NuPlayer and other applications
3833 // which may set up buffers that are close to the minimum size, or use
3834 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3835 //
3836 // The throttle smooths out sudden large data drains from the device,
3837 // e.g. when it comes out of standby, which often causes problems with
3838 // (1) mixer threads without a fast mixer (which has its own warm-up)
3839 // (2) minimum buffer sized tracks (even if the track is full,
3840 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003841 //
3842 // Total time spent in last processing cycle equals time spent in
3843 // 1. threadLoop_write, as well as time spent in
3844 // 2. threadLoop_mix (significant for heavy mixing, especially
3845 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003846
Andy Hung446f4df2019-02-21 12:26:41 -08003847 // it's OK if deltaMs is an overestimate.
3848
3849 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003850
Ivan Lozanoea04d392017-11-07 14:37:07 -08003851 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003852 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3853 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003854 // notify of throttle start on verbose log
3855 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3856 "mixer(%p) throttle begin:"
3857 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003858 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003859 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003860 // Throttle must be attributed to the previous mixer loop's write time
3861 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08003862 // This also ensures proper timing statistics.
3863 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07003864 } else {
3865 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3866 if (diff > 0) {
3867 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003868 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07003869 ALOGD_IF(!isSingleDeviceType(
3870 outDeviceTypes(), audio_is_a2dp_out_device) &&
3871 !isSingleDeviceType(
3872 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07003873 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003874 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3875 }
Andy Hung08fb1742015-05-31 23:22:10 -07003876 }
3877 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003878 }
Eric Laurent81784c32012-11-19 14:55:58 -08003879
Eric Laurentbfb1b832013-01-07 09:53:42 -08003880 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003881 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003882 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003883 // suspended requires accurate metering of sleep time.
3884 if (isSuspended()) {
3885 // advance by expected sleepTime
3886 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3887 const nsecs_t nowNs = systemTime();
3888
3889 // compute expected next time vs current time.
3890 // (negative deltas are treated as delays).
3891 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3892 if (deltaNs < -kMaxNextBufferDelayNs) {
3893 // Delays longer than the max allowed trigger a reset.
3894 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3895 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3896 timeLoopNextNs = nowNs + deltaNs;
3897 } else if (deltaNs < 0) {
3898 // Delays within the max delay allowed: zero the delta/sleepTime
3899 // to help the system catch up in the next iteration(s)
3900 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3901 deltaNs = 0;
3902 }
3903 // update sleep time (which is >= 0)
3904 mSleepTimeUs = deltaNs / 1000;
3905 }
Eric Laurente93cc032016-05-05 10:15:10 -07003906 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3907 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003908 }
Glenn Kastene7754022014-10-31 12:11:26 -07003909 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003910 }
Eric Laurent81784c32012-11-19 14:55:58 -08003911 }
3912
3913 // Finally let go of removed track(s), without the lock held
3914 // since we can't guarantee the destructors won't acquire that
3915 // same lock. This will also mutate and push a new fast mixer state.
3916 threadLoop_removeTracks(tracksToRemove);
3917 tracksToRemove.clear();
3918
3919 // FIXME I don't understand the need for this here;
3920 // it was in the original code but maybe the
3921 // assignment in saveOutputTracks() makes this unnecessary?
3922 clearOutputTracks();
3923
3924 // Effect chains will be actually deleted here if they were removed from
3925 // mEffectChains list during mixing or effects processing
3926 effectChains.clear();
3927
3928 // FIXME Note that the above .clear() is no longer necessary since effectChains
3929 // is now local to this block, but will keep it for now (at least until merge done).
3930 }
3931
Eric Laurentbfb1b832013-01-07 09:53:42 -08003932 threadLoop_exit();
3933
Eric Laurentcf817a22014-08-04 20:36:31 -07003934 if (!mStandby) {
3935 threadLoop_standby();
3936 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003937 }
3938
3939 releaseWakeLock();
3940
3941 ALOGV("Thread %p type %d exiting", this, mType);
3942 return false;
3943}
3944
Eric Laurentbfb1b832013-01-07 09:53:42 -08003945// removeTracks_l() must be called with ThreadBase::mLock held
3946void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3947{
Andy Hungfe726a62018-09-27 15:17:25 -07003948 for (const auto& track : tracksToRemove) {
3949 mActiveTracks.remove(track);
3950 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
3951 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3952 if (chain != 0) {
3953 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
3954 __func__, track->id(), chain.get(), track->sessionId());
3955 chain->decActiveTrackCnt();
3956 }
3957 // If an external client track, inform APM we're no longer active, and remove if needed.
3958 // We do this under lock so that the state is consistent if the Track is destroyed.
3959 if (track->isExternalTrack()) {
3960 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003961 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07003962 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003963 }
3964 }
Andy Hungfe726a62018-09-27 15:17:25 -07003965 if (track->isTerminated()) {
3966 // remove from our tracks vector
3967 removeTrack_l(track);
3968 }
jiabin57303cc2018-12-18 15:45:57 -08003969 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
3970 && mHapticChannelCount > 0) {
3971 mLock.unlock();
3972 // Unlock due to VibratorService will lock for this call and will
3973 // call Tracks.mute/unmute which also require thread's lock.
3974 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
3975 mLock.lock();
jiabin245cdd92018-12-07 17:55:15 -08003976 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003977 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003978}
Eric Laurent81784c32012-11-19 14:55:58 -08003979
Eric Laurentaccc1472013-09-20 09:36:34 -07003980status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3981{
3982 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003983 ExtendedTimestamp ets;
3984 status_t status = mNormalSink->getTimestamp(ets);
3985 if (status == NO_ERROR) {
3986 status = ets.getBestTimestamp(&timestamp);
3987 }
3988 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003989 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003990 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003991 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003992 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003993 timestamp.mPosition = (uint32_t)position64;
Dean Wheatley30d28422018-11-06 10:27:40 +11003994 if (mDownstreamLatencyStatMs.getN() > 0) {
3995 const uint32_t positionOffset =
3996 (uint32_t)(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
3997 if (positionOffset > timestamp.mPosition) {
3998 timestamp.mPosition = 0;
3999 } else {
4000 timestamp.mPosition -= positionOffset;
4001 }
4002 }
Eric Laurentaccc1472013-09-20 09:36:34 -07004003 return NO_ERROR;
4004 }
4005 }
4006 return INVALID_OPERATION;
4007}
Eric Laurent1c333e22014-05-20 10:48:17 -07004008
Eric Laurenteab90452019-06-24 15:17:46 -07004009// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4010// still applied by the mixer.
4011// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4012// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4013// if more than one track are active
4014status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4015{
4016 status_t result = NO_ERROR;
4017 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4018 if (*volume != mLeftVolFloat) {
4019 result = mOutput->stream->setVolume(*volume, *volume);
4020 ALOGE_IF(result != OK,
4021 "Error when setting output stream volume: %d", result);
4022 if (result == NO_ERROR) {
4023 mLeftVolFloat = *volume;
4024 }
4025 }
4026 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4027 // remove stream volume contribution from software volume.
4028 if (mLeftVolFloat == *volume) {
4029 *volume = 1.0f;
4030 }
4031 }
4032 return result;
4033}
4034
Eric Laurent054d9d32015-04-24 08:48:48 -07004035status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4036 audio_patch_handle_t *handle)
4037{
Andy Hungf60abce2016-08-26 11:37:54 -07004038 status_t status;
4039 if (property_get_bool("af.patch_park", false /* default_value */)) {
4040 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4041 // or if HAL does not properly lock against access.
4042 AutoPark<FastMixer> park(mFastMixer);
4043 status = PlaybackThread::createAudioPatch_l(patch, handle);
4044 } else {
4045 status = PlaybackThread::createAudioPatch_l(patch, handle);
4046 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004047 return status;
4048}
4049
Eric Laurent1c333e22014-05-20 10:48:17 -07004050status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4051 audio_patch_handle_t *handle)
4052{
4053 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004054
4055 // store new device and send to effects
4056 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004057 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004058 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004059 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4060 && !mOutput->audioHwDev->supportsAudioPatches(),
4061 "Enumerated device type(%#x) must not be used "
4062 "as it does not support audio patches",
4063 patch->sinks[i].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004064 type |= patch->sinks[i].ext.device.type;
jiabinc52b1ff2019-10-31 17:20:42 -07004065 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4066 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004067 }
4068
François Gaffie0c280aa2018-07-25 10:02:15 +02004069 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004070#ifdef ADD_BATTERY_DATA
4071 // when changing the audio output device, call addBatteryData to notify
4072 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004073 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004074 uint32_t params = 0;
4075 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004076 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004077 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004078 }
4079
Eric Laurent054d9d32015-04-24 08:48:48 -07004080 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004081 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004082 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4083 }
4084
4085 if (params != 0) {
4086 addBatteryData(params);
4087 }
4088 }
4089#endif
4090
4091 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004092 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004093 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004094
jiabinc52b1ff2019-10-31 17:20:42 -07004095 // mPatch.num_sinks is not set when the thread is created so that
4096 // the first patch creation triggers an ioConfigChanged callback
4097 bool configChanged = (mPatch.num_sinks == 0) ||
4098 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004099 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004100 mOutDeviceTypeAddrs = deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004101
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004102 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004103 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4104 status = hwDevice->createAudioPatch(patch->num_sources,
4105 patch->sources,
4106 patch->num_sinks,
4107 patch->sinks,
4108 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004109 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004110 char *address;
4111 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4112 //FIXME: we only support address on first sink with HAL version < 3.0
4113 address = audio_device_address_to_parameter(
4114 patch->sinks[0].ext.device.type,
4115 patch->sinks[0].ext.device.address);
4116 } else {
4117 address = (char *)calloc(1, 1);
4118 }
4119 AudioParameter param = AudioParameter(String8(address));
4120 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004121 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004122 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004123 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004124 }
Eric Laurente8726fe2015-06-26 09:39:24 -07004125 if (configChanged) {
4126 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4127 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004128 return status;
4129}
4130
Eric Laurent054d9d32015-04-24 08:48:48 -07004131status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4132{
Andy Hungf60abce2016-08-26 11:37:54 -07004133 status_t status;
4134 if (property_get_bool("af.patch_park", false /* default_value */)) {
4135 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4136 // or if HAL does not properly lock against access.
4137 AutoPark<FastMixer> park(mFastMixer);
4138 status = PlaybackThread::releaseAudioPatch_l(handle);
4139 } else {
4140 status = PlaybackThread::releaseAudioPatch_l(handle);
4141 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004142 return status;
4143}
4144
Eric Laurent1c333e22014-05-20 10:48:17 -07004145status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4146{
4147 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004148
jiabinc52b1ff2019-10-31 17:20:42 -07004149 mPatch = audio_patch{};
4150 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004151
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004152 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004153 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4154 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004155 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004156 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004157 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004158 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004159 }
4160 return status;
4161}
4162
Eric Laurent83b88082014-06-20 18:31:16 -07004163void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4164{
4165 Mutex::Autolock _l(mLock);
4166 mTracks.add(track);
4167}
4168
4169void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4170{
4171 Mutex::Autolock _l(mLock);
4172 destroyTrack_l(track);
4173}
4174
Mikhail Naganovdc769682018-05-04 15:34:08 -07004175void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004176{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004177 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004178 config->role = AUDIO_PORT_ROLE_SOURCE;
4179 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4180 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004181 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4182 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4183 config->flags.output = mOutput->flags;
4184 }
Eric Laurent83b88082014-06-20 18:31:16 -07004185}
4186
Eric Laurent81784c32012-11-19 14:55:58 -08004187// ----------------------------------------------------------------------------
4188
4189AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
jiabinc52b1ff2019-10-31 17:20:42 -07004190 audio_io_handle_t id, bool systemReady, type_t type)
4191 : PlaybackThread(audioFlinger, output, id, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004192 // mAudioMixer below
4193 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004194 mFastMixerFutex(0),
4195 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004196 // mOutputSink below
4197 // mPipeSink below
4198 // mNormalSink below
4199{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004200 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004201 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004202 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004203 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004204 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4205 mNormalFrameCount);
4206 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4207
Andy Hungfbfc3952015-01-15 13:33:51 -08004208 if (type == DUPLICATING) {
4209 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4210 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4211 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4212 return;
4213 }
Eric Laurent81784c32012-11-19 14:55:58 -08004214 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004215 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004216 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004217 const NBAIO_Format offers[1] = {Format_from_SR_C(
4218 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004219#if !LOG_NDEBUG
4220 ssize_t index =
4221#else
4222 (void)
4223#endif
4224 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004225 ALOG_ASSERT(index == 0);
4226
4227 // initialize fast mixer depending on configuration
4228 bool initFastMixer;
4229 switch (kUseFastMixer) {
4230 case FastMixer_Never:
4231 initFastMixer = false;
4232 break;
4233 case FastMixer_Always:
4234 initFastMixer = true;
4235 break;
4236 case FastMixer_Static:
4237 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004238 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4239 // where the period is less than an experimentally determined threshold that can be
4240 // scheduled reliably with CFS. However, the BT A2DP HAL is
4241 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4242 initFastMixer = mFrameCount < mNormalFrameCount
jiabinc52b1ff2019-10-31 17:20:42 -07004243 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
Eric Laurent81784c32012-11-19 14:55:58 -08004244 break;
4245 }
Andy Hungfda69402017-02-15 14:33:12 -08004246 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4247 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4248 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004249 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004250 audio_format_t fastMixerFormat;
4251 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4252 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4253 } else {
4254 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4255 }
4256 if (mFormat != fastMixerFormat) {
4257 // change our Sink format to accept our intermediate precision
4258 mFormat = fastMixerFormat;
4259 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004260 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004261 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4262 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4263 }
Eric Laurent81784c32012-11-19 14:55:58 -08004264
4265 // create a MonoPipe to connect our submix to FastMixer
4266 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004267
Andy Hung1258c1a2014-05-23 21:22:17 -07004268 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004269 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004270 format.mFormat = fastMixerFormat;
4271 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4272
Eric Laurent81784c32012-11-19 14:55:58 -08004273 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4274 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4275 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4276 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4277 const NBAIO_Format offers[1] = {format};
4278 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004279#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004280 ssize_t index =
4281#else
4282 (void)
4283#endif
4284 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004285 ALOG_ASSERT(index == 0);
4286 monoPipe->setAvgFrames((mScreenState & 1) ?
4287 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4288 mPipeSink = monoPipe;
4289
Eric Laurent81784c32012-11-19 14:55:58 -08004290 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004291 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004292 FastMixerStateQueue *sq = mFastMixer->sq();
4293#ifdef STATE_QUEUE_DUMP
4294 sq->setObserverDump(&mStateQueueObserverDump);
4295 sq->setMutatorDump(&mStateQueueMutatorDump);
4296#endif
4297 FastMixerState *state = sq->begin();
4298 FastTrack *fastTrack = &state->mFastTracks[0];
4299 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4300 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4301 fastTrack->mVolumeProvider = NULL;
jiabin245cdd92018-12-07 17:55:15 -08004302 fastTrack->mChannelMask = mChannelMask | mHapticChannelMask; // mPipeSink channel mask for
4303 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004304 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004305 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabin84114c32019-04-10 16:38:07 -07004306 fastTrack->mHapticIntensity = AudioMixer::HAPTIC_SCALE_NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08004307 fastTrack->mGeneration++;
4308 state->mFastTracksGen++;
4309 state->mTrackMask = 1;
4310 // fast mixer will use the HAL output sink
4311 state->mOutputSink = mOutputSink.get();
4312 state->mOutputSinkGen++;
4313 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004314 // specify sink channel mask when haptic channel mask present as it can not
4315 // be calculated directly from channel count
4316 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
4317 ? AUDIO_CHANNEL_NONE : mChannelMask | mHapticChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08004318 state->mCommand = FastMixerState::COLD_IDLE;
4319 // already done in constructor initialization list
4320 //mFastMixerFutex = 0;
4321 state->mColdFutexAddr = &mFastMixerFutex;
4322 state->mColdGen++;
4323 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004324 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4325 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004326 sq->end();
4327 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4328
Eric Tan0513b5d2018-09-17 10:32:48 -07004329 NBLog::thread_info_t info;
4330 info.id = mId;
4331 info.type = NBLog::FASTMIXER;
4332 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4333
Eric Laurent81784c32012-11-19 14:55:58 -08004334 // start the fast mixer
4335 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4336 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004337 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004338 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004339
4340#ifdef AUDIO_WATCHDOG
4341 // create and start the watchdog
4342 mAudioWatchdog = new AudioWatchdog();
4343 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4344 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4345 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004346 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004347#endif
Andy Hung8946a282018-04-19 20:04:56 -07004348 } else {
4349#ifdef TEE_SINK
4350 // Only use the MixerThread tee if there is no FastMixer.
4351 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4352 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4353#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004354 }
4355
4356 switch (kUseFastMixer) {
4357 case FastMixer_Never:
4358 case FastMixer_Dynamic:
4359 mNormalSink = mOutputSink;
4360 break;
4361 case FastMixer_Always:
4362 mNormalSink = mPipeSink;
4363 break;
4364 case FastMixer_Static:
4365 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4366 break;
4367 }
4368}
4369
4370AudioFlinger::MixerThread::~MixerThread()
4371{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004372 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004373 FastMixerStateQueue *sq = mFastMixer->sq();
4374 FastMixerState *state = sq->begin();
4375 if (state->mCommand == FastMixerState::COLD_IDLE) {
4376 int32_t old = android_atomic_inc(&mFastMixerFutex);
4377 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004378 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004379 }
4380 }
4381 state->mCommand = FastMixerState::EXIT;
4382 sq->end();
4383 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4384 mFastMixer->join();
4385 // Though the fast mixer thread has exited, it's state queue is still valid.
4386 // We'll use that extract the final state which contains one remaining fast track
4387 // corresponding to our sub-mix.
4388 state = sq->begin();
4389 ALOG_ASSERT(state->mTrackMask == 1);
4390 FastTrack *fastTrack = &state->mFastTracks[0];
4391 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4392 delete fastTrack->mBufferProvider;
4393 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004394 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004395#ifdef AUDIO_WATCHDOG
4396 if (mAudioWatchdog != 0) {
4397 mAudioWatchdog->requestExit();
4398 mAudioWatchdog->requestExitAndWait();
4399 mAudioWatchdog.clear();
4400 }
4401#endif
4402 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004403 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004404 delete mAudioMixer;
4405}
4406
4407
4408uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4409{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004410 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004411 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4412 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4413 }
4414 return latency;
4415}
4416
Eric Laurentbfb1b832013-01-07 09:53:42 -08004417ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004418{
4419 // FIXME we should only do one push per cycle; confirm this is true
4420 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004421 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004422 FastMixerStateQueue *sq = mFastMixer->sq();
4423 FastMixerState *state = sq->begin();
4424 if (state->mCommand != FastMixerState::MIX_WRITE &&
4425 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4426 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004427
4428 // FIXME workaround for first HAL write being CPU bound on some devices
4429 ATRACE_BEGIN("write");
4430 mOutput->write((char *)mSinkBuffer, 0);
4431 ATRACE_END();
4432
Eric Laurent81784c32012-11-19 14:55:58 -08004433 int32_t old = android_atomic_inc(&mFastMixerFutex);
4434 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004435 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004436 }
4437#ifdef AUDIO_WATCHDOG
4438 if (mAudioWatchdog != 0) {
4439 mAudioWatchdog->resume();
4440 }
4441#endif
4442 }
4443 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004444#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004445 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004446 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004447#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004448 sq->end();
4449 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4450 if (kUseFastMixer == FastMixer_Dynamic) {
4451 mNormalSink = mPipeSink;
4452 }
4453 } else {
4454 sq->end(false /*didModify*/);
4455 }
4456 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004457 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004458}
4459
4460void AudioFlinger::MixerThread::threadLoop_standby()
4461{
4462 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004463 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004464 FastMixerStateQueue *sq = mFastMixer->sq();
4465 FastMixerState *state = sq->begin();
4466 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004467 // Report any frames trapped in the Monopipe
4468 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4469 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4470 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4471 "monoPipeWritten:%lld monoPipeLeft:%lld",
4472 (long long)mFramesWritten, (long long)mSuspendedFrames,
4473 (long long)mPipeSink->framesWritten(), pipeFrames);
4474 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4475
Eric Laurent81784c32012-11-19 14:55:58 -08004476 state->mCommand = FastMixerState::COLD_IDLE;
4477 state->mColdFutexAddr = &mFastMixerFutex;
4478 state->mColdGen++;
4479 mFastMixerFutex = 0;
4480 sq->end();
4481 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4482 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4483 if (kUseFastMixer == FastMixer_Dynamic) {
4484 mNormalSink = mOutputSink;
4485 }
4486#ifdef AUDIO_WATCHDOG
4487 if (mAudioWatchdog != 0) {
4488 mAudioWatchdog->pause();
4489 }
4490#endif
4491 } else {
4492 sq->end(false /*didModify*/);
4493 }
4494 }
4495 PlaybackThread::threadLoop_standby();
4496}
4497
Eric Laurentbfb1b832013-01-07 09:53:42 -08004498bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4499{
4500 return false;
4501}
4502
4503bool AudioFlinger::PlaybackThread::shouldStandby_l()
4504{
4505 return !mStandby;
4506}
4507
4508bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4509{
4510 Mutex::Autolock _l(mLock);
4511 return waitingAsyncCallback_l();
4512}
4513
Eric Laurent81784c32012-11-19 14:55:58 -08004514// shared by MIXER and DIRECT, overridden by DUPLICATING
4515void AudioFlinger::PlaybackThread::threadLoop_standby()
4516{
4517 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004518 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004519 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004520 // discard any pending drain or write ack by incrementing sequence
4521 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4522 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004523 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004524 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4525 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004526 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004527 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004528}
4529
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004530void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4531{
4532 ALOGV("signal playback thread");
4533 broadcast_l();
4534}
4535
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004536void AudioFlinger::PlaybackThread::onAsyncError()
4537{
4538 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4539 invalidateTracks((audio_stream_type_t)i);
4540 }
4541}
4542
Eric Laurent81784c32012-11-19 14:55:58 -08004543void AudioFlinger::MixerThread::threadLoop_mix()
4544{
Eric Laurent81784c32012-11-19 14:55:58 -08004545 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004546 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004547 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004548 // increase sleep time progressively when application underrun condition clears.
4549 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4550 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4551 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004552 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004553 sleepTimeShift--;
4554 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004555 mSleepTimeUs = 0;
4556 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004557 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004558
Eric Laurent81784c32012-11-19 14:55:58 -08004559}
4560
4561void AudioFlinger::MixerThread::threadLoop_sleepTime()
4562{
4563 // If no tracks are ready, sleep once for the duration of an output
4564 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004565 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004566 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004567 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4568 // Using the Monopipe availableToWrite, we estimate the
4569 // sleep time to retry for more data (before we underrun).
4570 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4571 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4572 const size_t pipeFrames = monoPipe->maxFrames();
4573 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4574 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4575 const size_t framesDelay = std::min(
4576 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4577 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4578 pipeFrames, framesLeft, framesDelay);
4579 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4580 } else {
4581 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4582 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4583 mSleepTimeUs = kMinThreadSleepTimeUs;
4584 }
4585 // reduce sleep time in case of consecutive application underruns to avoid
4586 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4587 // duration we would end up writing less data than needed by the audio HAL if
4588 // the condition persists.
4589 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4590 sleepTimeShift++;
4591 }
Eric Laurent81784c32012-11-19 14:55:58 -08004592 }
4593 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004594 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004595 }
4596 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004597 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4598 // before effects processing or output.
4599 if (mMixerBufferValid) {
4600 memset(mMixerBuffer, 0, mMixerBufferSize);
4601 } else {
4602 memset(mSinkBuffer, 0, mSinkBufferSize);
4603 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004604 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004605 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4606 "anticipated start");
4607 }
4608 // TODO add standby time extension fct of effect tail
4609}
4610
4611// prepareTracks_l() must be called with ThreadBase::mLock held
4612AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4613 Vector< sp<Track> > *tracksToRemove)
4614{
Andy Hungc0691382018-09-12 18:01:57 -07004615 // clean up deleted track ids in AudioMixer before allocating new tracks
4616 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4617 // for each trackId, destroy it in the AudioMixer
4618 if (mAudioMixer->exists(trackId)) {
4619 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004620 }
4621 });
Andy Hungc0691382018-09-12 18:01:57 -07004622 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004623
4624 mixer_state mixerStatus = MIXER_IDLE;
4625 // find out which tracks need to be processed
4626 size_t count = mActiveTracks.size();
4627 size_t mixedTracks = 0;
4628 size_t tracksWithEffect = 0;
4629 // counts only _active_ fast tracks
4630 size_t fastTracks = 0;
4631 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4632
4633 float masterVolume = mMasterVolume;
4634 bool masterMute = mMasterMute;
4635
4636 if (masterMute) {
4637 masterVolume = 0;
4638 }
4639 // Delegate master volume control to effect in output mix effect chain if needed
4640 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4641 if (chain != 0) {
4642 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4643 chain->setVolume_l(&v, &v);
4644 masterVolume = (float)((v + (1 << 23)) >> 24);
4645 chain.clear();
4646 }
4647
4648 // prepare a new state to push
4649 FastMixerStateQueue *sq = NULL;
4650 FastMixerState *state = NULL;
4651 bool didModify = false;
4652 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004653 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004654 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004655 sq = mFastMixer->sq();
4656 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004657 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004658 }
4659
Andy Hung69aed5f2014-02-25 17:24:40 -08004660 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004661 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004662
Andy Hungbd3b2b02018-05-21 10:53:11 -07004663 // DeferredOperations handles statistics after setting mixerStatus.
4664 class DeferredOperations {
4665 public:
4666 DeferredOperations(mixer_state *mixerStatus)
4667 : mMixerStatus(mixerStatus) { }
4668
4669 // when leaving scope, tally frames properly.
4670 ~DeferredOperations() {
4671 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4672 // because that is when the underrun occurs.
4673 // We do not distinguish between FastTracks and NormalTracks here.
4674 if (*mMixerStatus == MIXER_TRACKS_READY) {
4675 for (const auto &underrun : mUnderrunFrames) {
4676 underrun.first->mAudioTrackServerProxy->tallyUnderrunFrames(
4677 underrun.second);
4678 }
4679 }
4680 }
4681
4682 // tallyUnderrunFrames() is called to update the track counters
4683 // with the number of underrun frames for a particular mixer period.
4684 // We defer tallying until we know the final mixer status.
4685 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4686 mUnderrunFrames.emplace_back(track, underrunFrames);
4687 }
4688
4689 private:
4690 const mixer_state * const mMixerStatus;
4691 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4692 } deferredOperations(&mixerStatus); // implicit nested scope for variable capture
4693
jiabin245cdd92018-12-07 17:55:15 -08004694 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004695 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004696 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004697
4698 // this const just means the local variable doesn't change
4699 Track* const track = t.get();
4700
4701 // process fast tracks
4702 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07004703 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
4704 "%s(%d): FastTrack(%d) present without FastMixer",
4705 __func__, id(), track->id());
4706
jiabin245cdd92018-12-07 17:55:15 -08004707 if (track->getHapticPlaybackEnabled()) {
4708 noFastHapticTrack = false;
4709 }
Eric Laurent81784c32012-11-19 14:55:58 -08004710
4711 // It's theoretically possible (though unlikely) for a fast track to be created
4712 // and then removed within the same normal mix cycle. This is not a problem, as
4713 // the track never becomes active so it's fast mixer slot is never touched.
4714 // The converse, of removing an (active) track and then creating a new track
4715 // at the identical fast mixer slot within the same normal mix cycle,
4716 // is impossible because the slot isn't marked available until the end of each cycle.
4717 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004718 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004719 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4720 FastTrack *fastTrack = &state->mFastTracks[j];
4721
4722 // Determine whether the track is currently in underrun condition,
4723 // and whether it had a recent underrun.
4724 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4725 FastTrackUnderruns underruns = ftDump->mUnderruns;
4726 uint32_t recentFull = (underruns.mBitFields.mFull -
4727 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4728 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4729 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4730 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4731 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4732 uint32_t recentUnderruns = recentPartial + recentEmpty;
4733 track->mObservedUnderruns = underruns;
4734 // don't count underruns that occur while stopping or pausing
4735 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004736 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004737 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4738 recentUnderruns > 0) {
4739 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004740 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004741 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004742 // Immediately account for FastTrack underruns.
4743 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004744
4745 // This is similar to the state machine for normal tracks,
4746 // with a few modifications for fast tracks.
4747 bool isActive = true;
4748 switch (track->mState) {
4749 case TrackBase::STOPPING_1:
4750 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004751 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004752 track->mState = TrackBase::STOPPING_2;
4753 }
4754 break;
4755 case TrackBase::PAUSING:
4756 // ramp down is not yet implemented
4757 track->setPaused();
4758 break;
4759 case TrackBase::RESUMING:
4760 // ramp up is not yet implemented
4761 track->mState = TrackBase::ACTIVE;
4762 break;
4763 case TrackBase::ACTIVE:
4764 if (recentFull > 0 || recentPartial > 0) {
4765 // track has provided at least some frames recently: reset retry count
4766 track->mRetryCount = kMaxTrackRetries;
4767 }
4768 if (recentUnderruns == 0) {
4769 // no recent underruns: stay active
4770 break;
4771 }
4772 // there has recently been an underrun of some kind
4773 if (track->sharedBuffer() == 0) {
4774 // were any of the recent underruns "empty" (no frames available)?
4775 if (recentEmpty == 0) {
4776 // no, then ignore the partial underruns as they are allowed indefinitely
4777 break;
4778 }
4779 // there has recently been an "empty" underrun: decrement the retry counter
4780 if (--(track->mRetryCount) > 0) {
4781 break;
4782 }
4783 // indicate to client process that the track was disabled because of underrun;
4784 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004785 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004786 // remove from active list, but state remains ACTIVE [confusing but true]
4787 isActive = false;
4788 break;
4789 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07004790 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08004791 case TrackBase::STOPPING_2:
4792 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004793 case TrackBase::STOPPED:
4794 case TrackBase::FLUSHED: // flush() while active
4795 // Check for presentation complete if track is inactive
4796 // We have consumed all the buffers of this track.
4797 // This would be incomplete if we auto-paused on underrun
4798 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004799 uint32_t latency = 0;
4800 status_t result = mOutput->stream->getLatency(&latency);
4801 ALOGE_IF(result != OK,
4802 "Error when retrieving output stream latency: %d", result);
4803 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004804 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004805 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4806 // track stays in active list until presentation is complete
4807 break;
4808 }
4809 }
4810 if (track->isStopping_2()) {
4811 track->mState = TrackBase::STOPPED;
4812 }
4813 if (track->isStopped()) {
4814 // Can't reset directly, as fast mixer is still polling this track
4815 // track->reset();
4816 // So instead mark this track as needing to be reset after push with ack
4817 resetMask |= 1 << i;
4818 }
4819 isActive = false;
4820 break;
4821 case TrackBase::IDLE:
4822 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004823 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004824 }
4825
4826 if (isActive) {
4827 // was it previously inactive?
4828 if (!(state->mTrackMask & (1 << j))) {
4829 ExtendedAudioBufferProvider *eabp = track;
4830 VolumeProvider *vp = track;
4831 fastTrack->mBufferProvider = eabp;
4832 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004833 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004834 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08004835 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08004836 fastTrack->mHapticIntensity = track->getHapticIntensity();
Eric Laurent81784c32012-11-19 14:55:58 -08004837 fastTrack->mGeneration++;
4838 state->mTrackMask |= 1 << j;
4839 didModify = true;
4840 // no acknowledgement required for newly active tracks
4841 }
Kevin Rocard12381092018-04-11 09:19:59 -07004842 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07004843 float volume;
4844 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
4845 volume = 0.f;
4846 } else {
4847 volume = masterVolume * mStreamTypes[track->streamType()].volume;
4848 }
4849
4850 handleVoipVolume_l(&volume);
4851
Eric Laurent81784c32012-11-19 14:55:58 -08004852 // cache the combined master volume and stream type volume for fast mixer; this
4853 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004854 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07004855 proxy->framesReleased()).first;
4856 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004857 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004858 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4859 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4860 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07004861
Kevin Rocard12381092018-04-11 09:19:59 -07004862 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004863 ++fastTracks;
4864 } else {
4865 // was it previously active?
4866 if (state->mTrackMask & (1 << j)) {
4867 fastTrack->mBufferProvider = NULL;
4868 fastTrack->mGeneration++;
4869 state->mTrackMask &= ~(1 << j);
4870 didModify = true;
4871 // If any fast tracks were removed, we must wait for acknowledgement
4872 // because we're about to decrement the last sp<> on those tracks.
4873 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4874 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004875 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4876 // AudioTrack may start (which may not be with a start() but with a write()
4877 // after underrun) and immediately paused or released. In that case the
4878 // FastTrack state hasn't had time to update.
4879 // TODO Remove the ALOGW when this theory is confirmed.
4880 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004881 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4882 j, track->mState, state->mTrackMask, recentUnderruns,
4883 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004884 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004885 }
4886 tracksToRemove->add(track);
4887 // Avoids a misleading display in dumpsys
4888 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4889 }
jiabin245cdd92018-12-07 17:55:15 -08004890 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
4891 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
4892 didModify = true;
4893 }
Eric Laurent81784c32012-11-19 14:55:58 -08004894 continue;
4895 }
4896
4897 { // local variable scope to avoid goto warning
4898
4899 audio_track_cblk_t* cblk = track->cblk();
4900
4901 // The first time a track is added we wait
4902 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07004903 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08004904
4905 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07004906 // use the trackId as the AudioMixer name.
4907 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08004908 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07004909 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08004910 track->mChannelMask,
4911 track->mFormat,
4912 track->mSessionId);
4913 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07004914 ALOGW("%s(): AudioMixer cannot create track(%d)"
4915 " mask %#x, format %#x, sessionId %d",
4916 __func__, trackId,
4917 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004918 tracksToRemove->add(track);
4919 track->invalidate(); // consider it dead.
4920 continue;
4921 }
4922 }
4923
Eric Laurent81784c32012-11-19 14:55:58 -08004924 // make sure that we have enough frames to mix one full buffer.
4925 // enforce this condition only once to enable draining the buffer in case the client
4926 // app does not call stop() and relies on underrun to stop:
4927 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4928 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004929 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004930 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004931 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004932
4933 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004934 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004935 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4936 // add frames already consumed but not yet released by the resampler
4937 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07004938 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004939
Eric Laurent81784c32012-11-19 14:55:58 -08004940 uint32_t minFrames = 1;
4941 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4942 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004943 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004944 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004945
4946 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004947 if (ATRACE_ENABLED()) {
4948 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004949 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07004950 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004951 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004952 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004953 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004954 !track->isPaused() && !track->isTerminated())
4955 {
Andy Hungc0691382018-09-12 18:01:57 -07004956 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004957
4958 mixedTracks++;
4959
Andy Hung69aed5f2014-02-25 17:24:40 -08004960 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4961 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004962 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004963 if (track->mainBuffer() != mSinkBuffer &&
4964 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004965 if (mEffectBufferEnabled) {
4966 mEffectBufferValid = true; // Later can set directly.
4967 }
Eric Laurent81784c32012-11-19 14:55:58 -08004968 chain = getEffectChain_l(track->sessionId());
4969 // Delegate volume control to effect in track effect chain if needed
4970 if (chain != 0) {
4971 tracksWithEffect++;
4972 } else {
Andy Hungc0691382018-09-12 18:01:57 -07004973 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08004974 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07004975 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08004976 }
4977 }
4978
4979
4980 int param = AudioMixer::VOLUME;
4981 if (track->mFillingUpStatus == Track::FS_FILLED) {
4982 // no ramp for the first volume setting
4983 track->mFillingUpStatus = Track::FS_ACTIVE;
4984 if (track->mState == TrackBase::RESUMING) {
4985 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08004986 // If a new track is paused immediately after start, do not ramp on resume.
4987 if (cblk->mServer != 0) {
4988 param = AudioMixer::RAMP_VOLUME;
4989 }
Eric Laurent81784c32012-11-19 14:55:58 -08004990 }
Andy Hungc0691382018-09-12 18:01:57 -07004991 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004992 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004993 // FIXME should not make a decision based on mServer
4994 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004995 // If the track is stopped before the first frame was mixed,
4996 // do not apply ramp
4997 param = AudioMixer::RAMP_VOLUME;
4998 }
4999
5000 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005001 uint32_t vl, vr; // in U8.24 integer format
5002 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005003 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005004 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005005 // Always fetch volumeshaper volume to ensure state is updated.
5006 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5007 const float vh = track->getVolumeHandler()->getVolume(
5008 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005009
Eric Laurenteab90452019-06-24 15:17:46 -07005010 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5011 v = 0;
5012 }
5013
5014 handleVoipVolume_l(&v);
5015
5016 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005017 vl = vr = 0;
5018 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005019 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005020 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005021 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005022 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5023 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005024 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005025 if (vlf > GAIN_FLOAT_UNITY) {
5026 ALOGV("Track left volume out of range: %.3g", vlf);
5027 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005028 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005029 if (vrf > GAIN_FLOAT_UNITY) {
5030 ALOGV("Track right volume out of range: %.3g", vrf);
5031 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005032 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005033 // now apply the master volume and stream type volume and shaper volume
5034 vlf *= v * vh;
5035 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005036 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005037 // then derive vl and vr as U8.24 versions for the effect chain
5038 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5039 vl = (uint32_t) (scaleto8_24 * vlf);
5040 vr = (uint32_t) (scaleto8_24 * vrf);
5041 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005042 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005043 // send level comes from shared memory and so may be corrupt
5044 if (sendLevel > MAX_GAIN_INT) {
5045 ALOGV("Track send level out of range: %04X", sendLevel);
5046 sendLevel = MAX_GAIN_INT;
5047 }
Andy Hung6be49402014-05-30 10:42:03 -07005048 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5049 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005050 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005051
Kevin Rocard12381092018-04-11 09:19:59 -07005052 track->setFinalVolume((vrf + vlf) / 2.f);
5053
Eric Laurent81784c32012-11-19 14:55:58 -08005054 // Delegate volume control to effect in track effect chain if needed
5055 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5056 // Do not ramp volume if volume is controlled by effect
5057 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005058 // Update remaining floating point volume levels
5059 vlf = (float)vl / (1 << 24);
5060 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005061 track->mHasVolumeController = true;
5062 } else {
5063 // force no volume ramp when volume controller was just disabled or removed
5064 // from effect chain to avoid volume spike
5065 if (track->mHasVolumeController) {
5066 param = AudioMixer::VOLUME;
5067 }
5068 track->mHasVolumeController = false;
5069 }
5070
Eric Laurent81784c32012-11-19 14:55:58 -08005071 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005072 mAudioMixer->setBufferProvider(trackId, track);
5073 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005074
Andy Hungc0691382018-09-12 18:01:57 -07005075 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5076 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5077 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005078 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005079 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005080 AudioMixer::TRACK,
5081 AudioMixer::FORMAT, (void *)track->format());
5082 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005083 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005084 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005085 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07005086 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005087 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07005088 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08005089 AudioMixer::MIXER_CHANNEL_MASK,
5090 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08005091 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005092 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005093 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005094 if (reqSampleRate == 0) {
5095 reqSampleRate = mSampleRate;
5096 } else if (reqSampleRate > maxSampleRate) {
5097 reqSampleRate = maxSampleRate;
5098 }
Eric Laurent81784c32012-11-19 14:55:58 -08005099 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005100 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005101 AudioMixer::RESAMPLE,
5102 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005103 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005104
Andy Hung333ab962019-05-28 20:23:35 -07005105 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005106 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005107 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005108 AudioMixer::TIMESTRETCH,
5109 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005110 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005111
Andy Hung69aed5f2014-02-25 17:24:40 -08005112 /*
5113 * Select the appropriate output buffer for the track.
5114 *
Andy Hung98ef9782014-03-04 14:46:50 -08005115 * Tracks with effects go into their own effects chain buffer
5116 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005117 *
5118 * Other tracks can use mMixerBuffer for higher precision
5119 * channel accumulation. If this buffer is enabled
5120 * (mMixerBufferEnabled true), then selected tracks will accumulate
5121 * into it.
5122 *
5123 */
5124 if (mMixerBufferEnabled
5125 && (track->mainBuffer() == mSinkBuffer
5126 || track->mainBuffer() == mMixerBuffer)) {
5127 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005128 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005129 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08005130 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08005131 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005132 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005133 AudioMixer::TRACK,
5134 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5135 // TODO: override track->mainBuffer()?
5136 mMixerBufferValid = true;
5137 } else {
5138 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005139 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005140 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005141 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005142 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005143 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005144 AudioMixer::TRACK,
5145 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5146 }
Eric Laurent81784c32012-11-19 14:55:58 -08005147 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005148 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005149 AudioMixer::TRACK,
5150 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005151 mAudioMixer->setParameter(
5152 trackId,
5153 AudioMixer::TRACK,
5154 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005155 mAudioMixer->setParameter(
5156 trackId,
5157 AudioMixer::TRACK,
5158 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Eric Laurent81784c32012-11-19 14:55:58 -08005159
5160 // reset retry count
5161 track->mRetryCount = kMaxTrackRetries;
5162
5163 // If one track is ready, set the mixer ready if:
5164 // - the mixer was not ready during previous round OR
5165 // - no other track is not ready
5166 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5167 mixerStatus != MIXER_TRACKS_ENABLED) {
5168 mixerStatus = MIXER_TRACKS_READY;
5169 }
5170 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005171 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005172 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungc0691382018-09-12 18:01:57 -07005173 ALOGV("track(%d) underrun, framesReady(%zu) < framesDesired(%zd)",
5174 trackId, framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005175 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005176 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005177 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005178
Eric Laurent81784c32012-11-19 14:55:58 -08005179 // clear effect chain input buffer if an active track underruns to avoid sending
5180 // previous audio buffer again to effects
5181 chain = getEffectChain_l(track->sessionId());
5182 if (chain != 0) {
5183 chain->clearInputBuffer();
5184 }
5185
Andy Hungc0691382018-09-12 18:01:57 -07005186 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005187 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5188 track->isStopped() || track->isPaused()) {
5189 // We have consumed all the buffers of this track.
5190 // Remove it from the list of active tracks.
5191 // TODO: use actual buffer filling status instead of latency when available from
5192 // audio HAL
5193 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005194 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005195 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5196 if (track->isStopped()) {
5197 track->reset();
5198 }
5199 tracksToRemove->add(track);
5200 }
5201 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005202 // No buffers for this track. Give it a few chances to
5203 // fill a buffer, then remove it from active list.
5204 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005205 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5206 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005207 tracksToRemove->add(track);
5208 // indicate to client process that the track was disabled because of underrun;
5209 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005210 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005211 // If one track is not ready, mark the mixer also not ready if:
5212 // - the mixer was ready during previous round OR
5213 // - no other track is ready
5214 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5215 mixerStatus != MIXER_TRACKS_READY) {
5216 mixerStatus = MIXER_TRACKS_ENABLED;
5217 }
5218 }
Andy Hungc0691382018-09-12 18:01:57 -07005219 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005220 }
5221
5222 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005223
5224 }
5225
jiabin245cdd92018-12-07 17:55:15 -08005226 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5227 // When there is no fast track playing haptic and FastMixer exists,
5228 // enabling the first FastTrack, which provides mixed data from normal
5229 // tracks, to play haptic data.
5230 FastTrack *fastTrack = &state->mFastTracks[0];
5231 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5232 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5233 didModify = true;
5234 }
5235 }
5236
Eric Laurent81784c32012-11-19 14:55:58 -08005237 // Push the new FastMixer state if necessary
5238 bool pauseAudioWatchdog = false;
5239 if (didModify) {
5240 state->mFastTracksGen++;
5241 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5242 if (kUseFastMixer == FastMixer_Dynamic &&
5243 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5244 state->mCommand = FastMixerState::COLD_IDLE;
5245 state->mColdFutexAddr = &mFastMixerFutex;
5246 state->mColdGen++;
5247 mFastMixerFutex = 0;
5248 if (kUseFastMixer == FastMixer_Dynamic) {
5249 mNormalSink = mOutputSink;
5250 }
5251 // If we go into cold idle, need to wait for acknowledgement
5252 // so that fast mixer stops doing I/O.
5253 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5254 pauseAudioWatchdog = true;
5255 }
Eric Laurent81784c32012-11-19 14:55:58 -08005256 }
5257 if (sq != NULL) {
5258 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005259 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5260 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5261 // when bringing the output sink into standby.)
5262 //
5263 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5264 //
5265 // This occurs with BT suspend when we idle the FastMixer with
5266 // active tracks, which may be added or removed.
5267 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005268 }
5269#ifdef AUDIO_WATCHDOG
5270 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5271 mAudioWatchdog->pause();
5272 }
5273#endif
5274
5275 // Now perform the deferred reset on fast tracks that have stopped
5276 while (resetMask != 0) {
5277 size_t i = __builtin_ctz(resetMask);
5278 ALOG_ASSERT(i < count);
5279 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005280 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005281 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5282 track->reset();
5283 }
5284
Andy Hung80d03d22018-04-10 10:32:11 -07005285 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5286 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5287 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5288 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5289 // See also the implementation of destroyTrack_l().
5290 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005291 const int trackId = track->id();
5292 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5293 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005294 }
5295 }
5296
Eric Laurent81784c32012-11-19 14:55:58 -08005297 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005298 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005299
Eric Laurent97d547d2014-09-02 14:45:53 -07005300 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5301 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005302 }
5303
5304 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005305 // as long as there are effects we should clear the effects buffer, to avoid
5306 // passing a non-clean buffer to the effect chain
5307 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005308 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005309 // sink or mix buffer must be cleared if all tracks are connected to an
5310 // effect chain as in this case the mixer will not write to the sink or mix buffer
5311 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005312 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5313 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005314 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005315 if (mMixerBufferValid) {
5316 memset(mMixerBuffer, 0, mMixerBufferSize);
5317 // TODO: In testing, mSinkBuffer below need not be cleared because
5318 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5319 // after mixing.
5320 //
5321 // To enforce this guarantee:
5322 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5323 // (mixedTracks == 0 && fastTracks > 0))
5324 // must imply MIXER_TRACKS_READY.
5325 // Later, we may clear buffers regardless, and skip much of this logic.
5326 }
Andy Hung98ef9782014-03-04 14:46:50 -08005327 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005328 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005329 }
5330
5331 // if any fast tracks, then status is ready
5332 mMixerStatusIgnoringFastTracks = mixerStatus;
5333 if (fastTracks > 0) {
5334 mixerStatus = MIXER_TRACKS_READY;
5335 }
5336 return mixerStatus;
5337}
5338
Eric Laurentad7dd962016-09-22 12:38:37 -07005339// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005340uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005341{
5342 uint32_t trackCount = 0;
5343 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005344 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005345 trackCount++;
5346 }
5347 }
5348 return trackCount;
5349}
5350
Andy Hung1bc088a2018-02-09 15:57:31 -08005351// isTrackAllowed_l() must be called with ThreadBase::mLock held
5352bool AudioFlinger::MixerThread::isTrackAllowed_l(
5353 audio_channel_mask_t channelMask, audio_format_t format,
5354 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005355{
Andy Hung1bc088a2018-02-09 15:57:31 -08005356 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5357 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005358 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005359 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005360 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005361 ALOGW("%s: invalid format: %#x", __func__, format);
5362 return false;
5363 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005364 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005365 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5366 return false;
5367 }
5368 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005369}
5370
Eric Laurent10351942014-05-08 18:49:52 -07005371// checkForNewParameter_l() must be called with ThreadBase::mLock held
5372bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5373 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005374{
Eric Laurent81784c32012-11-19 14:55:58 -08005375 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005376 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005377
Eric Laurent10351942014-05-08 18:49:52 -07005378 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005379
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005380 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005381
Eric Laurent10351942014-05-08 18:49:52 -07005382 AudioParameter param = AudioParameter(keyValuePair);
5383 int value;
5384 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5385 reconfig = true;
5386 }
5387 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005388 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005389 status = BAD_VALUE;
5390 } else {
5391 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005392 reconfig = true;
5393 }
Eric Laurent10351942014-05-08 18:49:52 -07005394 }
5395 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005396 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005397 status = BAD_VALUE;
5398 } else {
5399 // no need to save value, since it's constant
5400 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005401 }
Eric Laurent10351942014-05-08 18:49:52 -07005402 }
5403 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5404 // do not accept frame count changes if tracks are open as the track buffer
5405 // size depends on frame count and correct behavior would not be guaranteed
5406 // if frame count is changed after track creation
5407 if (!mTracks.isEmpty()) {
5408 status = INVALID_OPERATION;
5409 } else {
5410 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005411 }
Eric Laurent10351942014-05-08 18:49:52 -07005412 }
5413 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005414 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005415 }
Eric Laurent81784c32012-11-19 14:55:58 -08005416
Eric Laurent10351942014-05-08 18:49:52 -07005417 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005418 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005419 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005420 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005421 mStandby = true;
5422 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005423 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005424 }
Eric Laurent10351942014-05-08 18:49:52 -07005425 if (status == NO_ERROR && reconfig) {
5426 readOutputParameters_l();
5427 delete mAudioMixer;
5428 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005429 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005430 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005431 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005432 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005433 track->mChannelMask,
5434 track->mFormat,
5435 track->mSessionId);
5436 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005437 "%s(): AudioMixer cannot create track(%d)"
5438 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005439 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005440 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005441 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005442 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005443 }
Eric Laurent81784c32012-11-19 14:55:58 -08005444 }
5445
Eric Laurent42537be2016-01-08 17:16:42 -08005446 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005447}
5448
5449
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005450void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005451{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005452 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005453 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005454 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005455 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005456 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5457 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5458 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005459 if (hasFastMixer()) {
5460 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5461
5462 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5463 // while we are dumping it. It may be inconsistent, but it won't mutate!
5464 // This is a large object so we place it on the heap.
5465 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005466 const std::unique_ptr<FastMixerDumpState> copy =
5467 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005468 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005469
5470#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005471 // Similar for state queue
5472 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5473 observerCopy.dump(fd);
5474 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5475 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005476#endif
5477
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005478#ifdef AUDIO_WATCHDOG
5479 if (mAudioWatchdog != 0) {
5480 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5481 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5482 wdCopy.dump(fd);
5483 }
5484#endif
5485
5486 } else {
5487 dprintf(fd, " No FastMixer\n");
5488 }
Eric Laurent81784c32012-11-19 14:55:58 -08005489}
5490
5491uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5492{
5493 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5494}
5495
5496uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5497{
5498 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5499}
5500
5501void AudioFlinger::MixerThread::cacheParameters_l()
5502{
5503 PlaybackThread::cacheParameters_l();
5504
5505 // FIXME: Relaxed timing because of a certain device that can't meet latency
5506 // Should be reduced to 2x after the vendor fixes the driver issue
5507 // increase threshold again due to low power audio mode. The way this warning
5508 // threshold is calculated and its usefulness should be reconsidered anyway.
5509 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5510}
5511
5512// ----------------------------------------------------------------------------
5513
5514AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07005515 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5516 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005517{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005518 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005519}
5520
Eric Laurent81784c32012-11-19 14:55:58 -08005521AudioFlinger::DirectOutputThread::~DirectOutputThread()
5522{
5523}
5524
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005525void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005526{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005527 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005528 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5529 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5530}
5531
5532void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5533{
5534 Mutex::Autolock _l(mLock);
5535 if (mMasterBalance != balance) {
5536 mMasterBalance.store(balance);
5537 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5538 broadcast_l();
5539 }
5540}
5541
Eric Laurent5850c4c2016-11-10 13:04:31 -08005542void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005543{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005544 float left, right;
5545
Andy Hung333ab962019-05-28 20:23:35 -07005546 // Ensure volumeshaper state always advances even when muted.
5547 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5548 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5549 proxy->framesReleased());
5550 mVolumeShaperActive = shaperActive;
5551
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005552 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005553 left = right = 0;
5554 } else {
5555 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005556 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005557
Glenn Kastenc56f3422014-03-21 17:53:17 -07005558 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5559 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5560 if (left > GAIN_FLOAT_UNITY) {
5561 left = GAIN_FLOAT_UNITY;
5562 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005563 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005564 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5565 if (right > GAIN_FLOAT_UNITY) {
5566 right = GAIN_FLOAT_UNITY;
5567 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005568 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005569 }
5570
5571 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005572 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005573 if (left != mLeftVolFloat || right != mRightVolFloat) {
5574 mLeftVolFloat = left;
5575 mRightVolFloat = right;
5576
Eric Laurentbfb1b832013-01-07 09:53:42 -08005577 // Delegate volume control to effect in track effect chain if needed
5578 // only one effect chain can be present on DirectOutputThread, so if
5579 // there is one, the track is connected to it
5580 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005581 // if effect chain exists, volume is handled by it.
5582 // Convert volumes from float to 8.24
5583 uint32_t vl = (uint32_t)(left * (1 << 24));
5584 uint32_t vr = (uint32_t)(right * (1 << 24));
5585 // Direct/Offload effect chains set output volume in setVolume_l().
5586 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5587 } else {
5588 // otherwise we directly set the volume.
5589 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005590 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005591 }
5592 }
5593}
5594
Phil Burk43b4dcc2015-06-09 16:53:44 -07005595void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5596{
5597 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005598 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005599
Eric Laurent0f0631e2015-07-06 18:01:25 -07005600 if (previousTrack != 0 && latestTrack != 0) {
5601 if (mType == DIRECT) {
5602 if (previousTrack.get() != latestTrack.get()) {
5603 mFlushPending = true;
5604 }
5605 } else /* mType == OFFLOAD */ {
5606 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5607 mFlushPending = true;
5608 }
5609 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005610 } else if (previousTrack == 0) {
5611 // there could be an old track added back during track transition for direct
5612 // output, so always issues flush to flush data of the previous track if it
5613 // was already destroyed with HAL paused, then flush can resume the playback
5614 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005615 }
5616 PlaybackThread::onAddNewTrack_l();
5617}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005618
Eric Laurent81784c32012-11-19 14:55:58 -08005619AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5620 Vector< sp<Track> > *tracksToRemove
5621)
5622{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005623 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005624 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005625 bool doHwPause = false;
5626 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005627
5628 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005629 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005630 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005631 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005632 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005633 continue;
5634 }
5635
Eric Laurent5850c4c2016-11-10 13:04:31 -08005636 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005637#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005638 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005639#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005640 // Only consider last track started for volume and mixer state control.
5641 // In theory an older track could underrun and restart after the new one starts
5642 // but as we only care about the transition phase between two tracks on a
5643 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005644 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005645 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005646
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005647 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005648 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005649 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005650 doHwPause = true;
5651 mHwPaused = true;
5652 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005653 } else if (track->isFlushPending()) {
5654 track->flushAck();
5655 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005656 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005657 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005658 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005659 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005660 if (last) {
5661 mLeftVolFloat = mRightVolFloat = -1.0;
5662 if (mHwPaused) {
5663 doHwResume = true;
5664 mHwPaused = false;
5665 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005666 }
5667 }
5668
Eric Laurent81784c32012-11-19 14:55:58 -08005669 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005670 // for all its buffers to be filled before processing it.
5671 // Allow draining the buffer in case the client
5672 // app does not call stop() and relies on underrun to stop:
5673 // hence the test on (track->mRetryCount > 1).
5674 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005675 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005676 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005677 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005678 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005679 minFrames = mNormalFrameCount;
5680 } else {
5681 minFrames = 1;
5682 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005683
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005684 const size_t framesReady = track->framesReady();
5685 const int trackId = track->id();
5686 if (ATRACE_ENABLED()) {
5687 std::string traceName("nRdy");
5688 traceName += std::to_string(trackId);
5689 ATRACE_INT(traceName.c_str(), framesReady);
5690 }
5691 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07005692 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005693 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005694 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005695
5696 if (track->mFillingUpStatus == Track::FS_FILLED) {
5697 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005698 if (last) {
5699 // make sure processVolume_l() will apply new volume even if 0
5700 mLeftVolFloat = mRightVolFloat = -1.0;
5701 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005702 if (!mHwSupportsPause) {
5703 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005704 }
5705 }
5706
5707 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005708 processVolume_l(track, last);
5709 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005710 sp<Track> previousTrack = mPreviousTrack.promote();
5711 if (previousTrack != 0) {
5712 if (track != previousTrack.get()) {
5713 // Flush any data still being written from last track
5714 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005715 // Invalidate previous track to force a seek when resuming.
5716 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005717 }
5718 }
5719 mPreviousTrack = track;
5720
Eric Laurentd595b7c2013-04-03 17:27:56 -07005721 // reset retry count
5722 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005723 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005724 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005725 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005726 doHwResume = true;
5727 mHwPaused = false;
5728 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005729 }
Eric Laurent81784c32012-11-19 14:55:58 -08005730 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005731 // clear effect chain input buffer if the last active track started underruns
5732 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005733 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005734 mEffectChains[0]->clearInputBuffer();
5735 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005736 if (track->isStopping_1()) {
5737 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005738 if (last && mHwPaused) {
5739 doHwResume = true;
5740 mHwPaused = false;
5741 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005742 }
5743 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5744 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005745 // We have consumed all the buffers of this track.
5746 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005747 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005748 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005749 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5750 } else {
5751 audioHALFrames = 0;
5752 }
5753
Andy Hung818e7a32016-02-16 18:08:07 -08005754 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005755 if (mStandby || !last ||
Aniket Kumar Lata179a0742019-01-30 14:16:16 -08005756 track->presentationComplete(framesWritten, audioHALFrames) ||
Jindong32dc26e2019-11-11 18:10:01 +08005757 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005758 if (track->isStopping_2()) {
5759 track->mState = TrackBase::STOPPED;
5760 }
Eric Laurent81784c32012-11-19 14:55:58 -08005761 if (track->isStopped()) {
5762 track->reset();
5763 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005764 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005765 }
5766 } else {
5767 // No buffers for this track. Give it a few chances to
5768 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005769 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005770 if (--(track->mRetryCount) <= 0) {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005771 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07005772 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005773 // indicate to client process that the track was disabled because of underrun;
5774 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005775 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005776 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005777 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5778 "minFrames = %u, mFormat = %#x",
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07005779 framesReady, minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005780 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005781 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005782 doHwPause = true;
5783 mHwPaused = true;
5784 }
Eric Laurent81784c32012-11-19 14:55:58 -08005785 }
5786 }
5787 }
5788 }
5789
Eric Laurentd1f69b02014-12-15 14:33:13 -08005790 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005791 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005792 for (size_t i = 0; i < mTracks.size(); i++) {
5793 if (mTracks[i]->isFlushPending()) {
5794 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005795 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005796 }
5797 }
5798 }
5799
5800 // make sure the pause/flush/resume sequence is executed in the right order.
5801 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5802 // before flush and then resume HW. This can happen in case of pause/flush/resume
5803 // if resume is received before pause is executed.
5804 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005805 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005806 status_t result = mOutput->stream->pause();
5807 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005808 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005809 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005810 flushHw_l();
5811 }
5812 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005813 status_t result = mOutput->stream->resume();
5814 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005815 }
Eric Laurent81784c32012-11-19 14:55:58 -08005816 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005817 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005818
5819 return mixerStatus;
5820}
5821
5822void AudioFlinger::DirectOutputThread::threadLoop_mix()
5823{
Eric Laurent81784c32012-11-19 14:55:58 -08005824 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005825 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005826 // output audio to hardware
5827 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005828 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005829 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005830 status_t status = mActiveTrack->getNextBuffer(&buffer);
5831 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005832 // no need to pad with 0 for compressed audio
5833 if (audio_has_proportional_frames(mFormat)) {
5834 memset(curBuf, 0, frameCount * mFrameSize);
5835 }
Eric Laurent81784c32012-11-19 14:55:58 -08005836 break;
5837 }
5838 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5839 frameCount -= buffer.frameCount;
5840 curBuf += buffer.frameCount * mFrameSize;
5841 mActiveTrack->releaseBuffer(&buffer);
5842 }
Andy Hung2098f272014-02-27 14:00:06 -08005843 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005844 mSleepTimeUs = 0;
5845 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005846 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005847}
5848
5849void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5850{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005851 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005852 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005853 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005854 return;
5855 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005856 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005857 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005858 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005859 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005860 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005861 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005862 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005863 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005864 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005865 }
5866}
5867
Eric Laurentd1f69b02014-12-15 14:33:13 -08005868void AudioFlinger::DirectOutputThread::threadLoop_exit()
5869{
5870 {
5871 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005872 for (size_t i = 0; i < mTracks.size(); i++) {
5873 if (mTracks[i]->isFlushPending()) {
5874 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005875 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005876 }
5877 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005878 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005879 flushHw_l();
5880 }
5881 }
5882 PlaybackThread::threadLoop_exit();
5883}
5884
5885// must be called with thread mutex locked
5886bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5887{
5888 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005889 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005890
vivek mehta9cd7ad12016-03-17 00:18:29 -07005891 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5892 return !mStandby;
5893 }
5894
Eric Laurentd1f69b02014-12-15 14:33:13 -08005895 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5896 // after a timeout and we will enter standby then.
5897 if (mTracks.size() > 0) {
5898 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005899 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5900 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005901 }
5902
Eric Laurent5cff4032015-05-26 13:49:58 -07005903 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005904}
5905
Eric Laurent10351942014-05-08 18:49:52 -07005906// checkForNewParameter_l() must be called with ThreadBase::mLock held
5907bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5908 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005909{
5910 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005911 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005912
Eric Laurent10351942014-05-08 18:49:52 -07005913 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005914
Eric Laurent10351942014-05-08 18:49:52 -07005915 AudioParameter param = AudioParameter(keyValuePair);
5916 int value;
5917 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005918 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08005919 }
Eric Laurent10351942014-05-08 18:49:52 -07005920 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5921 // do not accept frame count changes if tracks are open as the track buffer
5922 // size depends on frame count and correct behavior would not be garantied
5923 // if frame count is changed after track creation
5924 if (!mTracks.isEmpty()) {
5925 status = INVALID_OPERATION;
5926 } else {
5927 reconfig = true;
5928 }
5929 }
5930 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005931 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005932 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005933 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005934 mStandby = true;
5935 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005936 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005937 }
5938 if (status == NO_ERROR && reconfig) {
5939 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005940 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005941 }
5942 }
5943
Eric Laurent42537be2016-01-08 17:16:42 -08005944 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005945}
5946
5947uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5948{
5949 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005950 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005951 time = PlaybackThread::activeSleepTimeUs();
5952 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005953 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005954 }
5955 return time;
5956}
5957
5958uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5959{
5960 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005961 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005962 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5963 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005964 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005965 }
5966 return time;
5967}
5968
5969uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5970{
5971 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005972 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005973 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5974 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005975 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005976 }
5977 return time;
5978}
5979
5980void AudioFlinger::DirectOutputThread::cacheParameters_l()
5981{
5982 PlaybackThread::cacheParameters_l();
5983
5984 // use shorter standby delay as on normal output to release
5985 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005986 // no delay on outputs with HW A/V sync
5987 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005988 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005989 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005990 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005991 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005992 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005993 }
Eric Laurent81784c32012-11-19 14:55:58 -08005994}
5995
Eric Laurente659ef42014-09-29 13:06:46 -07005996void AudioFlinger::DirectOutputThread::flushHw_l()
5997{
Phil Burk062e67a2015-02-11 13:40:50 -08005998 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005999 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006000 mFlushPending = false;
Andy Hungf3234512018-07-03 14:51:47 -07006001 mTimestampVerifier.discontinuity(); // DIRECT and OFFLOADED flush resets frame count.
Eric Laurente659ef42014-09-29 13:06:46 -07006002}
6003
Andy Hung10cbff12017-02-21 17:30:14 -08006004int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6005 // If a VolumeShaper is active, we must wake up periodically to update volume.
6006 const int64_t NS_PER_MS = 1000000;
6007 return mVolumeShaperActive ?
6008 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6009}
6010
Eric Laurent81784c32012-11-19 14:55:58 -08006011// ----------------------------------------------------------------------------
6012
Eric Laurentbfb1b832013-01-07 09:53:42 -08006013AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006014 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006015 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006016 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006017 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006018 mDrainSequence(0),
6019 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006020{
6021}
6022
6023AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6024{
6025}
6026
6027void AudioFlinger::AsyncCallbackThread::onFirstRef()
6028{
6029 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6030}
6031
6032bool AudioFlinger::AsyncCallbackThread::threadLoop()
6033{
6034 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006035 uint32_t writeAckSequence;
6036 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006037 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006038
6039 {
6040 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006041 while (!((mWriteAckSequence & 1) ||
6042 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006043 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006044 exitPending())) {
6045 mWaitWorkCV.wait(mLock);
6046 }
6047
Eric Laurentbfb1b832013-01-07 09:53:42 -08006048 if (exitPending()) {
6049 break;
6050 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006051 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6052 mWriteAckSequence, mDrainSequence);
6053 writeAckSequence = mWriteAckSequence;
6054 mWriteAckSequence &= ~1;
6055 drainSequence = mDrainSequence;
6056 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006057 asyncError = mAsyncError;
6058 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006059 }
6060 {
Eric Laurent4de95592013-09-26 15:28:21 -07006061 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6062 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006063 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006064 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006065 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006066 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006067 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006068 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006069 if (asyncError) {
6070 playbackThread->onAsyncError();
6071 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006072 }
6073 }
6074 }
6075 return false;
6076}
6077
6078void AudioFlinger::AsyncCallbackThread::exit()
6079{
6080 ALOGV("AsyncCallbackThread::exit");
6081 Mutex::Autolock _l(mLock);
6082 requestExit();
6083 mWaitWorkCV.broadcast();
6084}
6085
Eric Laurent3b4529e2013-09-05 18:09:19 -07006086void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006087{
6088 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006089 // bit 0 is cleared
6090 mWriteAckSequence = sequence << 1;
6091}
6092
6093void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6094{
6095 Mutex::Autolock _l(mLock);
6096 // ignore unexpected callbacks
6097 if (mWriteAckSequence & 2) {
6098 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006099 mWaitWorkCV.signal();
6100 }
6101}
6102
Eric Laurent3b4529e2013-09-05 18:09:19 -07006103void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006104{
6105 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006106 // bit 0 is cleared
6107 mDrainSequence = sequence << 1;
6108}
6109
6110void AudioFlinger::AsyncCallbackThread::resetDraining()
6111{
6112 Mutex::Autolock _l(mLock);
6113 // ignore unexpected callbacks
6114 if (mDrainSequence & 2) {
6115 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006116 mWaitWorkCV.signal();
6117 }
6118}
6119
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006120void AudioFlinger::AsyncCallbackThread::setAsyncError()
6121{
6122 Mutex::Autolock _l(mLock);
6123 mAsyncError = true;
6124 mWaitWorkCV.signal();
6125}
6126
Eric Laurentbfb1b832013-01-07 09:53:42 -08006127
6128// ----------------------------------------------------------------------------
6129AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006130 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6131 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006132 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6133 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006134{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006135 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006136 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006137 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006138}
6139
Eric Laurentbfb1b832013-01-07 09:53:42 -08006140void AudioFlinger::OffloadThread::threadLoop_exit()
6141{
6142 if (mFlushPending || mHwPaused) {
6143 // If a flush is pending or track was paused, just discard buffered data
6144 flushHw_l();
6145 } else {
6146 mMixerStatus = MIXER_DRAIN_ALL;
6147 threadLoop_drain();
6148 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006149 if (mUseAsyncWrite) {
6150 ALOG_ASSERT(mCallbackThread != 0);
6151 mCallbackThread->exit();
6152 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006153 PlaybackThread::threadLoop_exit();
6154}
6155
6156AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6157 Vector< sp<Track> > *tracksToRemove
6158)
6159{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006160 size_t count = mActiveTracks.size();
6161
6162 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006163 bool doHwPause = false;
6164 bool doHwResume = false;
6165
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006166 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006167
Eric Laurentbfb1b832013-01-07 09:53:42 -08006168 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006169 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006170 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006171#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006172 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006173#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006174 // Only consider last track started for volume and mixer state control.
6175 // In theory an older track could underrun and restart after the new one starts
6176 // but as we only care about the transition phase between two tracks on a
6177 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006178 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006179 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006180
Haynes Mathew George7844f672014-01-15 12:32:55 -08006181 if (track->isInvalid()) {
6182 ALOGW("An invalidated track shouldn't be in active list");
6183 tracksToRemove->add(track);
6184 continue;
6185 }
6186
6187 if (track->mState == TrackBase::IDLE) {
6188 ALOGW("An idle track shouldn't be in active list");
6189 continue;
6190 }
6191
Eric Laurentbfb1b832013-01-07 09:53:42 -08006192 if (track->isPausing()) {
6193 track->setPaused();
6194 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006195 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006196 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006197 mHwPaused = true;
6198 }
6199 // If we were part way through writing the mixbuffer to
6200 // the HAL we must save this until we resume
6201 // BUG - this will be wrong if a different track is made active,
6202 // in that case we want to discard the pending data in the
6203 // mixbuffer and tell the client to present it again when the
6204 // track is resumed
6205 mPausedWriteLength = mCurrentWriteLength;
6206 mPausedBytesRemaining = mBytesRemaining;
6207 mBytesRemaining = 0; // stop writing
6208 }
6209 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006210 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006211 if (track->isStopping_1()) {
6212 track->mRetryCount = kMaxTrackStopRetriesOffload;
6213 } else {
6214 track->mRetryCount = kMaxTrackRetriesOffload;
6215 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006216 track->flushAck();
6217 if (last) {
6218 mFlushPending = true;
6219 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006220 } else if (track->isResumePending()){
6221 track->resumeAck();
6222 if (last) {
6223 if (mPausedBytesRemaining) {
6224 // Need to continue write that was interrupted
6225 mCurrentWriteLength = mPausedWriteLength;
6226 mBytesRemaining = mPausedBytesRemaining;
6227 mPausedBytesRemaining = 0;
6228 }
6229 if (mHwPaused) {
6230 doHwResume = true;
6231 mHwPaused = false;
6232 // threadLoop_mix() will handle the case that we need to
6233 // resume an interrupted write
6234 }
6235 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006236 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006237
Eric Laurent3df841a2016-07-15 15:15:40 -07006238 mLeftVolFloat = mRightVolFloat = -1.0;
6239
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006240 // Do not handle new data in this iteration even if track->framesReady()
6241 mixerStatus = MIXER_TRACKS_ENABLED;
6242 }
6243 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006244 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006245 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006246 if (track->mFillingUpStatus == Track::FS_FILLED) {
6247 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006248 if (last) {
6249 // make sure processVolume_l() will apply new volume even if 0
6250 mLeftVolFloat = mRightVolFloat = -1.0;
6251 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006252 }
6253
6254 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006255 sp<Track> previousTrack = mPreviousTrack.promote();
6256 if (previousTrack != 0) {
6257 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006258 // Flush any data still being written from last track
6259 mBytesRemaining = 0;
6260 if (mPausedBytesRemaining) {
6261 // Last track was paused so we also need to flush saved
6262 // mixbuffer state and invalidate track so that it will
6263 // re-submit that unwritten data when it is next resumed
6264 mPausedBytesRemaining = 0;
6265 // Invalidate is a bit drastic - would be more efficient
6266 // to have a flag to tell client that some of the
6267 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006268 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006269 }
6270 // flush data already sent to the DSP if changing audio session as audio
6271 // comes from a different source. Also invalidate previous track to force a
6272 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006273 if (previousTrack->sessionId() != track->sessionId()) {
6274 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006275 }
6276 }
6277 }
6278 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006279 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006280 if (track->isStopping_1()) {
6281 track->mRetryCount = kMaxTrackStopRetriesOffload;
6282 } else {
6283 track->mRetryCount = kMaxTrackRetriesOffload;
6284 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006285 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006286 mixerStatus = MIXER_TRACKS_READY;
6287 }
6288 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006289 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006290 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006291 if (--(track->mRetryCount) <= 0) {
6292 // Hardware buffer can hold a large amount of audio so we must
6293 // wait for all current track's data to drain before we say
6294 // that the track is stopped.
6295 if (mBytesRemaining == 0) {
6296 // Only start draining when all data in mixbuffer
6297 // has been written
6298 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6299 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6300 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6301 if (last && !mStandby) {
6302 // do not modify drain sequence if we are already draining. This happens
6303 // when resuming from pause after drain.
6304 if ((mDrainSequence & 1) == 0) {
6305 mSleepTimeUs = 0;
6306 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6307 mixerStatus = MIXER_DRAIN_TRACK;
6308 mDrainSequence += 2;
6309 }
6310 if (mHwPaused) {
6311 // It is possible to move from PAUSED to STOPPING_1 without
6312 // a resume so we must ensure hardware is running
6313 doHwResume = true;
6314 mHwPaused = false;
6315 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006316 }
6317 }
Eric Laurente93cc032016-05-05 10:15:10 -07006318 } else if (last) {
6319 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6320 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006321 }
6322 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006323 // Drain has completed or we are in standby, signal presentation complete
6324 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006325 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006326 uint32_t latency = 0;
6327 status_t result = mOutput->stream->getLatency(&latency);
6328 ALOGE_IF(result != OK,
6329 "Error when retrieving output stream latency: %d", result);
6330 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006331 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006332 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006333 track->presentationComplete(framesWritten, audioHALFrames);
6334 track->reset();
6335 tracksToRemove->add(track);
Andy Hungf3234512018-07-03 14:51:47 -07006336 // DIRECT and OFFLOADED stop resets frame counts.
6337 if (!mUseAsyncWrite) {
6338 // If we don't get explicit drain notification we must
6339 // register discontinuity regardless of whether this is
6340 // the previous (!last) or the upcoming (last) track
6341 // to avoid skipping the discontinuity.
6342 mTimestampVerifier.discontinuity();
6343 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006344 }
6345 } else {
6346 // No buffers for this track. Give it a few chances to
6347 // fill a buffer, then remove it from active list.
6348 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006349 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006350 uint64_t position = 0;
6351 struct timespec unused;
6352 // The running check restarts the retry counter at least once.
6353 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6354 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6355 running = true;
6356 mOffloadUnderrunPosition = position;
6357 }
6358 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006359 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6360 (long long)position, (long long)mOffloadUnderrunPosition);
6361 }
6362 if (running) { // still running, give us more time.
6363 track->mRetryCount = kMaxTrackRetriesOffload;
6364 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006365 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6366 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006367 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006368 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006369 // it will then automatically call start() when data is available
6370 track->disable();
6371 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006372 } else if (last){
6373 mixerStatus = MIXER_TRACKS_ENABLED;
6374 }
6375 }
6376 }
6377 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006378 if (track->isReady()) { // check ready to prevent premature start.
6379 processVolume_l(track, last);
6380 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006381 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006382
Eric Laurentea0fade2013-10-04 16:23:48 -07006383 // make sure the pause/flush/resume sequence is executed in the right order.
6384 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6385 // before flush and then resume HW. This can happen in case of pause/flush/resume
6386 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006387 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006388 status_t result = mOutput->stream->pause();
6389 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006390 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006391 if (mFlushPending) {
6392 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006393 }
Eric Laurentfd477972013-10-25 18:10:40 -07006394 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006395 status_t result = mOutput->stream->resume();
6396 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006397 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006398
Eric Laurentbfb1b832013-01-07 09:53:42 -08006399 // remove all the tracks that need to be...
6400 removeTracks_l(*tracksToRemove);
6401
6402 return mixerStatus;
6403}
6404
Eric Laurentbfb1b832013-01-07 09:53:42 -08006405// must be called with thread mutex locked
6406bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6407{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006408 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6409 mWriteAckSequence, mDrainSequence);
6410 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006411 return true;
6412 }
6413 return false;
6414}
6415
Eric Laurentbfb1b832013-01-07 09:53:42 -08006416bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6417{
6418 Mutex::Autolock _l(mLock);
6419 return waitingAsyncCallback_l();
6420}
6421
6422void AudioFlinger::OffloadThread::flushHw_l()
6423{
Eric Laurente659ef42014-09-29 13:06:46 -07006424 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006425 // Flush anything still waiting in the mixbuffer
6426 mCurrentWriteLength = 0;
6427 mBytesRemaining = 0;
6428 mPausedWriteLength = 0;
6429 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006430 // reset bytes written count to reflect that DSP buffers are empty after flush.
6431 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006432 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006433
Eric Laurentbfb1b832013-01-07 09:53:42 -08006434 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006435 // discard any pending drain or write ack by incrementing sequence
6436 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6437 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006438 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006439 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6440 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006441 }
6442}
6443
Haynes Mathew George05317d22016-05-03 16:34:26 -07006444void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6445{
6446 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006447 if (PlaybackThread::invalidateTracks_l(streamType)) {
6448 mFlushPending = true;
6449 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006450}
6451
Eric Laurentbfb1b832013-01-07 09:53:42 -08006452// ----------------------------------------------------------------------------
6453
Eric Laurent81784c32012-11-19 14:55:58 -08006454AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006455 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07006456 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006457 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006458 mWaitTimeMs(UINT_MAX)
6459{
6460 addOutputTrack(mainThread);
6461}
6462
6463AudioFlinger::DuplicatingThread::~DuplicatingThread()
6464{
6465 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6466 mOutputTracks[i]->destroy();
6467 }
6468}
6469
6470void AudioFlinger::DuplicatingThread::threadLoop_mix()
6471{
6472 // mix buffers...
6473 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006474 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006475 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006476 if (mMixerBufferValid) {
6477 memset(mMixerBuffer, 0, mMixerBufferSize);
6478 } else {
6479 memset(mSinkBuffer, 0, mSinkBufferSize);
6480 }
Eric Laurent81784c32012-11-19 14:55:58 -08006481 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006482 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006483 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006484 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006485 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006486}
6487
6488void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6489{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006490 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006491 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006492 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006493 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006494 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006495 }
6496 } else if (mBytesWritten != 0) {
6497 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6498 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006499 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006500 } else {
6501 // flush remaining overflow buffers in output tracks
6502 writeFrames = 0;
6503 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006504 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006505 }
6506}
6507
Eric Laurentbfb1b832013-01-07 09:53:42 -08006508ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006509{
6510 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006511 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6512
6513 // Consider the first OutputTrack for timestamp and frame counting.
6514
6515 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6516 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6517 // we always claim success.
6518 if (i == 0) {
6519 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6520 ALOGD_IF(correction != 0 && writeFrames != 0,
6521 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6522 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6523 mFramesWritten -= correction;
6524 }
6525
6526 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006527 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006528 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006529 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006530}
6531
6532void AudioFlinger::DuplicatingThread::threadLoop_standby()
6533{
6534 // DuplicatingThread implements standby by stopping all tracks
6535 for (size_t i = 0; i < outputTracks.size(); i++) {
6536 outputTracks[i]->stop();
6537 }
6538}
6539
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006540void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006541{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006542 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006543
6544 std::stringstream ss;
6545 const size_t numTracks = mOutputTracks.size();
6546 ss << " " << numTracks << " OutputTracks";
6547 if (numTracks > 0) {
6548 ss << ":";
6549 for (const auto &track : mOutputTracks) {
6550 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006551 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006552 if (thread.get() != nullptr) {
6553 ss << thread.get() << ", " << thread->id();
6554 } else {
6555 ss << "null";
6556 }
6557 ss << ")";
6558 }
6559 }
6560 ss << "\n";
6561 std::string result = ss.str();
6562 write(fd, result.c_str(), result.size());
6563}
6564
Eric Laurent81784c32012-11-19 14:55:58 -08006565void AudioFlinger::DuplicatingThread::saveOutputTracks()
6566{
6567 outputTracks = mOutputTracks;
6568}
6569
6570void AudioFlinger::DuplicatingThread::clearOutputTracks()
6571{
6572 outputTracks.clear();
6573}
6574
6575void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6576{
6577 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006578 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6579 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6580 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6581 const size_t frameCount =
6582 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6583 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6584 // from different OutputTracks and their associated MixerThreads (e.g. one may
6585 // nearly empty and the other may be dropping data).
6586
6587 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006588 this,
6589 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006590 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006591 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006592 frameCount,
6593 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006594 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6595 if (status != NO_ERROR) {
6596 ALOGE("addOutputTrack() initCheck failed %d", status);
6597 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006598 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006599 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6600 mOutputTracks.add(outputTrack);
6601 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6602 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006603}
6604
6605void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6606{
6607 Mutex::Autolock _l(mLock);
6608 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6609 if (mOutputTracks[i]->thread() == thread) {
6610 mOutputTracks[i]->destroy();
6611 mOutputTracks.removeAt(i);
6612 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006613 if (thread->getOutput() == mOutput) {
6614 mOutput = NULL;
6615 }
Eric Laurent81784c32012-11-19 14:55:58 -08006616 return;
6617 }
6618 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006619 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006620}
6621
6622// caller must hold mLock
6623void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6624{
6625 mWaitTimeMs = UINT_MAX;
6626 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6627 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6628 if (strong != 0) {
6629 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6630 if (waitTimeMs < mWaitTimeMs) {
6631 mWaitTimeMs = waitTimeMs;
6632 }
6633 }
6634 }
6635}
6636
6637
6638bool AudioFlinger::DuplicatingThread::outputsReady(
6639 const SortedVector< sp<OutputTrack> > &outputTracks)
6640{
6641 for (size_t i = 0; i < outputTracks.size(); i++) {
6642 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6643 if (thread == 0) {
6644 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6645 outputTracks[i].get());
6646 return false;
6647 }
6648 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6649 // see note at standby() declaration
6650 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6651 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6652 thread.get());
6653 return false;
6654 }
6655 }
6656 return true;
6657}
6658
Kevin Rocard12381092018-04-11 09:19:59 -07006659void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6660 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006661{
Kevin Rocard12381092018-04-11 09:19:59 -07006662 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6663 outputTrack->setMetadatas(metadata.tracks);
6664 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006665}
6666
Eric Laurent81784c32012-11-19 14:55:58 -08006667uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6668{
6669 return (mWaitTimeMs * 1000) / 2;
6670}
6671
6672void AudioFlinger::DuplicatingThread::cacheParameters_l()
6673{
6674 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6675 updateWaitTime_l();
6676
6677 MixerThread::cacheParameters_l();
6678}
6679
Eric Laurent6acd1d42017-01-04 14:23:29 -08006680
Eric Laurent81784c32012-11-19 14:55:58 -08006681// ----------------------------------------------------------------------------
6682// Record
6683// ----------------------------------------------------------------------------
6684
6685AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6686 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006687 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006688 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006689 ) :
jiabinc52b1ff2019-10-31 17:20:42 -07006690 ThreadBase(audioFlinger, id, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006691 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07006692 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006693 mActiveTracks(&this->mLocalLog),
6694 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006695 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006696 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006697 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6698 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006699 // mFastCapture below
6700 , mFastCaptureFutex(0)
6701 // mInputSource
6702 // mPipeSink
6703 // mPipeSource
6704 , mPipeFramesP2(0)
6705 // mPipeMemory
6706 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006707 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006708 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006709{
Glenn Kastend7dca052015-03-05 16:05:54 -08006710 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6711 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006712
Andy Hungc8fddf32018-08-08 18:32:37 -07006713 if (mInput != nullptr && mInput->audioHwDev != nullptr) {
6714 mIsMsdDevice = strcmp(
6715 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6716 }
6717
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006718 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006719
Andy Hungc8fddf32018-08-08 18:32:37 -07006720 // TODO: We may also match on address as well as device type for
6721 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07006722 // TODO: This property should be ensure that only contains one single device type.
6723 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
6724 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07006725 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
6726 : AUDIO_DEVICE_NONE));
6727
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006728 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006729 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006730 size_t numCounterOffers = 0;
6731 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006732#if !LOG_NDEBUG
6733 ssize_t index =
6734#else
6735 (void)
6736#endif
6737 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006738 ALOG_ASSERT(index == 0);
6739
6740 // initialize fast capture depending on configuration
6741 bool initFastCapture;
6742 switch (kUseFastCapture) {
6743 case FastCapture_Never:
6744 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006745 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006746 break;
6747 case FastCapture_Always:
6748 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006749 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006750 break;
6751 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006752 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006753 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6754 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6755 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006756 break;
6757 // case FastCapture_Dynamic:
6758 }
6759
6760 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006761 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006762 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006763 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6764 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006765 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006766 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006767 const sp<MemoryDealer> roHeap(readOnlyHeap());
6768 sp<IMemory> pipeMemory;
6769 if ((roHeap == 0) ||
6770 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07006771 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006772 ALOGE("not enough memory for pipe buffer size=%zu; "
6773 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6774 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6775 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006776 goto failed;
6777 }
6778 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6779 memset(pipeBuffer, 0, pipeSize);
6780 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6781 const NBAIO_Format offers[1] = {format};
6782 size_t numCounterOffers = 0;
6783 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6784 ALOG_ASSERT(index == 0);
6785 mPipeSink = pipe;
6786 PipeReader *pipeReader = new PipeReader(*pipe);
6787 numCounterOffers = 0;
6788 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6789 ALOG_ASSERT(index == 0);
6790 mPipeSource = pipeReader;
6791 mPipeFramesP2 = pipeFramesP2;
6792 mPipeMemory = pipeMemory;
6793
6794 // create fast capture
6795 mFastCapture = new FastCapture();
6796 FastCaptureStateQueue *sq = mFastCapture->sq();
6797#ifdef STATE_QUEUE_DUMP
6798 // FIXME
6799#endif
6800 FastCaptureState *state = sq->begin();
6801 state->mCblk = NULL;
6802 state->mInputSource = mInputSource.get();
6803 state->mInputSourceGen++;
6804 state->mPipeSink = pipe;
6805 state->mPipeSinkGen++;
6806 state->mFrameCount = mFrameCount;
6807 state->mCommand = FastCaptureState::COLD_IDLE;
6808 // already done in constructor initialization list
6809 //mFastCaptureFutex = 0;
6810 state->mColdFutexAddr = &mFastCaptureFutex;
6811 state->mColdGen++;
6812 state->mDumpState = &mFastCaptureDumpState;
6813#ifdef TEE_SINK
6814 // FIXME
6815#endif
6816 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6817 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6818 sq->end();
6819 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6820
6821 // start the fast capture
6822 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6823 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07006824 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006825 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006826#ifdef AUDIO_WATCHDOG
6827 // FIXME
6828#endif
6829
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006830 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006831 }
Andy Hung8946a282018-04-19 20:04:56 -07006832#ifdef TEE_SINK
6833 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
6834 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
6835#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006836failed: ;
6837
6838 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006839}
6840
Eric Laurent81784c32012-11-19 14:55:58 -08006841AudioFlinger::RecordThread::~RecordThread()
6842{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006843 if (mFastCapture != 0) {
6844 FastCaptureStateQueue *sq = mFastCapture->sq();
6845 FastCaptureState *state = sq->begin();
6846 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6847 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6848 if (old == -1) {
6849 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6850 }
6851 }
6852 state->mCommand = FastCaptureState::EXIT;
6853 sq->end();
6854 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6855 mFastCapture->join();
6856 mFastCapture.clear();
6857 }
6858 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006859 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006860 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006861}
6862
6863void AudioFlinger::RecordThread::onFirstRef()
6864{
Glenn Kastend7dca052015-03-05 16:05:54 -08006865 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006866}
6867
Eric Laurent555530a2017-02-07 18:17:24 -08006868void AudioFlinger::RecordThread::preExit()
6869{
6870 ALOGV(" preExit()");
6871 Mutex::Autolock _l(mLock);
6872 for (size_t i = 0; i < mTracks.size(); i++) {
6873 sp<RecordTrack> track = mTracks[i];
6874 track->invalidate();
6875 }
6876 mActiveTracks.clear();
6877 mStartStopCond.broadcast();
6878}
6879
Eric Laurent81784c32012-11-19 14:55:58 -08006880bool AudioFlinger::RecordThread::threadLoop()
6881{
Eric Laurent81784c32012-11-19 14:55:58 -08006882 nsecs_t lastWarning = 0;
6883
6884 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006885
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006886reacquire_wakelock:
6887 sp<RecordTrack> activeTrack;
6888 {
6889 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006890 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006891 }
6892
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006893 // used to request a deferred sleep, to be executed later while mutex is unlocked
6894 uint32_t sleepUs = 0;
6895
Andy Hung446f4df2019-02-21 12:26:41 -08006896 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
6897
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006898 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08006899 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006900 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006901
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006902 // activeTracks accumulates a copy of a subset of mActiveTracks
6903 Vector< sp<RecordTrack> > activeTracks;
6904
Glenn Kasten735f45f2014-08-18 15:51:59 -07006905 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006906 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006907
Glenn Kasten735f45f2014-08-18 15:51:59 -07006908 // reference to a fast track which is about to be removed
6909 sp<RecordTrack> fastTrackToRemove;
6910
Eric Laurent81784c32012-11-19 14:55:58 -08006911 { // scope for mLock
6912 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006913
Eric Laurent021cf962014-05-13 10:18:14 -07006914 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006915
Eric Laurent000a4192014-01-29 15:17:32 -08006916 // check exitPending here because checkForNewParameters_l() and
6917 // checkForNewParameters_l() can temporarily release mLock
6918 if (exitPending()) {
6919 break;
6920 }
6921
Eric Laurent5c25d562016-07-13 17:17:45 -07006922 // sleep with mutex unlocked
6923 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006924 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006925 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6926 ATRACE_END();
6927 sleepUs = 0;
6928 continue;
6929 }
6930
Glenn Kasten2b806402013-11-20 16:37:38 -08006931 // if no active track(s), then standby and release wakelock
6932 size_t size = mActiveTracks.size();
6933 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006934 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006935 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006936 releaseWakeLock_l();
6937 ALOGV("RecordThread: loop stopping");
6938 // go to sleep
6939 mWaitWorkCV.wait(mLock);
6940 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006941 goto reacquire_wakelock;
6942 }
6943
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006944 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006945 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006946 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006947
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006948 activeTrack = mActiveTracks[i];
6949 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006950 if (activeTrack->isFastTrack()) {
6951 ALOG_ASSERT(fastTrackToRemove == 0);
6952 fastTrackToRemove = activeTrack;
6953 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006954 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006955 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006956 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006957 continue;
6958 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006959
6960 TrackBase::track_state activeTrackState = activeTrack->mState;
6961 switch (activeTrackState) {
6962
6963 case TrackBase::PAUSING:
6964 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07006965 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006966 doBroadcast = true;
6967 size--;
6968 continue;
6969
6970 case TrackBase::STARTING_1:
6971 sleepUs = 10000;
6972 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006973 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006974 continue;
6975
6976 case TrackBase::STARTING_2:
6977 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006978 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006979 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006980 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006981 break;
6982
6983 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006984 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006985 break;
6986
Andy Hungce685402018-10-05 17:23:27 -07006987 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
6988 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
6989 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006990 default:
Andy Hungce685402018-10-05 17:23:27 -07006991 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
6992 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07006993 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006994
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006995 activeTracks.add(activeTrack);
6996 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006997
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006998 if (activeTrack->isFastTrack()) {
6999 ALOG_ASSERT(!mFastTrackAvail);
7000 ALOG_ASSERT(fastTrack == 0);
7001 fastTrack = activeTrack;
7002 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007003 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007004
Andy Hungdae27702016-10-31 14:01:16 -07007005 mActiveTracks.updatePowerState(this);
7006
Kevin Rocard069c2712018-03-29 19:09:14 -07007007 updateMetadata_l();
7008
Eric Laurent5c25d562016-07-13 17:17:45 -07007009 if (allStopped) {
7010 standbyIfNotAlreadyInStandby();
7011 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007012 if (doBroadcast) {
7013 mStartStopCond.broadcast();
7014 }
7015
7016 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007017 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007018 if (sleepUs == 0) {
7019 sleepUs = kRecordThreadSleepUs;
7020 }
7021 continue;
7022 }
7023 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007024
Eric Laurent81784c32012-11-19 14:55:58 -08007025 lockEffectChains_l(effectChains);
7026 }
7027
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007028 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007029
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007030 size_t size = effectChains.size();
7031 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007032 // thread mutex is not locked, but effect chain is locked
7033 effectChains[i]->process_l();
7034 }
7035
Glenn Kasten735f45f2014-08-18 15:51:59 -07007036 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007037 if (mFastCapture != 0) {
7038 FastCaptureStateQueue *sq = mFastCapture->sq();
7039 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007040 bool didModify = false;
7041 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007042 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7043 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7044 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7045 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7046 if (old == -1) {
7047 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7048 }
7049 }
7050 state->mCommand = FastCaptureState::READ_WRITE;
7051#if 0 // FIXME
7052 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007053 FastThreadDumpState::kSamplingNforLowRamDevice :
7054 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007055#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007056 didModify = true;
7057 }
7058 audio_track_cblk_t *cblkOld = state->mCblk;
7059 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7060 if (cblkNew != cblkOld) {
7061 state->mCblk = cblkNew;
7062 // block until acked if removing a fast track
7063 if (cblkOld != NULL) {
7064 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7065 }
7066 didModify = true;
7067 }
jiabin01c8f562018-07-19 17:47:28 -07007068 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7069 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7070 if (state->mFastPatchRecordBufferProvider != abp) {
7071 state->mFastPatchRecordBufferProvider = abp;
7072 state->mFastPatchRecordFormat = fastTrack == 0 ?
7073 AUDIO_FORMAT_INVALID : fastTrack->format();
7074 didModify = true;
7075 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007076 sq->end(didModify);
7077 if (didModify) {
7078 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007079#if 0
7080 if (kUseFastCapture == FastCapture_Dynamic) {
7081 mNormalSource = mPipeSource;
7082 }
7083#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007084 }
7085 }
7086
Glenn Kasten735f45f2014-08-18 15:51:59 -07007087 // now run the fast track destructor with thread mutex unlocked
7088 fastTrackToRemove.clear();
7089
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007090 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7091 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7092 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7093 // If destination is non-contiguous, first read past the nominal end of buffer, then
7094 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007095
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007096 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007097 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007098 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007099
7100 // If an NBAIO source is present, use it to read the normal capture's data
7101 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007102 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007103
7104 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7105 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7106 // we immediately retry the read() to get data and prevent another overflow.
7107 for (int retries = 0; retries <= 2; ++retries) {
7108 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7109 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7110 framesToRead);
7111 if (framesRead != OVERRUN) break;
7112 }
7113
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007114 const ssize_t availableToRead = mPipeSource->availableToRead();
7115 if (availableToRead >= 0) {
7116 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
7117 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7118 "more frames to read than fifo size, %zd > %zu",
7119 availableToRead, mPipeFramesP2);
7120 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7121 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7122 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7123 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007124 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7125 }
7126 if (framesRead < 0) {
7127 status_t status = (status_t) framesRead;
7128 switch (status) {
7129 case OVERRUN:
7130 ALOGW("overrun on read from pipe");
7131 framesRead = 0;
7132 break;
7133 case NEGOTIATE:
7134 ALOGE("re-negotiation is needed");
7135 framesRead = -1; // Will cause an attempt to recover.
7136 break;
7137 default:
7138 ALOGE("unknown error %d on read from pipe", status);
7139 break;
7140 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007141 }
7142 // otherwise use the HAL / AudioStreamIn directly
7143 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007144 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007145 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007146 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007147 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007148 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007149 if (result < 0) {
7150 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007151 } else {
7152 framesRead = bytesRead / mFrameSize;
7153 }
7154 }
7155
Andy Hung446f4df2019-02-21 12:26:41 -08007156 const int64_t lastIoEndNs = systemTime(); // end IO timing
7157
Andy Hung3f0c9022016-01-15 17:49:46 -08007158 // Update server timestamp with server stats
7159 // systemTime() is optional if the hardware supports timestamps.
7160 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007161 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
Andy Hung3f0c9022016-01-15 17:49:46 -08007162
7163 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007164 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007165 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007166 if (mStandby) {
7167 mTimestampVerifier.discontinuity();
Mikhail Naganov2534b382019-09-25 13:05:02 -07007168 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007169 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7170
7171 mTimestampVerifier.add(position, time, mSampleRate);
7172
7173 // Correct timestamps
7174 if (isTimestampCorrectionEnabled()) {
7175 ALOGV("TS_BEFORE: %d %lld %lld",
7176 id(), (long long)time, (long long)position);
7177 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7178 position = correctedTimestamp.mFrames;
7179 time = correctedTimestamp.mTimeNs;
7180 ALOGV("TS_AFTER: %d %lld %lld",
7181 id(), (long long)time, (long long)position);
7182 }
7183
Andy Hung3f0c9022016-01-15 17:49:46 -08007184 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7185 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7186 // Note: In general record buffers should tend to be empty in
7187 // a properly running pipeline.
7188 //
7189 // Also, it is not advantageous to call get_presentation_position during the read
7190 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007191 } else {
7192 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007193 }
7194 }
Andy Hunge6c37112019-02-26 17:38:10 -08007195
7196 // From the timestamp, input read latency is negative output write latency.
7197 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7198 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7199 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7200 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7201 mLatencyMs.add(latencyMs);
7202 }
7203
Andy Hung3f0c9022016-01-15 17:49:46 -08007204 // Use this to track timestamp information
7205 // ALOGD("%s", mTimestamp.toString().c_str());
7206
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007207 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007208 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007209 // Force input into standby so that it tries to recover at next read attempt
7210 inputStandBy();
7211 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007212 }
7213 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007214 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007215 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007216 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007217 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007218
Andy Hung8946a282018-04-19 20:04:56 -07007219#ifdef TEE_SINK
7220 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7221#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007222 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007223 {
7224 size_t part1 = mRsmpInFramesP2 - rear;
7225 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007226 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007227 (framesRead - part1) * mFrameSize);
7228 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007229 }
7230 rear = mRsmpInRear += framesRead;
7231
7232 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007233
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007234 // loop over each active track
7235 for (size_t i = 0; i < size; i++) {
7236 activeTrack = activeTracks[i];
7237
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007238 // skip fast tracks, as those are handled directly by FastCapture
7239 if (activeTrack->isFastTrack()) {
7240 continue;
7241 }
7242
Andy Hung73c02e42015-03-29 01:13:58 -07007243 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007244 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7245
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007246 enum {
7247 OVERRUN_UNKNOWN,
7248 OVERRUN_TRUE,
7249 OVERRUN_FALSE
7250 } overrun = OVERRUN_UNKNOWN;
7251
7252 // loop over getNextBuffer to handle circular sink
7253 for (;;) {
7254
7255 activeTrack->mSink.frameCount = ~0;
7256 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7257 size_t framesOut = activeTrack->mSink.frameCount;
7258 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7259
Andy Hung73c02e42015-03-29 01:13:58 -07007260 // check available frames and handle overrun conditions
7261 // if the record track isn't draining fast enough.
7262 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007263 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007264 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7265 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007266 overrun = OVERRUN_TRUE;
7267 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007268 if (framesOut == 0 || framesIn == 0) {
7269 break;
7270 }
7271
Andy Hung6770c6f2015-04-07 13:43:36 -07007272 // Don't allow framesOut to be larger than what is possible with resampling
7273 // from framesIn.
7274 // This isn't strictly necessary but helps limit buffer resizing in
7275 // RecordBufferConverter. TODO: remove when no longer needed.
7276 framesOut = min(framesOut,
7277 destinationFramesPossible(
7278 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007279
7280 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007281 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007282 // straight from RecordThread buffer to RecordTrack buffer.
7283 AudioBufferProvider::Buffer buffer;
7284 buffer.frameCount = framesOut;
7285 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7286 if (status == OK && buffer.frameCount != 0) {
7287 ALOGV_IF(buffer.frameCount != framesOut,
7288 "%s() read less than expected (%zu vs %zu)",
7289 __func__, buffer.frameCount, framesOut);
7290 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007291 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007292 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7293 } else {
7294 framesOut = 0;
7295 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7296 __func__, status, buffer.frameCount);
7297 }
7298 } else {
7299 // process frames from the RecordThread buffer provider to the RecordTrack
7300 // buffer
7301 framesOut = activeTrack->mRecordBufferConverter->convert(
7302 activeTrack->mSink.raw,
7303 activeTrack->mResamplerBufferProvider,
7304 framesOut);
7305 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007306
7307 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7308 overrun = OVERRUN_FALSE;
7309 }
7310
7311 if (activeTrack->mFramesToDrop == 0) {
7312 if (framesOut > 0) {
7313 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007314 // Sanitize before releasing if the track has no access to the source data
7315 // An idle UID receives silence from non virtual devices until active
7316 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007317 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007318 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007319 activeTrack->releaseBuffer(&activeTrack->mSink);
7320 }
7321 } else {
7322 // FIXME could do a partial drop of framesOut
7323 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007324 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007325 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007326 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007327 }
7328 } else {
7329 activeTrack->mFramesToDrop += framesOut;
7330 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7331 activeTrack->mSyncStartEvent->isCancelled()) {
7332 ALOGW("Synced record %s, session %d, trigger session %d",
7333 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7334 activeTrack->sessionId(),
7335 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007336 activeTrack->mSyncStartEvent->triggerSession() :
7337 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007338 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007339 }
7340 }
7341 }
7342
7343 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007344 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007345 }
7346 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007347
7348 switch (overrun) {
7349 case OVERRUN_TRUE:
7350 // client isn't retrieving buffers fast enough
7351 if (!activeTrack->setOverflow()) {
7352 nsecs_t now = systemTime();
7353 // FIXME should lastWarning per track?
7354 if ((now - lastWarning) > kWarningThrottleNs) {
7355 ALOGW("RecordThread: buffer overflow");
7356 lastWarning = now;
7357 }
7358 }
7359 break;
7360 case OVERRUN_FALSE:
7361 activeTrack->clearOverflow();
7362 break;
7363 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007364 break;
7365 }
7366
Andy Hung3f0c9022016-01-15 17:49:46 -08007367 // update frame information and push timestamp out
7368 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007369 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007370 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7371 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007372 }
7373
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007374unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007375 // enable changes in effect chain
7376 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007377 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007378 if (audio_has_proportional_frames(mFormat)
7379 && loopCount == lastLoopCountRead + 1) {
7380 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7381 const double jitterMs =
7382 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7383 {framesRead, readPeriodNs},
7384 {0, 0} /* lastTimestamp */, mSampleRate);
7385 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7386
7387 Mutex::Autolock _l(mLock);
7388 mIoJitterMs.add(jitterMs);
7389 mProcessTimeMs.add(processMs);
7390 }
7391 // update timing info.
7392 mLastIoBeginNs = lastIoBeginNs;
7393 mLastIoEndNs = lastIoEndNs;
7394 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007395 }
7396
Glenn Kasten93e471f2013-08-19 08:40:07 -07007397 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007398
7399 {
7400 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007401 for (size_t i = 0; i < mTracks.size(); i++) {
7402 sp<RecordTrack> track = mTracks[i];
7403 track->invalidate();
7404 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007405 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007406 mStartStopCond.broadcast();
7407 }
7408
7409 releaseWakeLock();
7410
7411 ALOGV("RecordThread %p exiting", this);
7412 return false;
7413}
7414
Glenn Kasten93e471f2013-08-19 08:40:07 -07007415void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007416{
7417 if (!mStandby) {
7418 inputStandBy();
7419 mStandby = true;
7420 }
7421}
7422
7423void AudioFlinger::RecordThread::inputStandBy()
7424{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007425 // Idle the fast capture if it's currently running
7426 if (mFastCapture != 0) {
7427 FastCaptureStateQueue *sq = mFastCapture->sq();
7428 FastCaptureState *state = sq->begin();
7429 if (!(state->mCommand & FastCaptureState::IDLE)) {
7430 state->mCommand = FastCaptureState::COLD_IDLE;
7431 state->mColdFutexAddr = &mFastCaptureFutex;
7432 state->mColdGen++;
7433 mFastCaptureFutex = 0;
7434 sq->end();
7435 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7436 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7437#if 0
7438 if (kUseFastCapture == FastCapture_Dynamic) {
7439 // FIXME
7440 }
7441#endif
7442#ifdef AUDIO_WATCHDOG
7443 // FIXME
7444#endif
7445 } else {
7446 sq->end(false /*didModify*/);
7447 }
7448 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07007449 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007450 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007451
7452 // If going into standby, flush the pipe source.
7453 if (mPipeSource.get() != nullptr) {
7454 const ssize_t flushed = mPipeSource->flush();
7455 if (flushed > 0) {
7456 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7457 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7458 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7459 }
7460 }
Eric Laurent81784c32012-11-19 14:55:58 -08007461}
7462
Glenn Kasten05997e22014-03-13 15:08:33 -07007463// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007464sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007465 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007466 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007467 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007468 audio_format_t format,
7469 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007470 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007471 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007472 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007473 pid_t creatorPid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007474 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007475 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007476 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007477 status_t *status,
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007478 audio_port_handle_t portId,
7479 const String16& opPackageName)
Eric Laurent81784c32012-11-19 14:55:58 -08007480{
Glenn Kasten74935e42013-12-19 08:56:45 -08007481 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007482 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007483 sp<RecordTrack> track;
7484 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007485 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007486 audio_input_flags_t requestedFlags = *flags;
7487 uint32_t sampleRate;
7488
7489 lStatus = initCheck();
7490 if (lStatus != NO_ERROR) {
7491 ALOGE("createRecordTrack_l() audio driver not initialized");
7492 goto Exit;
7493 }
7494
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007495 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7496 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7497 lStatus = BAD_VALUE;
7498 goto Exit;
7499 }
7500
Eric Laurentf14db3c2017-12-08 14:20:36 -08007501 if (*pSampleRate == 0) {
7502 *pSampleRate = mSampleRate;
7503 }
7504 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007505
7506 // special case for FAST flag considered OK if fast capture is present
7507 if (hasFastCapture()) {
7508 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7509 }
7510
Eric Laurentf14db3c2017-12-08 14:20:36 -08007511 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007512 if ((*flags & inputFlags) != *flags) {
7513 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7514 " input flags (%08x)",
7515 *flags, inputFlags);
7516 *flags = (audio_input_flags_t)(*flags & inputFlags);
7517 }
Eric Laurent81784c32012-11-19 14:55:58 -08007518
Glenn Kasten90e58b12013-07-31 16:16:02 -07007519 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007520 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007521 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007522 // we formerly checked for a callback handler (non-0 tid),
7523 // but that is no longer required for TRANSFER_OBTAIN mode
7524 //
Phil Burk7ed66a12019-04-18 13:20:30 -07007525 // Frame count is not specified (0), or is less than or equal the pipe depth.
7526 // It is OK to provide a higher capacity than requested.
7527 // We will force it to mPipeFramesP2 below.
7528 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007529 // PCM data
7530 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007531 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007532 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007533 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007534 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007535 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007536 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007537 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007538 hasFastCapture() &&
7539 // there are sufficient fast track slots available
7540 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007541 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007542 // check compatibility with audio effects.
7543 Mutex::Autolock _l(mLock);
7544 // Do not accept FAST flag if the session has software effects
7545 sp<EffectChain> chain = getEffectChain_l(sessionId);
7546 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007547 audio_input_flags_t old = *flags;
7548 chain->checkInputFlagCompatibility(flags);
7549 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007550 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7551 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007552 }
7553 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007554 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007555 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7556 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007557 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007558 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7559 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007560 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007561 this, frameCount, mFrameCount, mPipeFramesP2,
7562 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007563 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007564 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007565 }
7566 }
7567
Eric Laurentf14db3c2017-12-08 14:20:36 -08007568 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7569 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7570 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7571 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7572 lStatus = BAD_TYPE;
7573 goto Exit;
7574 }
7575
Glenn Kasten74105912014-07-03 12:28:53 -07007576 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007577 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007578 // fast track: frame count is exactly the pipe depth
7579 frameCount = mPipeFramesP2;
7580 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007581 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007582 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007583 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7584 // or 20 ms if there is a fast capture
7585 // TODO This could be a roundupRatio inline, and const
7586 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7587 * sampleRate + mSampleRate - 1) / mSampleRate;
7588 // minimum number of notification periods is at least kMinNotifications,
7589 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7590 static const size_t kMinNotifications = 3;
7591 static const uint32_t kMinMs = 30;
7592 // TODO This could be a roundupRatio inline
7593 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7594 // TODO This could be a roundupRatio inline
7595 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7596 maxNotificationFrames;
7597 const size_t minFrameCount = maxNotificationFrames *
7598 max(kMinNotifications, minNotificationsByMs);
7599 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007600 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7601 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007602 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007603 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007604 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007605 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007606
7607 { // scope for mLock
7608 Mutex::Autolock _l(mLock);
7609
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007610 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007611 format, channelMask, frameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007612 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid, uid,
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007613 *flags, TrackBase::TYPE_DEFAULT, opPackageName, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007614
Glenn Kasten03003332013-08-06 15:40:54 -07007615 lStatus = track->initCheck();
7616 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007617 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007618 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007619 goto Exit;
7620 }
7621 mTracks.add(track);
7622
Eric Laurent05067782016-06-01 18:27:28 -07007623 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007624 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7625 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7626 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007627 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007628 }
Eric Laurent81784c32012-11-19 14:55:58 -08007629 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007630
Eric Laurent81784c32012-11-19 14:55:58 -08007631 lStatus = NO_ERROR;
7632
7633Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007634 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007635 return track;
7636}
7637
7638status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7639 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007640 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007641{
7642 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7643 sp<ThreadBase> strongMe = this;
7644 status_t status = NO_ERROR;
7645
7646 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007647 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007648 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007649 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007650 triggerSession,
7651 recordTrack->sessionId(),
7652 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007653 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007654 // Sync event can be cancelled by the trigger session if the track is not in a
7655 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007656 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007657 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007658 } else {
7659 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007660 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007661 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007662 }
7663 }
7664
7665 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007666 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007667 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007668 if (recordTrack->isInvalid()) {
7669 recordTrack->clearSyncStartEvent();
7670 return INVALID_OPERATION;
7671 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007672 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7673 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07007674 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
7675 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007676 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007677 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007678 } else {
7679 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007680 }
7681 return status;
7682 }
7683
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007684 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7685 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7686 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007687 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007688 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007689 status_t status = NO_ERROR;
7690 if (recordTrack->isExternalTrack()) {
7691 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08007692 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007693 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07007694 if (recordTrack->isInvalid()) {
7695 recordTrack->clearSyncStartEvent();
7696 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
7697 recordTrack->mState = TrackBase::STARTING_2;
7698 // STARTING_2 forces destroy to call stopInput.
7699 }
7700 return INVALID_OPERATION;
7701 }
7702 if (recordTrack->mState != TrackBase::STARTING_1) {
7703 ALOGW("%s(%d): unsynchronized mState:%d change",
7704 __func__, recordTrack->id(), recordTrack->mState);
7705 // Someone else has changed state, let them take over,
7706 // leave mState in the new state.
7707 recordTrack->clearSyncStartEvent();
7708 return INVALID_OPERATION;
7709 }
7710 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07007711 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07007712 ALOGW("%s(%d): startInput failed, status %d",
7713 __func__, recordTrack->id(), status);
7714 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
7715 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07007716 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007717 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07007718 return status;
7719 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07007720 sendIoConfigEvent_l(
7721 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08007722 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007723 // Catch up with current buffer indices if thread is already running.
7724 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7725 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7726 // see previously buffered data before it called start(), but with greater risk of overrun.
7727
Andy Hung73c02e42015-03-29 01:13:58 -07007728 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007729 if (!recordTrack->isDirect()) {
7730 // clear any converter state as new data will be discontinuous
7731 recordTrack->mRecordBufferConverter->reset();
7732 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007733 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007734 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007735 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007736 return status;
7737 }
Eric Laurent81784c32012-11-19 14:55:58 -08007738}
7739
Eric Laurent81784c32012-11-19 14:55:58 -08007740void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7741{
7742 sp<SyncEvent> strongEvent = event.promote();
7743
7744 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007745 sp<RefBase> ptr = strongEvent->cookie().promote();
7746 if (ptr != 0) {
7747 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7748 recordTrack->handleSyncStartEvent(strongEvent);
7749 }
Eric Laurent81784c32012-11-19 14:55:58 -08007750 }
7751}
7752
Glenn Kastena8356f62013-07-25 14:37:52 -07007753bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007754 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007755 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007756 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007757 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007758 return false;
7759 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007760 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007761 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07007762
Andy Hungabfab202019-03-07 19:45:54 -08007763 // NOTE: Waiting here is important to keep stop synchronous.
7764 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07007765 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
7766 mWaitWorkCV.broadcast(); // signal thread to stop
7767 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08007768 }
Andy Hungce685402018-10-05 17:23:27 -07007769
7770 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08007771 ALOGV("Record stopped OK");
7772 return true;
7773 }
Andy Hungce685402018-10-05 17:23:27 -07007774
7775 // don't handle anything - we've been invalidated or restarted and in a different state
7776 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
7777 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007778 return false;
7779}
7780
Glenn Kasten0f11b512014-01-31 16:18:54 -08007781bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007782{
7783 return false;
7784}
7785
Glenn Kasten0f11b512014-01-31 16:18:54 -08007786status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007787{
7788#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7789 if (!isValidSyncEvent(event)) {
7790 return BAD_VALUE;
7791 }
7792
Glenn Kastend848eb42016-03-08 13:42:11 -08007793 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007794 status_t ret = NAME_NOT_FOUND;
7795
7796 Mutex::Autolock _l(mLock);
7797
7798 for (size_t i = 0; i < mTracks.size(); i++) {
7799 sp<RecordTrack> track = mTracks[i];
7800 if (eventSession == track->sessionId()) {
7801 (void) track->setSyncEvent(event);
7802 ret = NO_ERROR;
7803 }
7804 }
7805 return ret;
7806#else
7807 return BAD_VALUE;
7808#endif
7809}
7810
jiabin653cc0a2018-01-17 17:54:10 -08007811status_t AudioFlinger::RecordThread::getActiveMicrophones(
7812 std::vector<media::MicrophoneInfo>* activeMicrophones)
7813{
7814 ALOGV("RecordThread::getActiveMicrophones");
7815 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007816 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7817 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007818}
7819
Paul McLean12340082019-03-19 09:35:05 -06007820status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
7821 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07007822{
Paul McLean12340082019-03-19 09:35:05 -06007823 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007824 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06007825 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007826}
7827
Paul McLean12340082019-03-19 09:35:05 -06007828status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07007829{
Paul McLean12340082019-03-19 09:35:05 -06007830 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007831 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06007832 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007833}
7834
Kevin Rocard069c2712018-03-29 19:09:14 -07007835void AudioFlinger::RecordThread::updateMetadata_l()
7836{
7837 if (mInput == nullptr || mInput->stream == nullptr ||
7838 !mActiveTracks.readAndClearHasChanged()) {
7839 return;
7840 }
7841 StreamInHalInterface::SinkMetadata metadata;
7842 for (const sp<RecordTrack> &track : mActiveTracks) {
7843 // No track is invalid as this is called after prepareTrack_l in the same critical section
7844 metadata.tracks.push_back({
7845 .source = track->attributes().source,
7846 .gain = 1, // capture tracks do not have volumes
7847 });
7848 }
7849 mInput->stream->updateSinkMetadata(metadata);
7850}
7851
Eric Laurent81784c32012-11-19 14:55:58 -08007852// destroyTrack_l() must be called with ThreadBase::mLock held
7853void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7854{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007855 track->terminate();
7856 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007857 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007858 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007859 removeTrack_l(track);
7860 }
7861}
7862
7863void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7864{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007865 String8 result;
7866 track->appendDump(result, false /* active */);
7867 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7868
Eric Laurent81784c32012-11-19 14:55:58 -08007869 mTracks.remove(track);
7870 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007871 if (track->isFastTrack()) {
7872 ALOG_ASSERT(!mFastTrackAvail);
7873 mFastTrackAvail = true;
7874 }
Eric Laurent81784c32012-11-19 14:55:58 -08007875}
7876
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007877void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007878{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007879 AudioStreamIn *input = mInput;
7880 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7881 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08007882 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07007883 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07007884 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007885 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007886 }
Andy Hungbfa64962017-06-12 14:43:19 -07007887
7888 if (input != nullptr) {
7889 dprintf(fd, " Hal stream dump:\n");
7890 (void)input->stream->dump(fd);
7891 }
7892
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007893 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007894 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007895
Glenn Kasten2f90c512015-12-02 11:40:09 -08007896 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7897 // while we are dumping it. It may be inconsistent, but it won't mutate!
7898 // This is a large object so we place it on the heap.
7899 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07007900 const std::unique_ptr<FastCaptureDumpState> copy =
7901 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08007902 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08007903}
7904
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007905void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007906{
Eric Laurent81784c32012-11-19 14:55:58 -08007907 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007908 size_t numtracks = mTracks.size();
7909 size_t numactive = mActiveTracks.size();
7910 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007911 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007912 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007913 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007914 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007915 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007916 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007917 for (size_t i = 0; i < numtracks ; ++i) {
7918 sp<RecordTrack> track = mTracks[i];
7919 if (track != 0) {
7920 bool active = mActiveTracks.indexOf(track) >= 0;
7921 if (active) {
7922 numactiveseen++;
7923 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007924 result.append(prefix);
7925 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007926 }
Eric Laurent81784c32012-11-19 14:55:58 -08007927 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007928 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007929 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007930 }
7931
Marco Nelissenb2208842014-02-07 14:00:50 -08007932 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007933 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007934 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007935 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007936 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007937 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007938 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007939 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007940 result.append(prefix);
7941 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007942 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007943 }
Eric Laurent81784c32012-11-19 14:55:58 -08007944
7945 }
7946 write(fd, result.string(), result.size());
7947}
7948
Eric Laurent5ada82e2019-08-29 17:53:54 -07007949void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007950{
7951 Mutex::Autolock _l(mLock);
7952 for (size_t i = 0; i < mTracks.size() ; i++) {
7953 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07007954 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007955 track->setSilenced(silenced);
7956 }
7957 }
7958}
Andy Hung73c02e42015-03-29 01:13:58 -07007959
7960void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7961{
7962 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7963 RecordThread *recordThread = (RecordThread *) threadBase.get();
7964 mRsmpInFront = recordThread->mRsmpInRear;
7965 mRsmpInUnrel = 0;
7966}
7967
7968void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7969 size_t *framesAvailable, bool *hasOverrun)
7970{
7971 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7972 RecordThread *recordThread = (RecordThread *) threadBase.get();
7973 const int32_t rear = recordThread->mRsmpInRear;
7974 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07007975 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07007976
7977 size_t framesIn;
7978 bool overrun = false;
7979 if (filled < 0) {
7980 // should not happen, but treat like a massive overrun and re-sync
7981 framesIn = 0;
7982 mRsmpInFront = rear;
7983 overrun = true;
7984 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7985 framesIn = (size_t) filled;
7986 } else {
7987 // client is not keeping up with server, but give it latest data
7988 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07007989 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
7990 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07007991 overrun = true;
7992 }
7993 if (framesAvailable != NULL) {
7994 *framesAvailable = framesIn;
7995 }
7996 if (hasOverrun != NULL) {
7997 *hasOverrun = overrun;
7998 }
7999}
8000
Eric Laurent81784c32012-11-19 14:55:58 -08008001// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008002status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008003 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008004{
Andy Hung73c02e42015-03-29 01:13:58 -07008005 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008006 if (threadBase == 0) {
8007 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008008 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008009 return NOT_ENOUGH_DATA;
8010 }
8011 RecordThread *recordThread = (RecordThread *) threadBase.get();
8012 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008013 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008014 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008015 // FIXME should not be P2 (don't want to increase latency)
8016 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008017 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008018 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008019 front &= recordThread->mRsmpInFramesP2 - 1;
8020 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008021 if (part1 > (size_t) filled) {
8022 part1 = filled;
8023 }
8024 size_t ask = buffer->frameCount;
8025 ALOG_ASSERT(ask > 0);
8026 if (part1 > ask) {
8027 part1 = ask;
8028 }
8029 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008030 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008031 buffer->raw = NULL;
8032 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008033 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008034 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008035 }
8036
Andy Hung57446612015-04-19 23:56:46 -07008037 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008038 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008039 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008040 return NO_ERROR;
8041}
8042
8043// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008044void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8045 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008046{
Hongwei Wang95e37682019-04-12 11:13:36 -07008047 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008048 if (stepCount == 0) {
8049 return;
8050 }
Andy Hung73c02e42015-03-29 01:13:58 -07008051 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8052 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008053 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008054 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008055 buffer->frameCount = 0;
8056}
8057
Eric Laurentd8365c52017-07-16 15:27:05 -07008058void AudioFlinger::RecordThread::checkBtNrec()
8059{
8060 Mutex::Autolock _l(mLock);
8061 checkBtNrec_l();
8062}
8063
8064void AudioFlinger::RecordThread::checkBtNrec_l()
8065{
8066 // disable AEC and NS if the device is a BT SCO headset supporting those
8067 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07008068 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008069 mAudioFlinger->btNrecIsOff();
8070 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8071 for (size_t i = 0; i < mEffectChains.size(); i++) {
8072 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8073 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8074 }
8075 }
8076}
8077
Andy Hung97a893e2015-03-29 01:03:07 -07008078
Eric Laurent10351942014-05-08 18:49:52 -07008079bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8080 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008081{
8082 bool reconfig = false;
8083
Eric Laurent10351942014-05-08 18:49:52 -07008084 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008085
Eric Laurent10351942014-05-08 18:49:52 -07008086 audio_format_t reqFormat = mFormat;
8087 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008088 // 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 -07008089 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8090
8091 AudioParameter param = AudioParameter(keyValuePair);
8092 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008093
8094 // scope for AutoPark extends to end of method
8095 AutoPark<FastCapture> park(mFastCapture);
8096
Eric Laurent10351942014-05-08 18:49:52 -07008097 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8098 // channel count change can be requested. Do we mandate the first client defines the
8099 // HAL sampling rate and channel count or do we allow changes on the fly?
8100 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8101 samplingRate = value;
8102 reconfig = true;
8103 }
8104 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008105 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008106 status = BAD_VALUE;
8107 } else {
8108 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008109 reconfig = true;
8110 }
Eric Laurent10351942014-05-08 18:49:52 -07008111 }
8112 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8113 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008114 if (!audio_is_input_channel(mask) ||
8115 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07008116 status = BAD_VALUE;
8117 } else {
8118 channelMask = mask;
8119 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008120 }
Eric Laurent10351942014-05-08 18:49:52 -07008121 }
8122 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8123 // do not accept frame count changes if tracks are open as the track buffer
8124 // size depends on frame count and correct behavior would not be guaranteed
8125 // if frame count is changed after track creation
8126 if (mActiveTracks.size() > 0) {
8127 status = INVALID_OPERATION;
8128 } else {
8129 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008130 }
Eric Laurent10351942014-05-08 18:49:52 -07008131 }
8132 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008133 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008134 }
8135 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8136 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07008137 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008138 }
Glenn Kastene198c362013-08-13 09:13:36 -07008139
Eric Laurent10351942014-05-08 18:49:52 -07008140 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008141 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008142 if (status == INVALID_OPERATION) {
8143 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008144 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008145 }
8146 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008147 if (status == BAD_VALUE) {
8148 uint32_t sRate;
8149 audio_channel_mask_t channelMask;
8150 audio_format_t format;
8151 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
8152 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
8153 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
8154 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
8155 status = NO_ERROR;
8156 }
Eric Laurent81784c32012-11-19 14:55:58 -08008157 }
Eric Laurent10351942014-05-08 18:49:52 -07008158 if (status == NO_ERROR) {
8159 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008160 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008161 }
8162 }
Eric Laurent81784c32012-11-19 14:55:58 -08008163 }
Eric Laurent10351942014-05-08 18:49:52 -07008164
Eric Laurent81784c32012-11-19 14:55:58 -08008165 return reconfig;
8166}
8167
8168String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8169{
Eric Laurent81784c32012-11-19 14:55:58 -08008170 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008171 if (initCheck() == NO_ERROR) {
8172 String8 out_s8;
8173 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8174 return out_s8;
8175 }
Eric Laurent81784c32012-11-19 14:55:58 -08008176 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008177 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008178}
8179
Eric Laurent09f1ed22019-04-24 17:45:17 -07008180void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8181 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008182 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8183
8184 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008185
8186 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008187 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008188 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008189 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008190 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008191 desc->mChannelMask = mChannelMask;
8192 desc->mSamplingRate = mSampleRate;
8193 desc->mFormat = mFormat;
8194 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008195 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008196 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008197 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008198 case AUDIO_CLIENT_STARTED:
8199 desc->mPatch = mPatch;
8200 desc->mPortId = portId;
8201 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008202 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008203 default:
8204 break;
8205 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008206 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008207}
8208
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008209void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008210{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008211 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8212 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008213 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008214 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8215 if (audio_is_linear_pcm(mFormat)) {
8216 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
8217 mChannelCount, FCC_8);
8218 } else {
8219 // Can have more that FCC_8 channels in encoded streams.
8220 ALOGI("HAL format %#x is not linear pcm", mFormat);
8221 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008222 result = mInput->stream->getFrameSize(&mFrameSize);
8223 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8224 result = mInput->stream->getBufferSize(&mBufferSize);
8225 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008226 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008227 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
8228 "mBufferSize=%lld, mFrameCount=%lld",
8229 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
8230 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008231 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08008232 // 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 -07008233 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08008234 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008235 // A larger value should allow more old data to be read after a track calls start(),
8236 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07008237 //
8238 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08008239 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07008240 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07008241 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07008242 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008243
8244 // TODO optimize audio capture buffer sizes ...
8245 // Here we calculate the size of the sliding buffer used as a source
8246 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8247 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8248 // be better to have it derived from the pipe depth in the long term.
8249 // The current value is higher than necessary. However it should not add to latency.
8250
Glenn Kasten85948432013-08-19 12:09:05 -07008251 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07008252 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8253 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08008254 // if posix_memalign fails, will segv here.
8255 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08008256
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008257 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8258 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08008259}
8260
Glenn Kasten5f972c02014-01-13 09:59:31 -08008261uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008262{
8263 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008264 uint32_t result;
8265 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8266 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008267 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008268 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008269}
8270
Glenn Kastend848eb42016-03-08 13:42:11 -08008271KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008272{
Glenn Kastend848eb42016-03-08 13:42:11 -08008273 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008274 Mutex::Autolock _l(mLock);
8275 for (size_t j = 0; j < mTracks.size(); ++j) {
8276 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008277 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008278 if (ids.indexOfKey(sessionId) < 0) {
8279 ids.add(sessionId, true);
8280 }
8281 }
8282 return ids;
8283}
8284
8285AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8286{
8287 Mutex::Autolock _l(mLock);
8288 AudioStreamIn *input = mInput;
8289 mInput = NULL;
8290 return input;
8291}
8292
8293// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008294sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008295{
8296 if (mInput == NULL) {
8297 return NULL;
8298 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008299 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008300}
8301
8302status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8303{
Eric Laurent81784c32012-11-19 14:55:58 -08008304 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008305 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008306 chain->setInBuffer(NULL);
8307 chain->setOutBuffer(NULL);
8308
8309 checkSuspendOnAddEffectChain_l(chain);
8310
Eric Laurent1b928682014-10-02 19:41:47 -07008311 // make sure enabled pre processing effects state is communicated to the HAL as we
8312 // just moved them to a new input stream.
8313 chain->syncHalEffectsState();
8314
Eric Laurent81784c32012-11-19 14:55:58 -08008315 mEffectChains.add(chain);
8316
8317 return NO_ERROR;
8318}
8319
8320size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8321{
8322 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008323
8324 for (size_t i = 0; i < mEffectChains.size(); i++) {
8325 if (chain == mEffectChains[i]) {
8326 mEffectChains.removeAt(i);
8327 break;
8328 }
Eric Laurent81784c32012-11-19 14:55:58 -08008329 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008330 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008331}
8332
Eric Laurent1c333e22014-05-20 10:48:17 -07008333status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8334 audio_patch_handle_t *handle)
8335{
8336 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008337
8338 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07008339 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
8340 mInDeviceTypeAddr.mAddress = patch->sources[0].ext.device.address;
François Gaffie0c280aa2018-07-25 10:02:15 +02008341 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07008342 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008343 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07008344 }
8345
Eric Laurentd8365c52017-07-16 15:27:05 -07008346 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008347
8348 // store new source and send to effects
8349 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8350 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008351 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008352 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008353 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008354 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008355
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008356 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008357 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8358 status = hwDevice->createAudioPatch(patch->num_sources,
8359 patch->sources,
8360 patch->num_sinks,
8361 patch->sinks,
8362 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008363 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008364 char *address;
8365 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8366 address = audio_device_address_to_parameter(
8367 patch->sources[0].ext.device.type,
8368 patch->sources[0].ext.device.address);
8369 } else {
8370 address = (char *)calloc(1, 1);
8371 }
8372 AudioParameter param = AudioParameter(String8(address));
8373 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008374 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008375 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008376 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008377 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008378 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008379 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008380 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008381
jiabinc52b1ff2019-10-31 17:20:42 -07008382 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008383 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07008384 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07008385 }
Eric Laurent296fb132015-05-01 11:38:42 -07008386
Eric Laurent1c333e22014-05-20 10:48:17 -07008387 return status;
8388}
8389
8390status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8391{
8392 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008393
jiabinc52b1ff2019-10-31 17:20:42 -07008394 mPatch = audio_patch{};
8395 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07008396
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008397 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008398 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8399 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008400 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008401 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008402 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008403 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008404 }
8405 return status;
8406}
8407
jiabinc52b1ff2019-10-31 17:20:42 -07008408void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
8409{
8410 mOutDevices = outDevices;
8411 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
8412 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008413 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07008414 }
8415}
8416
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008417void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008418{
8419 Mutex::Autolock _l(mLock);
8420 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008421 if (record->getSource()) {
8422 mSource = record->getSource();
8423 }
Eric Laurent83b88082014-06-20 18:31:16 -07008424}
8425
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008426void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008427{
8428 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008429 if (mSource == record->getSource()) {
8430 mSource = mInput;
8431 }
Eric Laurent83b88082014-06-20 18:31:16 -07008432 destroyTrack_l(record);
8433}
8434
Mikhail Naganovdc769682018-05-04 15:34:08 -07008435void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008436{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008437 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008438 config->role = AUDIO_PORT_ROLE_SINK;
8439 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8440 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008441 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8442 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8443 config->flags.input = mInput->flags;
8444 }
Eric Laurent83b88082014-06-20 18:31:16 -07008445}
Eric Laurent1c333e22014-05-20 10:48:17 -07008446
Eric Laurent6acd1d42017-01-04 14:23:29 -08008447// ----------------------------------------------------------------------------
8448// Mmap
8449// ----------------------------------------------------------------------------
8450
8451AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8452 : mThread(thread)
8453{
Phil Burk9fabbf82017-08-03 12:02:00 -07008454 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008455}
8456
8457AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8458{
Phil Burk9fabbf82017-08-03 12:02:00 -07008459 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008460}
8461
8462status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8463 struct audio_mmap_buffer_info *info)
8464{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008465 return mThread->createMmapBuffer(minSizeFrames, info);
8466}
8467
8468status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8469{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008470 return mThread->getMmapPosition(position);
8471}
8472
Eric Laurenta54f1282017-07-01 19:39:32 -07008473status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08008474 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008475
8476{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008477 return mThread->start(client, handle);
8478}
8479
8480status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8481{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008482 return mThread->stop(handle);
8483}
8484
Eric Laurent18b57012017-02-13 16:23:52 -08008485status_t AudioFlinger::MmapThreadHandle::standby()
8486{
Eric Laurent18b57012017-02-13 16:23:52 -08008487 return mThread->standby();
8488}
8489
Eric Laurent6acd1d42017-01-04 14:23:29 -08008490
8491AudioFlinger::MmapThread::MmapThread(
8492 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07008493 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady)
8494 : ThreadBase(audioFlinger, id, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008495 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02008496 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008497 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008498 mActiveTracks(&this->mLocalLog),
8499 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8500 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008501{
Eric Laurent18b57012017-02-13 16:23:52 -08008502 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008503 readHalParameters_l();
8504}
8505
8506AudioFlinger::MmapThread::~MmapThread()
8507{
Eric Laurent18b57012017-02-13 16:23:52 -08008508 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008509}
8510
8511void AudioFlinger::MmapThread::onFirstRef()
8512{
8513 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8514}
8515
8516void AudioFlinger::MmapThread::disconnect()
8517{
Eric Laurent331679c2018-04-16 17:03:16 -07008518 ActiveTracks<MmapTrack> activeTracks;
8519 {
8520 Mutex::Autolock _l(mLock);
8521 for (const sp<MmapTrack> &t : mActiveTracks) {
8522 activeTracks.add(t);
8523 }
8524 }
8525 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008526 stop(t->portId());
8527 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008528 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008529 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008530 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008531 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008532 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008533 }
8534}
8535
8536
8537void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8538 audio_stream_type_t streamType __unused,
8539 audio_session_t sessionId,
8540 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008541 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008542 audio_port_handle_t portId)
8543{
8544 mAttr = *attr;
8545 mSessionId = sessionId;
8546 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008547 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008548 mPortId = portId;
8549}
8550
8551status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8552 struct audio_mmap_buffer_info *info)
8553{
8554 if (mHalStream == 0) {
8555 return NO_INIT;
8556 }
Eric Laurent18b57012017-02-13 16:23:52 -08008557 mStandby = true;
8558 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008559 return mHalStream->createMmapBuffer(minSizeFrames, info);
8560}
8561
8562status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8563{
8564 if (mHalStream == 0) {
8565 return NO_INIT;
8566 }
8567 return mHalStream->getMmapPosition(position);
8568}
8569
Eric Laurent331679c2018-04-16 17:03:16 -07008570status_t AudioFlinger::MmapThread::exitStandby()
8571{
8572 status_t ret = mHalStream->start();
8573 if (ret != NO_ERROR) {
8574 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8575 return ret;
8576 }
8577 mStandby = false;
8578 return NO_ERROR;
8579}
8580
Eric Laurenta54f1282017-07-01 19:39:32 -07008581status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008582 audio_port_handle_t *handle)
8583{
Eric Laurenta54f1282017-07-01 19:39:32 -07008584 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8585 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008586 if (mHalStream == 0) {
8587 return NO_INIT;
8588 }
8589
8590 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008591
Eric Laurenta54f1282017-07-01 19:39:32 -07008592 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008593 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008594 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008595 }
8596
8597 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8598
8599 audio_io_handle_t io = mId;
8600 if (isOutput()) {
8601 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8602 config.sample_rate = mSampleRate;
8603 config.channel_mask = mChannelMask;
8604 config.format = mFormat;
8605 audio_stream_type_t stream = streamType();
8606 audio_output_flags_t flags =
8607 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008608 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08008609 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07008610 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8611 mSessionId,
8612 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008613 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008614 client.clientUid,
8615 &config,
8616 flags,
8617 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08008618 &portId,
8619 &secondaryOutputs);
8620 ALOGD_IF(!secondaryOutputs.empty(),
8621 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008622 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008623 audio_config_base_t config;
8624 config.sample_rate = mSampleRate;
8625 config.channel_mask = mChannelMask;
8626 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008627 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008628 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07008629 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07008630 mSessionId,
8631 client.clientPid,
8632 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008633 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008634 &config,
8635 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8636 &deviceId,
8637 &portId);
8638 }
8639 // APM should not chose a different input or output stream for the same set of attributes
8640 // and audo configuration
8641 if (ret != NO_ERROR || io != mId) {
8642 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8643 __FUNCTION__, ret, io, mId);
8644 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008645 }
8646
8647 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008648 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008649 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08008650 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008651 }
8652
Eric Laurent331679c2018-04-16 17:03:16 -07008653 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008654 // abort if start is rejected by audio policy manager
8655 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008656 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07008657 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07008658 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008659 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008660 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008661 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008662 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008663 }
Eric Laurent331679c2018-04-16 17:03:16 -07008664 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008665 } else {
8666 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008667 }
8668 return PERMISSION_DENIED;
8669 }
8670
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008671 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8672 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008673 isOutput(), client.clientUid, client.clientPid,
8674 IPCThreadState::self()->getCallingPid(), portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008675
Eric Laurent4eb58f12018-12-07 16:41:02 -08008676 if (isOutput()) {
8677 // force volume update when a new track is added
8678 mHalVolFloat = -1.0f;
8679 } else if (!track->isSilenced_l()) {
8680 for (const sp<MmapTrack> &t : mActiveTracks) {
8681 if (t->isSilenced_l() && t->uid() != client.clientUid)
8682 t->invalidate();
8683 }
8684 }
8685
8686
Eric Laurent6acd1d42017-01-04 14:23:29 -08008687 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008688 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008689 if (chain != 0) {
8690 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8691 chain->incTrackCnt();
8692 chain->incActiveTrackCnt();
8693 }
8694
8695 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008696 broadcast_l();
8697
Eric Laurenta54f1282017-07-01 19:39:32 -07008698 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008699
8700 return NO_ERROR;
8701}
8702
8703status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8704{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008705 ALOGV("%s handle %d", __FUNCTION__, handle);
8706
8707 if (mHalStream == 0) {
8708 return NO_INIT;
8709 }
8710
Eric Laurenta54f1282017-07-01 19:39:32 -07008711 if (handle == mPortId) {
8712 mHalStream->stop();
8713 return NO_ERROR;
8714 }
8715
Eric Laurent331679c2018-04-16 17:03:16 -07008716 Mutex::Autolock _l(mLock);
8717
Eric Laurent6acd1d42017-01-04 14:23:29 -08008718 sp<MmapTrack> track;
8719 for (const sp<MmapTrack> &t : mActiveTracks) {
8720 if (handle == t->portId()) {
8721 track = t;
8722 break;
8723 }
8724 }
8725 if (track == 0) {
8726 return BAD_VALUE;
8727 }
8728
8729 mActiveTracks.remove(track);
8730
Eric Laurent331679c2018-04-16 17:03:16 -07008731 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008732 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008733 AudioSystem::stopOutput(track->portId());
8734 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008735 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008736 AudioSystem::stopInput(track->portId());
8737 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008738 }
Eric Laurent331679c2018-04-16 17:03:16 -07008739 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008740
8741 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8742 if (chain != 0) {
8743 chain->decActiveTrackCnt();
8744 chain->decTrackCnt();
8745 }
8746
8747 broadcast_l();
8748
Eric Laurent6acd1d42017-01-04 14:23:29 -08008749 return NO_ERROR;
8750}
8751
Eric Laurent18b57012017-02-13 16:23:52 -08008752status_t AudioFlinger::MmapThread::standby()
8753{
8754 ALOGV("%s", __FUNCTION__);
8755
8756 if (mHalStream == 0) {
8757 return NO_INIT;
8758 }
Eric Tan39ec8d62018-07-24 09:49:29 -07008759 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08008760 return INVALID_OPERATION;
8761 }
8762 mHalStream->standby();
8763 mStandby = true;
8764 releaseWakeLock();
8765 return NO_ERROR;
8766}
8767
Eric Laurent6acd1d42017-01-04 14:23:29 -08008768
8769void AudioFlinger::MmapThread::readHalParameters_l()
8770{
8771 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8772 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8773 mFormat = mHALFormat;
8774 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8775 result = mHalStream->getFrameSize(&mFrameSize);
8776 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8777 result = mHalStream->getBufferSize(&mBufferSize);
8778 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8779 mFrameCount = mBufferSize / mFrameSize;
8780}
8781
8782bool AudioFlinger::MmapThread::threadLoop()
8783{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008784 checkSilentMode_l();
8785
8786 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8787
8788 while (!exitPending())
8789 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008790 Vector< sp<EffectChain> > effectChains;
8791
Andy Hung13850be2019-03-14 11:33:09 -07008792 { // under Thread lock
8793 Mutex::Autolock _l(mLock);
8794
Eric Laurent6acd1d42017-01-04 14:23:29 -08008795 if (mSignalPending) {
8796 // A signal was raised while we were unlocked
8797 mSignalPending = false;
8798 } else {
8799 if (mConfigEvents.isEmpty()) {
8800 // we're about to wait, flush the binder command buffer
8801 IPCThreadState::self()->flushCommands();
8802
8803 if (exitPending()) {
8804 break;
8805 }
8806
Eric Laurent6acd1d42017-01-04 14:23:29 -08008807 // wait until we have something to do...
8808 ALOGV("%s going to sleep", myName.string());
8809 mWaitWorkCV.wait(mLock);
8810 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008811
8812 checkSilentMode_l();
8813
8814 continue;
8815 }
8816 }
8817
8818 processConfigEvents_l();
8819
8820 processVolume_l();
8821
8822 checkInvalidTracks_l();
8823
8824 mActiveTracks.updatePowerState(this);
8825
Kevin Rocard069c2712018-03-29 19:09:14 -07008826 updateMetadata_l();
8827
Eric Laurent6acd1d42017-01-04 14:23:29 -08008828 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07008829 } // release Thread lock
8830
Eric Laurent6acd1d42017-01-04 14:23:29 -08008831 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07008832 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08008833 }
Andy Hung13850be2019-03-14 11:33:09 -07008834
8835 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008836 unlockEffectChains(effectChains);
8837 // Effect chains will be actually deleted here if they were removed from
8838 // mEffectChains list during mixing or effects processing
8839 }
8840
8841 threadLoop_exit();
8842
8843 if (!mStandby) {
8844 threadLoop_standby();
8845 mStandby = true;
8846 }
8847
Eric Laurent6acd1d42017-01-04 14:23:29 -08008848 ALOGV("Thread %p type %d exiting", this, mType);
8849 return false;
8850}
8851
8852// checkForNewParameter_l() must be called with ThreadBase::mLock held
8853bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8854 status_t& status)
8855{
8856 AudioParameter param = AudioParameter(keyValuePair);
8857 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008858 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008859 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008860 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008861 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008862 if (sendToHal) {
8863 status = mHalStream->setParameters(keyValuePair);
8864 } else {
8865 status = NO_ERROR;
8866 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008867
8868 return false;
8869}
8870
8871String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8872{
8873 Mutex::Autolock _l(mLock);
8874 String8 out_s8;
8875 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8876 return out_s8;
8877 }
8878 return String8();
8879}
8880
Eric Laurent09f1ed22019-04-24 17:45:17 -07008881void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8882 audio_port_handle_t portId __unused) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008883 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8884
8885 desc->mIoHandle = mId;
8886
8887 switch (event) {
8888 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008889 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008890 case AUDIO_INPUT_CONFIG_CHANGED:
8891 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008892 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008893 case AUDIO_OUTPUT_CONFIG_CHANGED:
8894 desc->mPatch = mPatch;
8895 desc->mChannelMask = mChannelMask;
8896 desc->mSamplingRate = mSampleRate;
8897 desc->mFormat = mFormat;
8898 desc->mFrameCount = mFrameCount;
8899 desc->mFrameCountHAL = mFrameCount;
8900 desc->mLatency = 0;
8901 break;
8902
8903 case AUDIO_INPUT_CLOSED:
8904 case AUDIO_OUTPUT_CLOSED:
8905 default:
8906 break;
8907 }
8908 mAudioFlinger->ioConfigChanged(event, desc, pid);
8909}
8910
8911status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8912 audio_patch_handle_t *handle)
8913{
8914 status_t status = NO_ERROR;
8915
8916 // store new device and send to effects
8917 audio_devices_t type = AUDIO_DEVICE_NONE;
8918 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -07008919 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
8920 AudioDeviceTypeAddr sourceDeviceTypeAddr;
8921 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008922 if (isOutput()) {
8923 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07008924 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
8925 && !mAudioHwDev->supportsAudioPatches(),
8926 "Enumerated device type(%#x) must not be used "
8927 "as it does not support audio patches",
8928 patch->sinks[i].ext.device.type);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008929 type |= patch->sinks[i].ext.device.type;
jiabinc52b1ff2019-10-31 17:20:42 -07008930 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
8931 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08008932 }
8933 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07008934 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008935 } else {
8936 type = patch->sources[0].ext.device.type;
8937 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07008938 numDevices = mPatch.num_sources;
8939 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
8940 sourceDeviceTypeAddr.mAddress = patch->sources[0].ext.device.address;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008941 }
8942
8943 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008944 if (isOutput()) {
8945 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
8946 } else {
8947 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
8948 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008949 }
8950
jiabinc52b1ff2019-10-31 17:20:42 -07008951 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008952 // store new source and send to effects
8953 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8954 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8955 for (size_t i = 0; i < mEffectChains.size(); i++) {
8956 mEffectChains[i]->setAudioSource_l(mAudioSource);
8957 }
8958 }
8959 }
8960
8961 if (mAudioHwDev->supportsAudioPatches()) {
8962 status = mHalDevice->createAudioPatch(patch->num_sources,
8963 patch->sources,
8964 patch->num_sinks,
8965 patch->sinks,
8966 handle);
8967 } else {
8968 char *address;
8969 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8970 //FIXME: we only support address on first sink with HAL version < 3.0
8971 address = audio_device_address_to_parameter(
8972 patch->sinks[0].ext.device.type,
8973 patch->sinks[0].ext.device.address);
8974 } else {
8975 address = (char *)calloc(1, 1);
8976 }
8977 AudioParameter param = AudioParameter(String8(address));
8978 free(address);
8979 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8980 if (!isOutput()) {
8981 param.addInt(String8(AudioParameter::keyInputSource),
8982 (int)patch->sinks[0].ext.mix.usecase.source);
8983 }
8984 status = mHalStream->setParameters(param.toString());
8985 *handle = AUDIO_PATCH_HANDLE_NONE;
8986 }
8987
jiabinc52b1ff2019-10-31 17:20:42 -07008988 if (numDevices == 0 || mDeviceId != deviceId) {
8989 if (isOutput()) {
8990 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
8991 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
8992 } else {
8993 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
8994 mInDeviceTypeAddr = sourceDeviceTypeAddr;
8995 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08008996 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008997 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008998 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008999 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07009000 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009001 }
jiabinc52b1ff2019-10-31 17:20:42 -07009002 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009003 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009004 }
9005 return status;
9006}
9007
9008status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9009{
9010 status_t status = NO_ERROR;
9011
jiabinc52b1ff2019-10-31 17:20:42 -07009012 mPatch = audio_patch{};
9013 mOutDeviceTypeAddrs.clear();
9014 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009015
9016 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9017 supportsAudioPatches : false;
9018
9019 if (supportsAudioPatches) {
9020 status = mHalDevice->releaseAudioPatch(handle);
9021 } else {
9022 AudioParameter param;
9023 param.addInt(String8(AudioParameter::keyRouting), 0);
9024 status = mHalStream->setParameters(param.toString());
9025 }
9026 return status;
9027}
9028
Mikhail Naganovdc769682018-05-04 15:34:08 -07009029void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009030{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009031 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009032 if (isOutput()) {
9033 config->role = AUDIO_PORT_ROLE_SOURCE;
9034 config->ext.mix.hw_module = mAudioHwDev->handle();
9035 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9036 } else {
9037 config->role = AUDIO_PORT_ROLE_SINK;
9038 config->ext.mix.hw_module = mAudioHwDev->handle();
9039 config->ext.mix.usecase.source = mAudioSource;
9040 }
9041}
9042
9043status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9044{
9045 audio_session_t session = chain->sessionId();
9046
9047 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9048 // Attach all tracks with same session ID to this chain.
9049 // indicate all active tracks in the chain
9050 for (const sp<MmapTrack> &track : mActiveTracks) {
9051 if (session == track->sessionId()) {
9052 chain->incTrackCnt();
9053 chain->incActiveTrackCnt();
9054 }
9055 }
9056
9057 chain->setThread(this);
9058 chain->setInBuffer(nullptr);
9059 chain->setOutBuffer(nullptr);
9060 chain->syncHalEffectsState();
9061
9062 mEffectChains.add(chain);
9063 checkSuspendOnAddEffectChain_l(chain);
9064 return NO_ERROR;
9065}
9066
9067size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9068{
9069 audio_session_t session = chain->sessionId();
9070
9071 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9072
9073 for (size_t i = 0; i < mEffectChains.size(); i++) {
9074 if (chain == mEffectChains[i]) {
9075 mEffectChains.removeAt(i);
9076 // detach all active tracks from the chain
9077 // detach all tracks with same session ID from this chain
9078 for (const sp<MmapTrack> &track : mActiveTracks) {
9079 if (session == track->sessionId()) {
9080 chain->decActiveTrackCnt();
9081 chain->decTrackCnt();
9082 }
9083 }
9084 break;
9085 }
9086 }
9087 return mEffectChains.size();
9088}
9089
Eric Laurent6acd1d42017-01-04 14:23:29 -08009090void AudioFlinger::MmapThread::threadLoop_standby()
9091{
9092 mHalStream->standby();
9093}
9094
9095void AudioFlinger::MmapThread::threadLoop_exit()
9096{
Phil Burk7dce7282017-09-27 13:51:41 -07009097 // Do not call callback->onTearDown() because it is redundant for thread exit
9098 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009099}
9100
9101status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9102{
9103 return BAD_VALUE;
9104}
9105
9106bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9107{
9108 return false;
9109}
9110
9111status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9112 const effect_descriptor_t *desc, audio_session_t sessionId)
9113{
9114 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -08009115 if (audio_is_global_session(sessionId)) {
9116 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -08009117 desc->name, mThreadName);
9118 return BAD_VALUE;
9119 }
9120
9121 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9122 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9123 desc->name);
9124 return BAD_VALUE;
9125 }
9126 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009127 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9128 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009129 return BAD_VALUE;
9130 }
9131
9132 // Only allow effects without processing load or latency
9133 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9134 return BAD_VALUE;
9135 }
9136
9137 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009138}
9139
9140void AudioFlinger::MmapThread::checkInvalidTracks_l()
9141{
9142 for (const sp<MmapTrack> &track : mActiveTracks) {
9143 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009144 sp<MmapStreamCallback> callback = mCallback.promote();
9145 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009146 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009147 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009148 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009149 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9150 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9151 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009152 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009153 }
9154 }
9155}
9156
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009157void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009158{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009159 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9160 mAttr.content_type, mAttr.usage, mAttr.source);
9161 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009162 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009163 dprintf(fd, " No active clients\n");
9164 }
9165}
9166
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009167void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009168{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009169 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009170 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009171 dprintf(fd, " %zu Tracks\n", numtracks);
9172 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009173 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009174 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009175 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009176 for (size_t i = 0; i < numtracks ; ++i) {
9177 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009178 result.append(prefix);
9179 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009180 }
9181 } else {
9182 dprintf(fd, "\n");
9183 }
9184 write(fd, result.string(), result.size());
9185}
9186
9187AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9188 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009189 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
9190 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009191 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009192 mStreamVolume(1.0),
9193 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009194 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009195{
9196 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9197 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9198 mMasterVolume = audioFlinger->masterVolume_l();
9199 mMasterMute = audioFlinger->masterMute_l();
9200 if (mAudioHwDev) {
9201 if (mAudioHwDev->canSetMasterVolume()) {
9202 mMasterVolume = 1.0;
9203 }
9204
9205 if (mAudioHwDev->canSetMasterMute()) {
9206 mMasterMute = false;
9207 }
9208 }
9209}
9210
9211void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9212 audio_stream_type_t streamType,
9213 audio_session_t sessionId,
9214 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009215 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009216 audio_port_handle_t portId)
9217{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009218 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009219 mStreamType = streamType;
9220}
9221
9222AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9223{
9224 Mutex::Autolock _l(mLock);
9225 AudioStreamOut *output = mOutput;
9226 mOutput = NULL;
9227 return output;
9228}
9229
9230void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9231{
9232 Mutex::Autolock _l(mLock);
9233 // Don't apply master volume in SW if our HAL can do it for us.
9234 if (mAudioHwDev &&
9235 mAudioHwDev->canSetMasterVolume()) {
9236 mMasterVolume = 1.0;
9237 } else {
9238 mMasterVolume = value;
9239 }
9240}
9241
9242void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9243{
9244 Mutex::Autolock _l(mLock);
9245 // Don't apply master mute in SW if our HAL can do it for us.
9246 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9247 mMasterMute = false;
9248 } else {
9249 mMasterMute = muted;
9250 }
9251}
9252
9253void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9254{
9255 Mutex::Autolock _l(mLock);
9256 if (stream == mStreamType) {
9257 mStreamVolume = value;
9258 broadcast_l();
9259 }
9260}
9261
9262float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9263{
9264 Mutex::Autolock _l(mLock);
9265 if (stream == mStreamType) {
9266 return mStreamVolume;
9267 }
9268 return 0.0f;
9269}
9270
9271void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9272{
9273 Mutex::Autolock _l(mLock);
9274 if (stream == mStreamType) {
9275 mStreamMute= muted;
9276 broadcast_l();
9277 }
9278}
9279
9280void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9281{
9282 Mutex::Autolock _l(mLock);
9283 if (streamType == mStreamType) {
9284 for (const sp<MmapTrack> &track : mActiveTracks) {
9285 track->invalidate();
9286 }
9287 broadcast_l();
9288 }
9289}
9290
9291void AudioFlinger::MmapPlaybackThread::processVolume_l()
9292{
9293 float volume;
9294
9295 if (mMasterMute || mStreamMute) {
9296 volume = 0;
9297 } else {
9298 volume = mMasterVolume * mStreamVolume;
9299 }
9300
9301 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009302
9303 // Convert volumes from float to 8.24
9304 uint32_t vol = (uint32_t)(volume * (1 << 24));
9305
9306 // Delegate volume control to effect in track effect chain if needed
9307 // only one effect chain can be present on DirectOutputThread, so if
9308 // there is one, the track is connected to it
9309 if (!mEffectChains.isEmpty()) {
9310 mEffectChains[0]->setVolume_l(&vol, &vol);
9311 volume = (float)vol / (1 << 24);
9312 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009313 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009314 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9315 mHalVolFloat = volume; // HW volume control worked, so update value.
9316 mNoCallbackWarningCount = 0;
9317 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009318 sp<MmapStreamCallback> callback = mCallback.promote();
9319 if (callback != 0) {
9320 int channelCount;
9321 if (isOutput()) {
9322 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9323 } else {
9324 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9325 }
9326 Vector<float> values;
9327 for (int i = 0; i < channelCount; i++) {
9328 values.add(volume);
9329 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009330 mHalVolFloat = volume; // SW volume control worked, so update value.
9331 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009332 mLock.unlock();
9333 callback->onVolumeChanged(mChannelMask, values);
9334 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009335 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009336 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9337 ALOGW("Could not set MMAP stream volume: no volume callback!");
9338 mNoCallbackWarningCount++;
9339 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009340 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009341 }
9342 }
9343}
9344
Kevin Rocard069c2712018-03-29 19:09:14 -07009345void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9346{
9347 if (mOutput == nullptr || mOutput->stream == nullptr ||
9348 !mActiveTracks.readAndClearHasChanged()) {
9349 return;
9350 }
9351 StreamOutHalInterface::SourceMetadata metadata;
9352 for (const sp<MmapTrack> &track : mActiveTracks) {
9353 // No track is invalid as this is called after prepareTrack_l in the same critical section
9354 metadata.tracks.push_back({
9355 .usage = track->attributes().usage,
9356 .content_type = track->attributes().content_type,
9357 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
9358 });
9359 }
9360 mOutput->stream->updateSourceMetadata(metadata);
9361}
9362
Eric Laurent6acd1d42017-01-04 14:23:29 -08009363void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9364{
9365 if (!mMasterMute) {
9366 char value[PROPERTY_VALUE_MAX];
9367 if (property_get("ro.audio.silent", value, "0") > 0) {
9368 char *endptr;
9369 unsigned long ul = strtoul(value, &endptr, 0);
9370 if (*endptr == '\0' && ul != 0) {
9371 ALOGD("Silence is golden");
9372 // The setprop command will not allow a property to be changed after
9373 // the first time it is set, so we don't have to worry about un-muting.
9374 setMasterMute_l(true);
9375 }
9376 }
9377 }
9378}
9379
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009380void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9381{
9382 MmapThread::toAudioPortConfig(config);
9383 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9384 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9385 config->flags.output = mOutput->flags;
9386 }
9387}
9388
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009389void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009390{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009391 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009392
Glenn Kastend3bb6452016-12-05 18:14:37 -08009393 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9394 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009395 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9396}
9397
9398AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9399 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009400 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
9401 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009402 mInput(input)
9403{
9404 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9405 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9406}
9407
Eric Laurent331679c2018-04-16 17:03:16 -07009408status_t AudioFlinger::MmapCaptureThread::exitStandby()
9409{
Phil Burkf054fc32018-12-06 09:45:59 -08009410 {
9411 // mInput might have been cleared by clearInput()
9412 Mutex::Autolock _l(mLock);
9413 if (mInput != nullptr && mInput->stream != nullptr) {
9414 mInput->stream->setGain(1.0f);
9415 }
9416 }
Eric Laurent331679c2018-04-16 17:03:16 -07009417 return MmapThread::exitStandby();
9418}
9419
Eric Laurent6acd1d42017-01-04 14:23:29 -08009420AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9421{
9422 Mutex::Autolock _l(mLock);
9423 AudioStreamIn *input = mInput;
9424 mInput = NULL;
9425 return input;
9426}
Kevin Rocard069c2712018-03-29 19:09:14 -07009427
Eric Laurent331679c2018-04-16 17:03:16 -07009428
9429void AudioFlinger::MmapCaptureThread::processVolume_l()
9430{
9431 bool changed = false;
9432 bool silenced = false;
9433
9434 sp<MmapStreamCallback> callback = mCallback.promote();
9435 if (callback == 0) {
9436 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9437 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9438 mNoCallbackWarningCount++;
9439 }
9440 }
9441
9442 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9443 // track is silenced and unmute otherwise
9444 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9445 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9446 changed = true;
9447 silenced = mActiveTracks[i]->isSilenced_l();
9448 }
9449 }
9450
9451 if (changed) {
9452 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9453 }
9454}
9455
Kevin Rocard069c2712018-03-29 19:09:14 -07009456void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9457{
9458 if (mInput == nullptr || mInput->stream == nullptr ||
9459 !mActiveTracks.readAndClearHasChanged()) {
9460 return;
9461 }
9462 StreamInHalInterface::SinkMetadata metadata;
9463 for (const sp<MmapTrack> &track : mActiveTracks) {
9464 // No track is invalid as this is called after prepareTrack_l in the same critical section
9465 metadata.tracks.push_back({
9466 .source = track->attributes().source,
9467 .gain = 1, // capture tracks do not have volumes
9468 });
9469 }
9470 mInput->stream->updateSinkMetadata(metadata);
9471}
9472
Eric Laurent5ada82e2019-08-29 17:53:54 -07009473void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -07009474{
9475 Mutex::Autolock _l(mLock);
9476 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07009477 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -07009478 mActiveTracks[i]->setSilenced_l(silenced);
9479 broadcast_l();
9480 }
9481 }
9482}
9483
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009484void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9485{
9486 MmapThread::toAudioPortConfig(config);
9487 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9488 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9489 config->flags.input = mInput->flags;
9490 }
9491}
9492
Glenn Kasten63238ef2015-03-02 15:50:29 -08009493} // namespace android