blob: 88d4eafe19137857d2b799ae8a61d2195a80eabc [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>
30#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070031#include <utils/Trace.h>
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070032#include <system/audio.h>
Glenn Kasten214b4062015-03-02 14:15:47 -080033#ifdef FAST_THREAD_STATISTICS
Eric Tan5b13ff82018-07-27 11:20:17 -070034#include <audio_utils/Statistics.h>
Glenn Kasten0a14c4c2012-06-13 14:58:49 -070035#ifdef CPU_FREQUENCY_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -070036#include <cpustats/ThreadCpuUsage.h>
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070037#endif
Glenn Kasten0a14c4c2012-06-13 14:58:49 -070038#endif
jiabin245cdd92018-12-07 17:55:15 -080039#include <audio_utils/channels.h>
Andy Hung1258c1a2014-05-23 21:22:17 -070040#include <audio_utils/format.h>
jiabin245cdd92018-12-07 17:55:15 -080041#include <audio_utils/mono_blend.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070042#include <cutils/bitops.h>
Andy Hung068561c2017-01-03 17:09:32 -080043#include <media/AudioMixer.h>
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070044#include "FastMixer.h"
Glenn Kasteneef598c2017-04-03 14:41:13 -070045#include "TypedLogger.h"
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070046
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070047namespace android {
48
Glenn Kastene4a7ce22015-03-03 11:23:17 -080049/*static*/ const FastMixerState FastMixer::sInitial;
Glenn Kasten22340022014-04-07 12:04:41 -070050
Andy Hung1b998522021-06-07 16:43:58 -070051static audio_channel_mask_t getChannelMaskFromCount(size_t count) {
52 const audio_channel_mask_t mask = audio_channel_out_mask_from_count(count);
53 if (mask == AUDIO_CHANNEL_INVALID) {
54 // some counts have no positional masks. TODO: Update this to return index count?
55 return audio_channel_mask_for_index_assignment_from_count(count);
56 }
57 return mask;
58}
59
Andy Hung8946a282018-04-19 20:04:56 -070060FastMixer::FastMixer(audio_io_handle_t parentIoHandle)
61 : FastThread("cycle_ms", "load_us"),
Glenn Kastene4a7ce22015-03-03 11:23:17 -080062 // mFastTrackNames
63 // mGenerations
64 mOutputSink(NULL),
65 mOutputSinkGen(0),
66 mMixer(NULL),
Andy Hung1258c1a2014-05-23 21:22:17 -070067 mSinkBuffer(NULL),
68 mSinkBufferSize(0),
Andy Hung9a592762014-07-21 21:56:01 -070069 mSinkChannelCount(FCC_2),
Andy Hung45d68d32014-05-23 21:13:31 -070070 mMixerBuffer(NULL),
Andy Hung1258c1a2014-05-23 21:22:17 -070071 mMixerBufferSize(0),
Andy Hung45d68d32014-05-23 21:13:31 -070072 mMixerBufferState(UNDEFINED),
Glenn Kastene4a7ce22015-03-03 11:23:17 -080073 mFormat(Format_Invalid),
74 mSampleRate(0),
75 mFastTracksGen(0),
76 mTotalNativeFramesWritten(0),
Glenn Kasten22340022014-04-07 12:04:41 -070077 // timestamp
Andy Hung2ddee192015-12-18 17:34:44 -080078 mNativeFramesWrittenButNotPresented(0), // the = 0 is to silence the compiler
Andy Hung8946a282018-04-19 20:04:56 -070079 mMasterMono(false),
80 mThreadIoHandle(parentIoHandle)
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070081{
Andy Hung8946a282018-04-19 20:04:56 -070082 (void)mThreadIoHandle; // prevent unused warning, see C++17 [[maybe_unused]]
83
Glenn Kastene4a7ce22015-03-03 11:23:17 -080084 // FIXME pass sInitial as parameter to base class constructor, and make it static local
85 mPrevious = &sInitial;
86 mCurrent = &sInitial;
Glenn Kasten22340022014-04-07 12:04:41 -070087
Glenn Kastene4a7ce22015-03-03 11:23:17 -080088 mDummyDumpState = &mDummyFastMixerDumpState;
Andy Hung9a592762014-07-21 21:56:01 -070089 // TODO: Add channel mask to NBAIO_Format.
90 // We assume that the channel mask must be a valid positional channel mask.
Andy Hung1b998522021-06-07 16:43:58 -070091 mSinkChannelMask = getChannelMaskFromCount(mSinkChannelCount);
Glenn Kasten22340022014-04-07 12:04:41 -070092
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070093 unsigned i;
Glenn Kastendc2c50b2016-04-21 08:13:14 -070094 for (i = 0; i < FastMixerState::sMaxFastTracks; ++i) {
Glenn Kastene4a7ce22015-03-03 11:23:17 -080095 mGenerations[i] = 0;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070096 }
Glenn Kasten214b4062015-03-02 14:15:47 -080097#ifdef FAST_THREAD_STATISTICS
Glenn Kastene4a7ce22015-03-03 11:23:17 -080098 mOldLoad.tv_sec = 0;
99 mOldLoad.tv_nsec = 0;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700100#endif
Glenn Kasten22340022014-04-07 12:04:41 -0700101}
102
103FastMixer::~FastMixer()
104{
105}
106
107FastMixerStateQueue* FastMixer::sq()
108{
109 return &mSQ;
110}
111
112const FastThreadState *FastMixer::poll()
113{
114 return mSQ.poll();
115}
116
Mikhail Naganov9b6599e2019-07-29 15:23:21 -0700117void FastMixer::setNBLogWriter(NBLog::Writer *logWriter __unused)
Glenn Kasten22340022014-04-07 12:04:41 -0700118{
Glenn Kasten22340022014-04-07 12:04:41 -0700119}
120
121void FastMixer::onIdle()
122{
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800123 mPreIdle = *(const FastMixerState *)mCurrent;
124 mCurrent = &mPreIdle;
Glenn Kasten22340022014-04-07 12:04:41 -0700125}
126
127void FastMixer::onExit()
128{
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800129 delete mMixer;
Andy Hung1258c1a2014-05-23 21:22:17 -0700130 free(mMixerBuffer);
131 free(mSinkBuffer);
Glenn Kasten22340022014-04-07 12:04:41 -0700132}
133
134bool FastMixer::isSubClassCommand(FastThreadState::Command command)
135{
136 switch ((FastMixerState::Command) command) {
137 case FastMixerState::MIX:
138 case FastMixerState::WRITE:
139 case FastMixerState::MIX_WRITE:
140 return true;
141 default:
142 return false;
143 }
144}
145
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800146void FastMixer::updateMixerTrack(int index, Reason reason) {
147 const FastMixerState * const current = (const FastMixerState *) mCurrent;
148 const FastTrack * const fastTrack = &current->mFastTracks[index];
149
150 // check and update generation
151 if (reason == REASON_MODIFY && mGenerations[index] == fastTrack->mGeneration) {
152 return; // no change on an already configured track.
153 }
154 mGenerations[index] = fastTrack->mGeneration;
155
156 // mMixer == nullptr on configuration failure (check done after generation update).
157 if (mMixer == nullptr) {
158 return;
159 }
160
161 switch (reason) {
162 case REASON_REMOVE:
163 mMixer->destroy(index);
164 break;
165 case REASON_ADD: {
166 const status_t status = mMixer->create(
167 index, fastTrack->mChannelMask, fastTrack->mFormat, AUDIO_SESSION_OUTPUT_MIX);
168 LOG_ALWAYS_FATAL_IF(status != NO_ERROR,
169 "%s: cannot create fast track index"
170 " %d, mask %#x, format %#x in AudioMixer",
171 __func__, index, fastTrack->mChannelMask, fastTrack->mFormat);
172 }
173 [[fallthrough]]; // now fallthrough to update the newly created track.
174 case REASON_MODIFY:
175 mMixer->setBufferProvider(index, fastTrack->mBufferProvider);
176
177 float vlf, vrf;
178 if (fastTrack->mVolumeProvider != nullptr) {
179 const gain_minifloat_packed_t vlr = fastTrack->mVolumeProvider->getVolumeLR();
180 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
181 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
182 } else {
183 vlf = vrf = AudioMixer::UNITY_GAIN_FLOAT;
184 }
185
186 // set volume to avoid ramp whenever the track is updated (or created).
187 // Note: this does not distinguish from starting fresh or
188 // resuming from a paused state.
189 mMixer->setParameter(index, AudioMixer::VOLUME, AudioMixer::VOLUME0, &vlf);
190 mMixer->setParameter(index, AudioMixer::VOLUME, AudioMixer::VOLUME1, &vrf);
191
192 mMixer->setParameter(index, AudioMixer::RESAMPLE, AudioMixer::REMOVE, nullptr);
193 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::MAIN_BUFFER,
194 (void *)mMixerBuffer);
195 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::MIXER_FORMAT,
196 (void *)(uintptr_t)mMixerBufferFormat);
197 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::FORMAT,
198 (void *)(uintptr_t)fastTrack->mFormat);
199 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK,
200 (void *)(uintptr_t)fastTrack->mChannelMask);
201 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::MIXER_CHANNEL_MASK,
202 (void *)(uintptr_t)mSinkChannelMask);
203 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::HAPTIC_ENABLED,
204 (void *)(uintptr_t)fastTrack->mHapticPlaybackEnabled);
205 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::HAPTIC_INTENSITY,
206 (void *)(uintptr_t)fastTrack->mHapticIntensity);
207
208 mMixer->enable(index);
209 break;
210 default:
211 LOG_ALWAYS_FATAL("%s: invalid update reason %d", __func__, reason);
212 }
213}
214
Glenn Kasten22340022014-04-07 12:04:41 -0700215void FastMixer::onStateChange()
216{
Glenn Kasten4dd03b52015-03-03 11:32:04 -0800217 const FastMixerState * const current = (const FastMixerState *) mCurrent;
218 const FastMixerState * const previous = (const FastMixerState *) mPrevious;
219 FastMixerDumpState * const dumpState = (FastMixerDumpState *) mDumpState;
Glenn Kasten22340022014-04-07 12:04:41 -0700220 const size_t frameCount = current->mFrameCount;
221
Andy Hung818e7a32016-02-16 18:08:07 -0800222 // update boottime offset, in case it has changed
223 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
224 mBoottimeOffset.load();
225
Glenn Kasten22340022014-04-07 12:04:41 -0700226 // handle state change here, but since we want to diff the state,
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800227 // we're prepared for previous == &sInitial the first time through
Glenn Kasten22340022014-04-07 12:04:41 -0700228 unsigned previousTrackMask;
229
230 // check for change in output HAL configuration
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800231 NBAIO_Format previousFormat = mFormat;
232 if (current->mOutputSinkGen != mOutputSinkGen) {
233 mOutputSink = current->mOutputSink;
234 mOutputSinkGen = current->mOutputSinkGen;
jiabin245cdd92018-12-07 17:55:15 -0800235 mSinkChannelMask = current->mSinkChannelMask;
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +0100236 mBalance.setChannelMask(mSinkChannelMask);
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800237 if (mOutputSink == NULL) {
238 mFormat = Format_Invalid;
239 mSampleRate = 0;
Andy Hung9a592762014-07-21 21:56:01 -0700240 mSinkChannelCount = 0;
241 mSinkChannelMask = AUDIO_CHANNEL_NONE;
jiabin245cdd92018-12-07 17:55:15 -0800242 mAudioChannelCount = 0;
Glenn Kasten22340022014-04-07 12:04:41 -0700243 } else {
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800244 mFormat = mOutputSink->format();
245 mSampleRate = Format_sampleRate(mFormat);
246 mSinkChannelCount = Format_channelCount(mFormat);
Andy Hung9a592762014-07-21 21:56:01 -0700247 LOG_ALWAYS_FATAL_IF(mSinkChannelCount > AudioMixer::MAX_NUM_CHANNELS);
248
jiabin245cdd92018-12-07 17:55:15 -0800249 if (mSinkChannelMask == AUDIO_CHANNEL_NONE) {
Andy Hung1b998522021-06-07 16:43:58 -0700250 mSinkChannelMask = getChannelMaskFromCount(mSinkChannelCount);
jiabin245cdd92018-12-07 17:55:15 -0800251 }
252 mAudioChannelCount = mSinkChannelCount - audio_channel_count_from_out_mask(
253 mSinkChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Glenn Kasten22340022014-04-07 12:04:41 -0700254 }
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800255 dumpState->mSampleRate = mSampleRate;
Glenn Kasten22340022014-04-07 12:04:41 -0700256 }
257
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800258 if ((!Format_isEqual(mFormat, previousFormat)) || (frameCount != previous->mFrameCount)) {
Glenn Kasten22340022014-04-07 12:04:41 -0700259 // FIXME to avoid priority inversion, don't delete here
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800260 delete mMixer;
261 mMixer = NULL;
Andy Hung1258c1a2014-05-23 21:22:17 -0700262 free(mMixerBuffer);
Andy Hung45d68d32014-05-23 21:13:31 -0700263 mMixerBuffer = NULL;
Andy Hung1258c1a2014-05-23 21:22:17 -0700264 free(mSinkBuffer);
265 mSinkBuffer = NULL;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800266 if (frameCount > 0 && mSampleRate > 0) {
Glenn Kasten22340022014-04-07 12:04:41 -0700267 // FIXME new may block for unbounded time at internal mutex of the heap
268 // implementation; it would be better to have normal mixer allocate for us
269 // to avoid blocking here and to prevent possible priority inversion
Andy Hung1bc088a2018-02-09 15:57:31 -0800270 mMixer = new AudioMixer(frameCount, mSampleRate);
Glenn Kasten3ab8d662017-04-03 14:35:09 -0700271 // FIXME See the other FIXME at FastMixer::setNBLogWriter()
Eric Tan0513b5d2018-09-17 10:32:48 -0700272 NBLog::thread_params_t params;
273 params.frameCount = frameCount;
274 params.sampleRate = mSampleRate;
275 LOG_THREAD_PARAMS(params);
Andy Hung9a592762014-07-21 21:56:01 -0700276 const size_t mixerFrameSize = mSinkChannelCount
277 * audio_bytes_per_sample(mMixerBufferFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -0700278 mMixerBufferSize = mixerFrameSize * frameCount;
279 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
Andy Hung9a592762014-07-21 21:56:01 -0700280 const size_t sinkFrameSize = mSinkChannelCount
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800281 * audio_bytes_per_sample(mFormat.mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -0700282 if (sinkFrameSize > mixerFrameSize) { // need a sink buffer
283 mSinkBufferSize = sinkFrameSize * frameCount;
284 (void)posix_memalign(&mSinkBuffer, 32, mSinkBufferSize);
285 }
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800286 mPeriodNs = (frameCount * 1000000000LL) / mSampleRate; // 1.00
287 mUnderrunNs = (frameCount * 1750000000LL) / mSampleRate; // 1.75
288 mOverrunNs = (frameCount * 500000000LL) / mSampleRate; // 0.50
289 mForceNs = (frameCount * 950000000LL) / mSampleRate; // 0.95
290 mWarmupNsMin = (frameCount * 750000000LL) / mSampleRate; // 0.75
291 mWarmupNsMax = (frameCount * 1250000000LL) / mSampleRate; // 1.25
Glenn Kasten22340022014-04-07 12:04:41 -0700292 } else {
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800293 mPeriodNs = 0;
294 mUnderrunNs = 0;
295 mOverrunNs = 0;
296 mForceNs = 0;
297 mWarmupNsMin = 0;
298 mWarmupNsMax = LONG_MAX;
Glenn Kasten22340022014-04-07 12:04:41 -0700299 }
Andy Hung45d68d32014-05-23 21:13:31 -0700300 mMixerBufferState = UNDEFINED;
Glenn Kasten22340022014-04-07 12:04:41 -0700301 // we need to reconfigure all active tracks
302 previousTrackMask = 0;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800303 mFastTracksGen = current->mFastTracksGen - 1;
Glenn Kasten22340022014-04-07 12:04:41 -0700304 dumpState->mFrameCount = frameCount;
Andy Hung8946a282018-04-19 20:04:56 -0700305#ifdef TEE_SINK
306 mTee.set(mFormat, NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
307 mTee.setId(std::string("_") + std::to_string(mThreadIoHandle) + "_F");
308#endif
Glenn Kasten22340022014-04-07 12:04:41 -0700309 } else {
310 previousTrackMask = previous->mTrackMask;
311 }
Glenn Kasten732845c2013-08-23 09:26:31 -0700312
Glenn Kasten22340022014-04-07 12:04:41 -0700313 // check for change in active track set
314 const unsigned currentTrackMask = current->mTrackMask;
315 dumpState->mTrackMask = currentTrackMask;
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800316 dumpState->mNumTracks = popcount(currentTrackMask);
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800317 if (current->mFastTracksGen != mFastTracksGen) {
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700318
Glenn Kasten22340022014-04-07 12:04:41 -0700319 // process removed tracks first to avoid running out of track names
320 unsigned removedTracks = previousTrackMask & ~currentTrackMask;
321 while (removedTracks != 0) {
322 int i = __builtin_ctz(removedTracks);
323 removedTracks &= ~(1 << i);
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800324 updateMixerTrack(i, REASON_REMOVE);
Glenn Kasten22340022014-04-07 12:04:41 -0700325 // don't reset track dump state, since other side is ignoring it
Glenn Kasten22340022014-04-07 12:04:41 -0700326 }
327
328 // now process added tracks
329 unsigned addedTracks = currentTrackMask & ~previousTrackMask;
330 while (addedTracks != 0) {
331 int i = __builtin_ctz(addedTracks);
332 addedTracks &= ~(1 << i);
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800333 updateMixerTrack(i, REASON_ADD);
Glenn Kasten22340022014-04-07 12:04:41 -0700334 }
335
336 // finally process (potentially) modified tracks; these use the same slot
337 // but may have a different buffer provider or volume provider
338 unsigned modifiedTracks = currentTrackMask & previousTrackMask;
339 while (modifiedTracks != 0) {
340 int i = __builtin_ctz(modifiedTracks);
341 modifiedTracks &= ~(1 << i);
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800342 updateMixerTrack(i, REASON_MODIFY);
Glenn Kasten22340022014-04-07 12:04:41 -0700343 }
344
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800345 mFastTracksGen = current->mFastTracksGen;
Glenn Kasten22340022014-04-07 12:04:41 -0700346 }
347}
348
349void FastMixer::onWork()
350{
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700351 // TODO: pass an ID parameter to indicate which time series we want to write to in NBLog.cpp
352 // Or: pass both of these into a single call with a boolean
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700353 const FastMixerState * const current = (const FastMixerState *) mCurrent;
354 FastMixerDumpState * const dumpState = (FastMixerDumpState *) mDumpState;
355
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700356 if (mIsWarm) {
Eric Tane98dd6f2018-08-22 18:23:50 -0700357 // Logging timestamps for FastMixer is currently disabled to make memory room for logging
358 // other statistics in FastMixer.
359 // To re-enable, delete the #ifdef FASTMIXER_LOG_HIST_TS lines (and the #endif lines).
360#ifdef FASTMIXER_LOG_HIST_TS
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700361 LOG_HIST_TS();
Eric Tane98dd6f2018-08-22 18:23:50 -0700362#endif
363 //ALOGD("Eric FastMixer::onWork() mIsWarm");
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700364 } else {
Dean Wheatley12473e92021-03-18 23:00:55 +1100365 dumpState->mTimestampVerifier.discontinuity(
366 dumpState->mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Eric Tane98dd6f2018-08-22 18:23:50 -0700367 // See comment in if block.
368#ifdef FASTMIXER_LOG_HIST_TS
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700369 LOG_AUDIO_STATE();
Eric Tane98dd6f2018-08-22 18:23:50 -0700370#endif
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700371 }
Glenn Kasten4dd03b52015-03-03 11:32:04 -0800372 const FastMixerState::Command command = mCommand;
Glenn Kasten22340022014-04-07 12:04:41 -0700373 const size_t frameCount = current->mFrameCount;
374
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800375 if ((command & FastMixerState::MIX) && (mMixer != NULL) && mIsWarm) {
Andy Hungef7c7fb2014-05-12 16:51:41 -0700376 ALOG_ASSERT(mMixerBuffer != NULL);
Mohan Kumar947ffa32014-12-12 15:16:46 +0530377
378 // AudioMixer::mState.enabledTracks is undefined if mState.hook == process__validate,
379 // so we keep a side copy of enabledTracks
380 bool anyEnabledTracks = false;
381
Glenn Kasten22340022014-04-07 12:04:41 -0700382 // for each track, update volume and check for underrun
383 unsigned currentTrackMask = current->mTrackMask;
384 while (currentTrackMask != 0) {
385 int i = __builtin_ctz(currentTrackMask);
386 currentTrackMask &= ~(1 << i);
387 const FastTrack* fastTrack = &current->mFastTracks[i];
388
Andy Hung818e7a32016-02-16 18:08:07 -0800389 const int64_t trackFramesWrittenButNotPresented =
390 mNativeFramesWrittenButNotPresented;
391 const int64_t trackFramesWritten = fastTrack->mBufferProvider->framesReleased();
392 ExtendedTimestamp perTrackTimestamp(mTimestamp);
393
394 // Can't provide an ExtendedTimestamp before first frame presented.
395 // Also, timestamp may not go to very last frame on stop().
396 if (trackFramesWritten >= trackFramesWrittenButNotPresented &&
397 perTrackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] > 0) {
398 perTrackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
399 trackFramesWritten - trackFramesWrittenButNotPresented;
400 } else {
401 perTrackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = 0;
402 perTrackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = -1;
Glenn Kasten22340022014-04-07 12:04:41 -0700403 }
Andy Hung818e7a32016-02-16 18:08:07 -0800404 perTrackTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = trackFramesWritten;
405 fastTrack->mBufferProvider->onTimestamp(perTrackTimestamp);
Glenn Kasten22340022014-04-07 12:04:41 -0700406
Andy Hung1bc088a2018-02-09 15:57:31 -0800407 const int name = i;
Glenn Kasten22340022014-04-07 12:04:41 -0700408 if (fastTrack->mVolumeProvider != NULL) {
Glenn Kastenc56f3422014-03-21 17:53:17 -0700409 gain_minifloat_packed_t vlr = fastTrack->mVolumeProvider->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -0700410 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
411 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
412
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800413 mMixer->setParameter(name, AudioMixer::RAMP_VOLUME, AudioMixer::VOLUME0, &vlf);
414 mMixer->setParameter(name, AudioMixer::RAMP_VOLUME, AudioMixer::VOLUME1, &vrf);
Glenn Kasten22340022014-04-07 12:04:41 -0700415 }
416 // FIXME The current implementation of framesReady() for fast tracks
417 // takes a tryLock, which can block
418 // up to 1 ms. If enough active tracks all blocked in sequence, this would result
419 // in the overall fast mix cycle being delayed. Should use a non-blocking FIFO.
420 size_t framesReady = fastTrack->mBufferProvider->framesReady();
421 if (ATRACE_ENABLED()) {
422 // I wish we had formatted trace names
423 char traceName[16];
424 strcpy(traceName, "fRdy");
425 traceName[4] = i + (i < 10 ? '0' : 'A' - 10);
426 traceName[5] = '\0';
427 ATRACE_INT(traceName, framesReady);
428 }
429 FastTrackDump *ftDump = &dumpState->mTracks[i];
430 FastTrackUnderruns underruns = ftDump->mUnderruns;
431 if (framesReady < frameCount) {
432 if (framesReady == 0) {
433 underruns.mBitFields.mEmpty++;
434 underruns.mBitFields.mMostRecent = UNDERRUN_EMPTY;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800435 mMixer->disable(name);
Glenn Kasten09474df2012-05-10 14:48:07 -0700436 } else {
Glenn Kasten22340022014-04-07 12:04:41 -0700437 // allow mixing partial buffer
438 underruns.mBitFields.mPartial++;
439 underruns.mBitFields.mMostRecent = UNDERRUN_PARTIAL;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800440 mMixer->enable(name);
Mohan Kumar947ffa32014-12-12 15:16:46 +0530441 anyEnabledTracks = true;
Glenn Kasten288ed212012-04-25 17:52:27 -0700442 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700443 } else {
Glenn Kasten22340022014-04-07 12:04:41 -0700444 underruns.mBitFields.mFull++;
445 underruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800446 mMixer->enable(name);
Mohan Kumar947ffa32014-12-12 15:16:46 +0530447 anyEnabledTracks = true;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700448 }
Glenn Kasten22340022014-04-07 12:04:41 -0700449 ftDump->mUnderruns = underruns;
450 ftDump->mFramesReady = framesReady;
Andy Hungb54c8542016-09-21 12:55:15 -0700451 ftDump->mFramesWritten = trackFramesWritten;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700452 }
453
Mohan Kumar947ffa32014-12-12 15:16:46 +0530454 if (anyEnabledTracks) {
455 // process() is CPU-bound
456 mMixer->process();
457 mMixerBufferState = MIXED;
458 } else if (mMixerBufferState != ZEROED) {
459 mMixerBufferState = UNDEFINED;
460 }
461
Andy Hung45d68d32014-05-23 21:13:31 -0700462 } else if (mMixerBufferState == MIXED) {
463 mMixerBufferState = UNDEFINED;
Glenn Kasten22340022014-04-07 12:04:41 -0700464 }
465 //bool didFullWrite = false; // dumpsys could display a count of partial writes
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800466 if ((command & FastMixerState::WRITE) && (mOutputSink != NULL) && (mMixerBuffer != NULL)) {
Andy Hung45d68d32014-05-23 21:13:31 -0700467 if (mMixerBufferState == UNDEFINED) {
Andy Hung1258c1a2014-05-23 21:22:17 -0700468 memset(mMixerBuffer, 0, mMixerBufferSize);
Andy Hung45d68d32014-05-23 21:13:31 -0700469 mMixerBufferState = ZEROED;
Glenn Kasten22340022014-04-07 12:04:41 -0700470 }
Andy Hung2ddee192015-12-18 17:34:44 -0800471
472 if (mMasterMono.load()) { // memory_order_seq_cst
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700473 mono_blend(mMixerBuffer, mMixerBufferFormat, Format_channelCount(mFormat), frameCount,
474 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -0800475 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +0100476
477 // Balance must take effect after mono conversion.
478 // mBalance detects zero balance within the class for speed (not needed here).
479 mBalance.setBalance(mMasterBalance.load());
480 mBalance.process((float *)mMixerBuffer, frameCount);
481
Glenn Kastenf59497b2015-01-26 16:35:47 -0800482 // prepare the buffer used to write to sink
Andy Hung1258c1a2014-05-23 21:22:17 -0700483 void *buffer = mSinkBuffer != NULL ? mSinkBuffer : mMixerBuffer;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800484 if (mFormat.mFormat != mMixerBufferFormat) { // sink format not the same as mixer format
485 memcpy_by_audio_format(buffer, mFormat.mFormat, mMixerBuffer, mMixerBufferFormat,
486 frameCount * Format_channelCount(mFormat));
Andy Hung1258c1a2014-05-23 21:22:17 -0700487 }
jiabin245cdd92018-12-07 17:55:15 -0800488 if (mSinkChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
489 // When there are haptic channels, the sample data is partially interleaved.
490 // Make the sample data fully interleaved here.
491 adjust_channels_non_destructive(buffer, mAudioChannelCount, buffer, mSinkChannelCount,
492 audio_bytes_per_sample(mFormat.mFormat),
493 frameCount * audio_bytes_per_frame(mAudioChannelCount, mFormat.mFormat));
494 }
Glenn Kasten22340022014-04-07 12:04:41 -0700495 // if non-NULL, then duplicate write() to this non-blocking sink
Andy Hung8946a282018-04-19 20:04:56 -0700496#ifdef TEE_SINK
497 mTee.write(buffer, frameCount);
498#endif
Glenn Kasten22340022014-04-07 12:04:41 -0700499 // FIXME write() is non-blocking and lock-free for a properly implemented NBAIO sink,
500 // but this code should be modified to handle both non-blocking and blocking sinks
501 dumpState->mWriteSequence++;
502 ATRACE_BEGIN("write");
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800503 ssize_t framesWritten = mOutputSink->write(buffer, frameCount);
Glenn Kasten22340022014-04-07 12:04:41 -0700504 ATRACE_END();
505 dumpState->mWriteSequence++;
506 if (framesWritten >= 0) {
507 ALOG_ASSERT((size_t) framesWritten <= frameCount);
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800508 mTotalNativeFramesWritten += framesWritten;
509 dumpState->mFramesWritten = mTotalNativeFramesWritten;
Glenn Kasten22340022014-04-07 12:04:41 -0700510 //if ((size_t) framesWritten == frameCount) {
511 // didFullWrite = true;
512 //}
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700513 } else {
Glenn Kasten22340022014-04-07 12:04:41 -0700514 dumpState->mWriteErrors++;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700515 }
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800516 mAttemptedWrite = true;
Glenn Kasten22340022014-04-07 12:04:41 -0700517 // FIXME count # of writes blocked excessively, CPU usage, etc. for dump
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700518
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700519 if (mIsWarm) {
520 ExtendedTimestamp timestamp; // local
521 status_t status = mOutputSink->getTimestamp(timestamp);
522 if (status == NO_ERROR) {
523 dumpState->mTimestampVerifier.add(
524 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
525 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
526 mSampleRate);
527 const int64_t totalNativeFramesPresented =
Andy Hung818e7a32016-02-16 18:08:07 -0800528 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700529 if (totalNativeFramesPresented <= mTotalNativeFramesWritten) {
530 mNativeFramesWrittenButNotPresented =
531 mTotalNativeFramesWritten - totalNativeFramesPresented;
532 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
533 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
534 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
535 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
536 // We don't compensate for server - kernel time difference and
537 // only update latency if we have valid info.
Eric Tane98dd6f2018-08-22 18:23:50 -0700538 const double latencyMs =
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700539 (double)mNativeFramesWrittenButNotPresented * 1000 / mSampleRate;
Eric Tane98dd6f2018-08-22 18:23:50 -0700540 dumpState->mLatencyMs = latencyMs;
541 LOG_LATENCY(latencyMs);
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700542 } else {
543 // HAL reported that more frames were presented than were written
544 mNativeFramesWrittenButNotPresented = 0;
545 status = INVALID_OPERATION;
546 }
Glenn Kasten22340022014-04-07 12:04:41 -0700547 } else {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700548 dumpState->mTimestampVerifier.error();
Glenn Kasten22340022014-04-07 12:04:41 -0700549 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700550 if (status == NO_ERROR) {
551 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] =
552 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
553 } else {
554 // fetch server time if we can't get timestamp
555 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] =
556 systemTime(SYSTEM_TIME_MONOTONIC);
557 // clear out kernel cached position as this may get rapidly stale
558 // if we never get a new valid timestamp
559 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = 0;
560 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = -1;
561 }
Andy Hung818e7a32016-02-16 18:08:07 -0800562 }
Glenn Kasten22340022014-04-07 12:04:41 -0700563 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700564}
565
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700566} // namespace android