blob: bf2e9535016338d87bd3a71022b7fbf259e8aa6c [file] [log] [blame]
Glenn Kasten97b5d0d2012-03-23 18:54:19 -07001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Glenn Kastena3d26282012-11-30 07:57:43 -080017// <IMPORTANT_WARNING>
18// Design rules for threadLoop() are given in the comments at section "Fast mixer thread" of
19// StateQueue.h. In particular, avoid library and system calls except at well-known points.
20// The design rules are only for threadLoop(), and don't apply to FastMixerDumpState methods.
21// </IMPORTANT_WARNING>
22
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070023#define LOG_TAG "FastMixer"
Glenn Kasten7f5d3352013-02-15 23:55:04 +000024//#define LOG_NDEBUG 0
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070025
Alex Rayb3a83642012-11-30 19:42:28 -080026#define ATRACE_TAG ATRACE_TAG_AUDIO
Alex Ray371eb972012-11-30 11:11:54 -080027
Glenn Kasten153b9fe2013-07-15 11:23:36 -070028#include "Configuration.h"
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070029#include <time.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080030#include <utils/Debug.h>
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070031#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070032#include <utils/Trace.h>
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070033#include <system/audio.h>
Glenn Kasten214b4062015-03-02 14:15:47 -080034#ifdef FAST_THREAD_STATISTICS
Eric Tan5b13ff82018-07-27 11:20:17 -070035#include <audio_utils/Statistics.h>
Glenn Kasten0a14c4c2012-06-13 14:58:49 -070036#ifdef CPU_FREQUENCY_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -070037#include <cpustats/ThreadCpuUsage.h>
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070038#endif
Glenn Kasten0a14c4c2012-06-13 14:58:49 -070039#endif
jiabin245cdd92018-12-07 17:55:15 -080040#include <audio_utils/channels.h>
Andy Hung1258c1a2014-05-23 21:22:17 -070041#include <audio_utils/format.h>
jiabin245cdd92018-12-07 17:55:15 -080042#include <audio_utils/mono_blend.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070043#include <cutils/bitops.h>
Andy Hung068561c2017-01-03 17:09:32 -080044#include <media/AudioMixer.h>
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070045#include "FastMixer.h"
Glenn Kasteneef598c2017-04-03 14:41:13 -070046#include "TypedLogger.h"
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070047
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070048namespace android {
49
Glenn Kastene4a7ce22015-03-03 11:23:17 -080050/*static*/ const FastMixerState FastMixer::sInitial;
Glenn Kasten22340022014-04-07 12:04:41 -070051
Andy Hung8946a282018-04-19 20:04:56 -070052FastMixer::FastMixer(audio_io_handle_t parentIoHandle)
53 : FastThread("cycle_ms", "load_us"),
Glenn Kastene4a7ce22015-03-03 11:23:17 -080054 // mFastTrackNames
55 // mGenerations
56 mOutputSink(NULL),
57 mOutputSinkGen(0),
58 mMixer(NULL),
Andy Hung1258c1a2014-05-23 21:22:17 -070059 mSinkBuffer(NULL),
60 mSinkBufferSize(0),
Andy Hung9a592762014-07-21 21:56:01 -070061 mSinkChannelCount(FCC_2),
Andy Hung45d68d32014-05-23 21:13:31 -070062 mMixerBuffer(NULL),
Andy Hung1258c1a2014-05-23 21:22:17 -070063 mMixerBufferSize(0),
Andy Hung45d68d32014-05-23 21:13:31 -070064 mMixerBufferState(UNDEFINED),
Glenn Kastene4a7ce22015-03-03 11:23:17 -080065 mFormat(Format_Invalid),
66 mSampleRate(0),
67 mFastTracksGen(0),
68 mTotalNativeFramesWritten(0),
Glenn Kasten22340022014-04-07 12:04:41 -070069 // timestamp
Andy Hung2ddee192015-12-18 17:34:44 -080070 mNativeFramesWrittenButNotPresented(0), // the = 0 is to silence the compiler
Andy Hung8946a282018-04-19 20:04:56 -070071 mMasterMono(false),
72 mThreadIoHandle(parentIoHandle)
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070073{
Andy Hung8946a282018-04-19 20:04:56 -070074 (void)mThreadIoHandle; // prevent unused warning, see C++17 [[maybe_unused]]
75
Glenn Kastene4a7ce22015-03-03 11:23:17 -080076 // FIXME pass sInitial as parameter to base class constructor, and make it static local
77 mPrevious = &sInitial;
78 mCurrent = &sInitial;
Glenn Kasten22340022014-04-07 12:04:41 -070079
Glenn Kastene4a7ce22015-03-03 11:23:17 -080080 mDummyDumpState = &mDummyFastMixerDumpState;
Andy Hung9a592762014-07-21 21:56:01 -070081 // TODO: Add channel mask to NBAIO_Format.
82 // We assume that the channel mask must be a valid positional channel mask.
83 mSinkChannelMask = audio_channel_out_mask_from_count(mSinkChannelCount);
Glenn Kasten22340022014-04-07 12:04:41 -070084
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070085 unsigned i;
Glenn Kastendc2c50b2016-04-21 08:13:14 -070086 for (i = 0; i < FastMixerState::sMaxFastTracks; ++i) {
Glenn Kastene4a7ce22015-03-03 11:23:17 -080087 mGenerations[i] = 0;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070088 }
Glenn Kasten214b4062015-03-02 14:15:47 -080089#ifdef FAST_THREAD_STATISTICS
Glenn Kastene4a7ce22015-03-03 11:23:17 -080090 mOldLoad.tv_sec = 0;
91 mOldLoad.tv_nsec = 0;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070092#endif
Glenn Kasten22340022014-04-07 12:04:41 -070093}
94
95FastMixer::~FastMixer()
96{
97}
98
99FastMixerStateQueue* FastMixer::sq()
100{
101 return &mSQ;
102}
103
104const FastThreadState *FastMixer::poll()
105{
106 return mSQ.poll();
107}
108
Mikhail Naganov9b6599e2019-07-29 15:23:21 -0700109void FastMixer::setNBLogWriter(NBLog::Writer *logWriter __unused)
Glenn Kasten22340022014-04-07 12:04:41 -0700110{
Glenn Kasten22340022014-04-07 12:04:41 -0700111}
112
113void FastMixer::onIdle()
114{
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800115 mPreIdle = *(const FastMixerState *)mCurrent;
116 mCurrent = &mPreIdle;
Glenn Kasten22340022014-04-07 12:04:41 -0700117}
118
119void FastMixer::onExit()
120{
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800121 delete mMixer;
Andy Hung1258c1a2014-05-23 21:22:17 -0700122 free(mMixerBuffer);
123 free(mSinkBuffer);
Glenn Kasten22340022014-04-07 12:04:41 -0700124}
125
126bool FastMixer::isSubClassCommand(FastThreadState::Command command)
127{
128 switch ((FastMixerState::Command) command) {
129 case FastMixerState::MIX:
130 case FastMixerState::WRITE:
131 case FastMixerState::MIX_WRITE:
132 return true;
133 default:
134 return false;
135 }
136}
137
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800138void FastMixer::updateMixerTrack(int index, Reason reason) {
139 const FastMixerState * const current = (const FastMixerState *) mCurrent;
140 const FastTrack * const fastTrack = &current->mFastTracks[index];
141
142 // check and update generation
143 if (reason == REASON_MODIFY && mGenerations[index] == fastTrack->mGeneration) {
144 return; // no change on an already configured track.
145 }
146 mGenerations[index] = fastTrack->mGeneration;
147
148 // mMixer == nullptr on configuration failure (check done after generation update).
149 if (mMixer == nullptr) {
150 return;
151 }
152
153 switch (reason) {
154 case REASON_REMOVE:
155 mMixer->destroy(index);
156 break;
157 case REASON_ADD: {
158 const status_t status = mMixer->create(
159 index, fastTrack->mChannelMask, fastTrack->mFormat, AUDIO_SESSION_OUTPUT_MIX);
160 LOG_ALWAYS_FATAL_IF(status != NO_ERROR,
161 "%s: cannot create fast track index"
162 " %d, mask %#x, format %#x in AudioMixer",
163 __func__, index, fastTrack->mChannelMask, fastTrack->mFormat);
164 }
165 [[fallthrough]]; // now fallthrough to update the newly created track.
166 case REASON_MODIFY:
167 mMixer->setBufferProvider(index, fastTrack->mBufferProvider);
168
169 float vlf, vrf;
170 if (fastTrack->mVolumeProvider != nullptr) {
171 const gain_minifloat_packed_t vlr = fastTrack->mVolumeProvider->getVolumeLR();
172 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
173 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
174 } else {
175 vlf = vrf = AudioMixer::UNITY_GAIN_FLOAT;
176 }
177
178 // set volume to avoid ramp whenever the track is updated (or created).
179 // Note: this does not distinguish from starting fresh or
180 // resuming from a paused state.
181 mMixer->setParameter(index, AudioMixer::VOLUME, AudioMixer::VOLUME0, &vlf);
182 mMixer->setParameter(index, AudioMixer::VOLUME, AudioMixer::VOLUME1, &vrf);
183
184 mMixer->setParameter(index, AudioMixer::RESAMPLE, AudioMixer::REMOVE, nullptr);
185 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::MAIN_BUFFER,
186 (void *)mMixerBuffer);
187 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::MIXER_FORMAT,
188 (void *)(uintptr_t)mMixerBufferFormat);
189 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::FORMAT,
190 (void *)(uintptr_t)fastTrack->mFormat);
191 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK,
192 (void *)(uintptr_t)fastTrack->mChannelMask);
193 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::MIXER_CHANNEL_MASK,
194 (void *)(uintptr_t)mSinkChannelMask);
195 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::HAPTIC_ENABLED,
196 (void *)(uintptr_t)fastTrack->mHapticPlaybackEnabled);
197 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::HAPTIC_INTENSITY,
198 (void *)(uintptr_t)fastTrack->mHapticIntensity);
199
200 mMixer->enable(index);
201 break;
202 default:
203 LOG_ALWAYS_FATAL("%s: invalid update reason %d", __func__, reason);
204 }
205}
206
Glenn Kasten22340022014-04-07 12:04:41 -0700207void FastMixer::onStateChange()
208{
Glenn Kasten4dd03b52015-03-03 11:32:04 -0800209 const FastMixerState * const current = (const FastMixerState *) mCurrent;
210 const FastMixerState * const previous = (const FastMixerState *) mPrevious;
211 FastMixerDumpState * const dumpState = (FastMixerDumpState *) mDumpState;
Glenn Kasten22340022014-04-07 12:04:41 -0700212 const size_t frameCount = current->mFrameCount;
213
Andy Hung818e7a32016-02-16 18:08:07 -0800214 // update boottime offset, in case it has changed
215 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
216 mBoottimeOffset.load();
217
Glenn Kasten22340022014-04-07 12:04:41 -0700218 // handle state change here, but since we want to diff the state,
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800219 // we're prepared for previous == &sInitial the first time through
Glenn Kasten22340022014-04-07 12:04:41 -0700220 unsigned previousTrackMask;
221
222 // check for change in output HAL configuration
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800223 NBAIO_Format previousFormat = mFormat;
224 if (current->mOutputSinkGen != mOutputSinkGen) {
225 mOutputSink = current->mOutputSink;
226 mOutputSinkGen = current->mOutputSinkGen;
jiabin245cdd92018-12-07 17:55:15 -0800227 mSinkChannelMask = current->mSinkChannelMask;
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +0100228 mBalance.setChannelMask(mSinkChannelMask);
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800229 if (mOutputSink == NULL) {
230 mFormat = Format_Invalid;
231 mSampleRate = 0;
Andy Hung9a592762014-07-21 21:56:01 -0700232 mSinkChannelCount = 0;
233 mSinkChannelMask = AUDIO_CHANNEL_NONE;
jiabin245cdd92018-12-07 17:55:15 -0800234 mAudioChannelCount = 0;
Glenn Kasten22340022014-04-07 12:04:41 -0700235 } else {
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800236 mFormat = mOutputSink->format();
237 mSampleRate = Format_sampleRate(mFormat);
238 mSinkChannelCount = Format_channelCount(mFormat);
Andy Hung9a592762014-07-21 21:56:01 -0700239 LOG_ALWAYS_FATAL_IF(mSinkChannelCount > AudioMixer::MAX_NUM_CHANNELS);
240
jiabin245cdd92018-12-07 17:55:15 -0800241 if (mSinkChannelMask == AUDIO_CHANNEL_NONE) {
242 mSinkChannelMask = audio_channel_out_mask_from_count(mSinkChannelCount);
243 }
244 mAudioChannelCount = mSinkChannelCount - audio_channel_count_from_out_mask(
245 mSinkChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Glenn Kasten22340022014-04-07 12:04:41 -0700246 }
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800247 dumpState->mSampleRate = mSampleRate;
Glenn Kasten22340022014-04-07 12:04:41 -0700248 }
249
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800250 if ((!Format_isEqual(mFormat, previousFormat)) || (frameCount != previous->mFrameCount)) {
Glenn Kasten22340022014-04-07 12:04:41 -0700251 // FIXME to avoid priority inversion, don't delete here
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800252 delete mMixer;
253 mMixer = NULL;
Andy Hung1258c1a2014-05-23 21:22:17 -0700254 free(mMixerBuffer);
Andy Hung45d68d32014-05-23 21:13:31 -0700255 mMixerBuffer = NULL;
Andy Hung1258c1a2014-05-23 21:22:17 -0700256 free(mSinkBuffer);
257 mSinkBuffer = NULL;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800258 if (frameCount > 0 && mSampleRate > 0) {
Glenn Kasten22340022014-04-07 12:04:41 -0700259 // FIXME new may block for unbounded time at internal mutex of the heap
260 // implementation; it would be better to have normal mixer allocate for us
261 // to avoid blocking here and to prevent possible priority inversion
Andy Hung1bc088a2018-02-09 15:57:31 -0800262 mMixer = new AudioMixer(frameCount, mSampleRate);
Glenn Kasten3ab8d662017-04-03 14:35:09 -0700263 // FIXME See the other FIXME at FastMixer::setNBLogWriter()
Eric Tan0513b5d2018-09-17 10:32:48 -0700264 NBLog::thread_params_t params;
265 params.frameCount = frameCount;
266 params.sampleRate = mSampleRate;
267 LOG_THREAD_PARAMS(params);
Andy Hung9a592762014-07-21 21:56:01 -0700268 const size_t mixerFrameSize = mSinkChannelCount
269 * audio_bytes_per_sample(mMixerBufferFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -0700270 mMixerBufferSize = mixerFrameSize * frameCount;
271 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
Andy Hung9a592762014-07-21 21:56:01 -0700272 const size_t sinkFrameSize = mSinkChannelCount
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800273 * audio_bytes_per_sample(mFormat.mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -0700274 if (sinkFrameSize > mixerFrameSize) { // need a sink buffer
275 mSinkBufferSize = sinkFrameSize * frameCount;
276 (void)posix_memalign(&mSinkBuffer, 32, mSinkBufferSize);
277 }
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800278 mPeriodNs = (frameCount * 1000000000LL) / mSampleRate; // 1.00
279 mUnderrunNs = (frameCount * 1750000000LL) / mSampleRate; // 1.75
280 mOverrunNs = (frameCount * 500000000LL) / mSampleRate; // 0.50
281 mForceNs = (frameCount * 950000000LL) / mSampleRate; // 0.95
282 mWarmupNsMin = (frameCount * 750000000LL) / mSampleRate; // 0.75
283 mWarmupNsMax = (frameCount * 1250000000LL) / mSampleRate; // 1.25
Glenn Kasten22340022014-04-07 12:04:41 -0700284 } else {
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800285 mPeriodNs = 0;
286 mUnderrunNs = 0;
287 mOverrunNs = 0;
288 mForceNs = 0;
289 mWarmupNsMin = 0;
290 mWarmupNsMax = LONG_MAX;
Glenn Kasten22340022014-04-07 12:04:41 -0700291 }
Andy Hung45d68d32014-05-23 21:13:31 -0700292 mMixerBufferState = UNDEFINED;
Glenn Kasten22340022014-04-07 12:04:41 -0700293 // we need to reconfigure all active tracks
294 previousTrackMask = 0;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800295 mFastTracksGen = current->mFastTracksGen - 1;
Glenn Kasten22340022014-04-07 12:04:41 -0700296 dumpState->mFrameCount = frameCount;
Andy Hung8946a282018-04-19 20:04:56 -0700297#ifdef TEE_SINK
298 mTee.set(mFormat, NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
299 mTee.setId(std::string("_") + std::to_string(mThreadIoHandle) + "_F");
300#endif
Glenn Kasten22340022014-04-07 12:04:41 -0700301 } else {
302 previousTrackMask = previous->mTrackMask;
303 }
Glenn Kasten732845c2013-08-23 09:26:31 -0700304
Glenn Kasten22340022014-04-07 12:04:41 -0700305 // check for change in active track set
306 const unsigned currentTrackMask = current->mTrackMask;
307 dumpState->mTrackMask = currentTrackMask;
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800308 dumpState->mNumTracks = popcount(currentTrackMask);
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800309 if (current->mFastTracksGen != mFastTracksGen) {
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700310
Glenn Kasten22340022014-04-07 12:04:41 -0700311 // process removed tracks first to avoid running out of track names
312 unsigned removedTracks = previousTrackMask & ~currentTrackMask;
313 while (removedTracks != 0) {
314 int i = __builtin_ctz(removedTracks);
315 removedTracks &= ~(1 << i);
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800316 updateMixerTrack(i, REASON_REMOVE);
Glenn Kasten22340022014-04-07 12:04:41 -0700317 // don't reset track dump state, since other side is ignoring it
Glenn Kasten22340022014-04-07 12:04:41 -0700318 }
319
320 // now process added tracks
321 unsigned addedTracks = currentTrackMask & ~previousTrackMask;
322 while (addedTracks != 0) {
323 int i = __builtin_ctz(addedTracks);
324 addedTracks &= ~(1 << i);
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800325 updateMixerTrack(i, REASON_ADD);
Glenn Kasten22340022014-04-07 12:04:41 -0700326 }
327
328 // finally process (potentially) modified tracks; these use the same slot
329 // but may have a different buffer provider or volume provider
330 unsigned modifiedTracks = currentTrackMask & previousTrackMask;
331 while (modifiedTracks != 0) {
332 int i = __builtin_ctz(modifiedTracks);
333 modifiedTracks &= ~(1 << i);
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800334 updateMixerTrack(i, REASON_MODIFY);
Glenn Kasten22340022014-04-07 12:04:41 -0700335 }
336
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800337 mFastTracksGen = current->mFastTracksGen;
Glenn Kasten22340022014-04-07 12:04:41 -0700338 }
339}
340
341void FastMixer::onWork()
342{
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700343 // TODO: pass an ID parameter to indicate which time series we want to write to in NBLog.cpp
344 // Or: pass both of these into a single call with a boolean
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700345 const FastMixerState * const current = (const FastMixerState *) mCurrent;
346 FastMixerDumpState * const dumpState = (FastMixerDumpState *) mDumpState;
347
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700348 if (mIsWarm) {
Eric Tane98dd6f2018-08-22 18:23:50 -0700349 // Logging timestamps for FastMixer is currently disabled to make memory room for logging
350 // other statistics in FastMixer.
351 // To re-enable, delete the #ifdef FASTMIXER_LOG_HIST_TS lines (and the #endif lines).
352#ifdef FASTMIXER_LOG_HIST_TS
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700353 LOG_HIST_TS();
Eric Tane98dd6f2018-08-22 18:23:50 -0700354#endif
355 //ALOGD("Eric FastMixer::onWork() mIsWarm");
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700356 } else {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700357 dumpState->mTimestampVerifier.discontinuity();
Eric Tane98dd6f2018-08-22 18:23:50 -0700358 // See comment in if block.
359#ifdef FASTMIXER_LOG_HIST_TS
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700360 LOG_AUDIO_STATE();
Eric Tane98dd6f2018-08-22 18:23:50 -0700361#endif
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700362 }
Glenn Kasten4dd03b52015-03-03 11:32:04 -0800363 const FastMixerState::Command command = mCommand;
Glenn Kasten22340022014-04-07 12:04:41 -0700364 const size_t frameCount = current->mFrameCount;
365
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800366 if ((command & FastMixerState::MIX) && (mMixer != NULL) && mIsWarm) {
Andy Hungef7c7fb2014-05-12 16:51:41 -0700367 ALOG_ASSERT(mMixerBuffer != NULL);
Mohan Kumar947ffa32014-12-12 15:16:46 +0530368
369 // AudioMixer::mState.enabledTracks is undefined if mState.hook == process__validate,
370 // so we keep a side copy of enabledTracks
371 bool anyEnabledTracks = false;
372
Glenn Kasten22340022014-04-07 12:04:41 -0700373 // for each track, update volume and check for underrun
374 unsigned currentTrackMask = current->mTrackMask;
375 while (currentTrackMask != 0) {
376 int i = __builtin_ctz(currentTrackMask);
377 currentTrackMask &= ~(1 << i);
378 const FastTrack* fastTrack = &current->mFastTracks[i];
379
Andy Hung818e7a32016-02-16 18:08:07 -0800380 const int64_t trackFramesWrittenButNotPresented =
381 mNativeFramesWrittenButNotPresented;
382 const int64_t trackFramesWritten = fastTrack->mBufferProvider->framesReleased();
383 ExtendedTimestamp perTrackTimestamp(mTimestamp);
384
385 // Can't provide an ExtendedTimestamp before first frame presented.
386 // Also, timestamp may not go to very last frame on stop().
387 if (trackFramesWritten >= trackFramesWrittenButNotPresented &&
388 perTrackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] > 0) {
389 perTrackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
390 trackFramesWritten - trackFramesWrittenButNotPresented;
391 } else {
392 perTrackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = 0;
393 perTrackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = -1;
Glenn Kasten22340022014-04-07 12:04:41 -0700394 }
Andy Hung818e7a32016-02-16 18:08:07 -0800395 perTrackTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = trackFramesWritten;
396 fastTrack->mBufferProvider->onTimestamp(perTrackTimestamp);
Glenn Kasten22340022014-04-07 12:04:41 -0700397
Andy Hung1bc088a2018-02-09 15:57:31 -0800398 const int name = i;
Glenn Kasten22340022014-04-07 12:04:41 -0700399 if (fastTrack->mVolumeProvider != NULL) {
Glenn Kastenc56f3422014-03-21 17:53:17 -0700400 gain_minifloat_packed_t vlr = fastTrack->mVolumeProvider->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -0700401 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
402 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
403
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800404 mMixer->setParameter(name, AudioMixer::RAMP_VOLUME, AudioMixer::VOLUME0, &vlf);
405 mMixer->setParameter(name, AudioMixer::RAMP_VOLUME, AudioMixer::VOLUME1, &vrf);
Glenn Kasten22340022014-04-07 12:04:41 -0700406 }
407 // FIXME The current implementation of framesReady() for fast tracks
408 // takes a tryLock, which can block
409 // up to 1 ms. If enough active tracks all blocked in sequence, this would result
410 // in the overall fast mix cycle being delayed. Should use a non-blocking FIFO.
411 size_t framesReady = fastTrack->mBufferProvider->framesReady();
412 if (ATRACE_ENABLED()) {
413 // I wish we had formatted trace names
414 char traceName[16];
415 strcpy(traceName, "fRdy");
416 traceName[4] = i + (i < 10 ? '0' : 'A' - 10);
417 traceName[5] = '\0';
418 ATRACE_INT(traceName, framesReady);
419 }
420 FastTrackDump *ftDump = &dumpState->mTracks[i];
421 FastTrackUnderruns underruns = ftDump->mUnderruns;
422 if (framesReady < frameCount) {
423 if (framesReady == 0) {
424 underruns.mBitFields.mEmpty++;
425 underruns.mBitFields.mMostRecent = UNDERRUN_EMPTY;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800426 mMixer->disable(name);
Glenn Kasten09474df2012-05-10 14:48:07 -0700427 } else {
Glenn Kasten22340022014-04-07 12:04:41 -0700428 // allow mixing partial buffer
429 underruns.mBitFields.mPartial++;
430 underruns.mBitFields.mMostRecent = UNDERRUN_PARTIAL;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800431 mMixer->enable(name);
Mohan Kumar947ffa32014-12-12 15:16:46 +0530432 anyEnabledTracks = true;
Glenn Kasten288ed212012-04-25 17:52:27 -0700433 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700434 } else {
Glenn Kasten22340022014-04-07 12:04:41 -0700435 underruns.mBitFields.mFull++;
436 underruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800437 mMixer->enable(name);
Mohan Kumar947ffa32014-12-12 15:16:46 +0530438 anyEnabledTracks = true;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700439 }
Glenn Kasten22340022014-04-07 12:04:41 -0700440 ftDump->mUnderruns = underruns;
441 ftDump->mFramesReady = framesReady;
Andy Hungb54c8542016-09-21 12:55:15 -0700442 ftDump->mFramesWritten = trackFramesWritten;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700443 }
444
Mohan Kumar947ffa32014-12-12 15:16:46 +0530445 if (anyEnabledTracks) {
446 // process() is CPU-bound
447 mMixer->process();
448 mMixerBufferState = MIXED;
449 } else if (mMixerBufferState != ZEROED) {
450 mMixerBufferState = UNDEFINED;
451 }
452
Andy Hung45d68d32014-05-23 21:13:31 -0700453 } else if (mMixerBufferState == MIXED) {
454 mMixerBufferState = UNDEFINED;
Glenn Kasten22340022014-04-07 12:04:41 -0700455 }
456 //bool didFullWrite = false; // dumpsys could display a count of partial writes
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800457 if ((command & FastMixerState::WRITE) && (mOutputSink != NULL) && (mMixerBuffer != NULL)) {
Andy Hung45d68d32014-05-23 21:13:31 -0700458 if (mMixerBufferState == UNDEFINED) {
Andy Hung1258c1a2014-05-23 21:22:17 -0700459 memset(mMixerBuffer, 0, mMixerBufferSize);
Andy Hung45d68d32014-05-23 21:13:31 -0700460 mMixerBufferState = ZEROED;
Glenn Kasten22340022014-04-07 12:04:41 -0700461 }
Andy Hung2ddee192015-12-18 17:34:44 -0800462
463 if (mMasterMono.load()) { // memory_order_seq_cst
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700464 mono_blend(mMixerBuffer, mMixerBufferFormat, Format_channelCount(mFormat), frameCount,
465 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -0800466 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +0100467
468 // Balance must take effect after mono conversion.
469 // mBalance detects zero balance within the class for speed (not needed here).
470 mBalance.setBalance(mMasterBalance.load());
471 mBalance.process((float *)mMixerBuffer, frameCount);
472
Glenn Kastenf59497b2015-01-26 16:35:47 -0800473 // prepare the buffer used to write to sink
Andy Hung1258c1a2014-05-23 21:22:17 -0700474 void *buffer = mSinkBuffer != NULL ? mSinkBuffer : mMixerBuffer;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800475 if (mFormat.mFormat != mMixerBufferFormat) { // sink format not the same as mixer format
476 memcpy_by_audio_format(buffer, mFormat.mFormat, mMixerBuffer, mMixerBufferFormat,
477 frameCount * Format_channelCount(mFormat));
Andy Hung1258c1a2014-05-23 21:22:17 -0700478 }
jiabin245cdd92018-12-07 17:55:15 -0800479 if (mSinkChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
480 // When there are haptic channels, the sample data is partially interleaved.
481 // Make the sample data fully interleaved here.
482 adjust_channels_non_destructive(buffer, mAudioChannelCount, buffer, mSinkChannelCount,
483 audio_bytes_per_sample(mFormat.mFormat),
484 frameCount * audio_bytes_per_frame(mAudioChannelCount, mFormat.mFormat));
485 }
Glenn Kasten22340022014-04-07 12:04:41 -0700486 // if non-NULL, then duplicate write() to this non-blocking sink
Andy Hung8946a282018-04-19 20:04:56 -0700487#ifdef TEE_SINK
488 mTee.write(buffer, frameCount);
489#endif
Glenn Kasten22340022014-04-07 12:04:41 -0700490 // FIXME write() is non-blocking and lock-free for a properly implemented NBAIO sink,
491 // but this code should be modified to handle both non-blocking and blocking sinks
492 dumpState->mWriteSequence++;
493 ATRACE_BEGIN("write");
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800494 ssize_t framesWritten = mOutputSink->write(buffer, frameCount);
Glenn Kasten22340022014-04-07 12:04:41 -0700495 ATRACE_END();
496 dumpState->mWriteSequence++;
497 if (framesWritten >= 0) {
498 ALOG_ASSERT((size_t) framesWritten <= frameCount);
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800499 mTotalNativeFramesWritten += framesWritten;
500 dumpState->mFramesWritten = mTotalNativeFramesWritten;
Glenn Kasten22340022014-04-07 12:04:41 -0700501 //if ((size_t) framesWritten == frameCount) {
502 // didFullWrite = true;
503 //}
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700504 } else {
Glenn Kasten22340022014-04-07 12:04:41 -0700505 dumpState->mWriteErrors++;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700506 }
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800507 mAttemptedWrite = true;
Glenn Kasten22340022014-04-07 12:04:41 -0700508 // FIXME count # of writes blocked excessively, CPU usage, etc. for dump
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700509
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700510 if (mIsWarm) {
511 ExtendedTimestamp timestamp; // local
512 status_t status = mOutputSink->getTimestamp(timestamp);
513 if (status == NO_ERROR) {
514 dumpState->mTimestampVerifier.add(
515 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
516 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
517 mSampleRate);
518 const int64_t totalNativeFramesPresented =
Andy Hung818e7a32016-02-16 18:08:07 -0800519 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700520 if (totalNativeFramesPresented <= mTotalNativeFramesWritten) {
521 mNativeFramesWrittenButNotPresented =
522 mTotalNativeFramesWritten - totalNativeFramesPresented;
523 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
524 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
525 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
526 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
527 // We don't compensate for server - kernel time difference and
528 // only update latency if we have valid info.
Eric Tane98dd6f2018-08-22 18:23:50 -0700529 const double latencyMs =
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700530 (double)mNativeFramesWrittenButNotPresented * 1000 / mSampleRate;
Eric Tane98dd6f2018-08-22 18:23:50 -0700531 dumpState->mLatencyMs = latencyMs;
532 LOG_LATENCY(latencyMs);
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700533 } else {
534 // HAL reported that more frames were presented than were written
535 mNativeFramesWrittenButNotPresented = 0;
536 status = INVALID_OPERATION;
537 }
Glenn Kasten22340022014-04-07 12:04:41 -0700538 } else {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700539 dumpState->mTimestampVerifier.error();
Glenn Kasten22340022014-04-07 12:04:41 -0700540 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700541 if (status == NO_ERROR) {
542 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] =
543 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
544 } else {
545 // fetch server time if we can't get timestamp
546 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] =
547 systemTime(SYSTEM_TIME_MONOTONIC);
548 // clear out kernel cached position as this may get rapidly stale
549 // if we never get a new valid timestamp
550 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = 0;
551 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = -1;
552 }
Andy Hung818e7a32016-02-16 18:08:07 -0800553 }
Glenn Kasten22340022014-04-07 12:04:41 -0700554 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700555}
556
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700557} // namespace android