blob: 13b21ecd8b824fa384dee012d0f210b8ff5207eb [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>
33#ifdef FAST_MIXER_STATISTICS
34#include <cpustats/CentralTendencyStatistics.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
Andy Hung1258c1a2014-05-23 21:22:17 -070039#include <audio_utils/format.h>
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070040#include "AudioMixer.h"
41#include "FastMixer.h"
42
Glenn Kasten7fc97ba2013-07-16 17:18:58 -070043#define FCC_2 2 // fixed channel count assumption
44
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070045namespace android {
46
Glenn Kasten22340022014-04-07 12:04:41 -070047/*static*/ const FastMixerState FastMixer::initial;
48
49FastMixer::FastMixer() : FastThread(),
50 slopNs(0),
51 // fastTrackNames
52 // generations
53 outputSink(NULL),
54 outputSinkGen(0),
55 mixer(NULL),
Andy Hung1258c1a2014-05-23 21:22:17 -070056 mSinkBuffer(NULL),
57 mSinkBufferSize(0),
Andy Hung45d68d32014-05-23 21:13:31 -070058 mMixerBuffer(NULL),
Andy Hung1258c1a2014-05-23 21:22:17 -070059 mMixerBufferSize(0),
60 mMixerBufferFormat(AUDIO_FORMAT_PCM_16_BIT),
Andy Hung45d68d32014-05-23 21:13:31 -070061 mMixerBufferState(UNDEFINED),
Glenn Kasten22340022014-04-07 12:04:41 -070062 format(Format_Invalid),
63 sampleRate(0),
64 fastTracksGen(0),
65 totalNativeFramesWritten(0),
66 // timestamp
67 nativeFramesWrittenButNotPresented(0) // the = 0 is to silence the compiler
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070068{
Glenn Kasten22340022014-04-07 12:04:41 -070069 // FIXME pass initial as parameter to base class constructor, and make it static local
70 previous = &initial;
71 current = &initial;
72
73 mDummyDumpState = &dummyDumpState;
74
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070075 unsigned i;
76 for (i = 0; i < FastMixerState::kMaxFastTracks; ++i) {
77 fastTrackNames[i] = -1;
78 generations[i] = 0;
79 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070080#ifdef FAST_MIXER_STATISTICS
Glenn Kasten22340022014-04-07 12:04:41 -070081 oldLoad.tv_sec = 0;
82 oldLoad.tv_nsec = 0;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070083#endif
Glenn Kasten22340022014-04-07 12:04:41 -070084}
85
86FastMixer::~FastMixer()
87{
88}
89
90FastMixerStateQueue* FastMixer::sq()
91{
92 return &mSQ;
93}
94
95const FastThreadState *FastMixer::poll()
96{
97 return mSQ.poll();
98}
99
100void FastMixer::setLog(NBLog::Writer *logWriter)
101{
102 if (mixer != NULL) {
103 mixer->setLog(logWriter);
104 }
105}
106
107void FastMixer::onIdle()
108{
109 preIdle = *(const FastMixerState *)current;
110 current = &preIdle;
111}
112
113void FastMixer::onExit()
114{
115 delete mixer;
Andy Hung1258c1a2014-05-23 21:22:17 -0700116 free(mMixerBuffer);
117 free(mSinkBuffer);
Glenn Kasten22340022014-04-07 12:04:41 -0700118}
119
120bool FastMixer::isSubClassCommand(FastThreadState::Command command)
121{
122 switch ((FastMixerState::Command) command) {
123 case FastMixerState::MIX:
124 case FastMixerState::WRITE:
125 case FastMixerState::MIX_WRITE:
126 return true;
127 default:
128 return false;
129 }
130}
131
132void FastMixer::onStateChange()
133{
134 const FastMixerState * const current = (const FastMixerState *) this->current;
135 const FastMixerState * const previous = (const FastMixerState *) this->previous;
136 FastMixerDumpState * const dumpState = (FastMixerDumpState *) this->dumpState;
137 const size_t frameCount = current->mFrameCount;
138
139 // handle state change here, but since we want to diff the state,
140 // we're prepared for previous == &initial the first time through
141 unsigned previousTrackMask;
142
143 // check for change in output HAL configuration
144 NBAIO_Format previousFormat = format;
145 if (current->mOutputSinkGen != outputSinkGen) {
146 outputSink = current->mOutputSink;
147 outputSinkGen = current->mOutputSinkGen;
148 if (outputSink == NULL) {
149 format = Format_Invalid;
150 sampleRate = 0;
151 } else {
152 format = outputSink->format();
153 sampleRate = Format_sampleRate(format);
154 ALOG_ASSERT(Format_channelCount(format) == FCC_2);
155 }
156 dumpState->mSampleRate = sampleRate;
157 }
158
159 if ((!Format_isEqual(format, previousFormat)) || (frameCount != previous->mFrameCount)) {
160 // FIXME to avoid priority inversion, don't delete here
161 delete mixer;
162 mixer = NULL;
Andy Hung1258c1a2014-05-23 21:22:17 -0700163 free(mMixerBuffer);
Andy Hung45d68d32014-05-23 21:13:31 -0700164 mMixerBuffer = NULL;
Andy Hung1258c1a2014-05-23 21:22:17 -0700165 free(mSinkBuffer);
166 mSinkBuffer = NULL;
Glenn Kasten22340022014-04-07 12:04:41 -0700167 if (frameCount > 0 && sampleRate > 0) {
168 // FIXME new may block for unbounded time at internal mutex of the heap
169 // implementation; it would be better to have normal mixer allocate for us
170 // to avoid blocking here and to prevent possible priority inversion
171 mixer = new AudioMixer(frameCount, sampleRate, FastMixerState::kMaxFastTracks);
Andy Hung1258c1a2014-05-23 21:22:17 -0700172 const size_t mixerFrameSize = FCC_2 * audio_bytes_per_sample(mMixerBufferFormat);
173 mMixerBufferSize = mixerFrameSize * frameCount;
174 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
175 const size_t sinkFrameSize = FCC_2 * audio_bytes_per_sample(format.mFormat);
176 if (sinkFrameSize > mixerFrameSize) { // need a sink buffer
177 mSinkBufferSize = sinkFrameSize * frameCount;
178 (void)posix_memalign(&mSinkBuffer, 32, mSinkBufferSize);
179 }
Glenn Kasten22340022014-04-07 12:04:41 -0700180 periodNs = (frameCount * 1000000000LL) / sampleRate; // 1.00
181 underrunNs = (frameCount * 1750000000LL) / sampleRate; // 1.75
182 overrunNs = (frameCount * 500000000LL) / sampleRate; // 0.50
183 forceNs = (frameCount * 950000000LL) / sampleRate; // 0.95
184 warmupNs = (frameCount * 500000000LL) / sampleRate; // 0.50
185 } else {
186 periodNs = 0;
187 underrunNs = 0;
188 overrunNs = 0;
189 forceNs = 0;
190 warmupNs = 0;
191 }
Andy Hung45d68d32014-05-23 21:13:31 -0700192 mMixerBufferState = UNDEFINED;
Glenn Kasten22340022014-04-07 12:04:41 -0700193#if !LOG_NDEBUG
194 for (unsigned i = 0; i < FastMixerState::kMaxFastTracks; ++i) {
195 fastTrackNames[i] = -1;
196 }
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700197#endif
Glenn Kasten22340022014-04-07 12:04:41 -0700198 // we need to reconfigure all active tracks
199 previousTrackMask = 0;
200 fastTracksGen = current->mFastTracksGen - 1;
201 dumpState->mFrameCount = frameCount;
202 } else {
203 previousTrackMask = previous->mTrackMask;
204 }
Glenn Kasten732845c2013-08-23 09:26:31 -0700205
Glenn Kasten22340022014-04-07 12:04:41 -0700206 // check for change in active track set
207 const unsigned currentTrackMask = current->mTrackMask;
208 dumpState->mTrackMask = currentTrackMask;
209 if (current->mFastTracksGen != fastTracksGen) {
Andy Hung45d68d32014-05-23 21:13:31 -0700210 ALOG_ASSERT(mMixerBuffer != NULL);
Glenn Kasten22340022014-04-07 12:04:41 -0700211 int name;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700212
Glenn Kasten22340022014-04-07 12:04:41 -0700213 // process removed tracks first to avoid running out of track names
214 unsigned removedTracks = previousTrackMask & ~currentTrackMask;
215 while (removedTracks != 0) {
216 int i = __builtin_ctz(removedTracks);
217 removedTracks &= ~(1 << i);
218 const FastTrack* fastTrack = &current->mFastTracks[i];
219 ALOG_ASSERT(fastTrack->mBufferProvider == NULL);
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800220 if (mixer != NULL) {
Glenn Kasten22340022014-04-07 12:04:41 -0700221 name = fastTrackNames[i];
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700222 ALOG_ASSERT(name >= 0);
Glenn Kasten22340022014-04-07 12:04:41 -0700223 mixer->deleteTrackName(name);
224 }
225#if !LOG_NDEBUG
226 fastTrackNames[i] = -1;
227#endif
228 // don't reset track dump state, since other side is ignoring it
229 generations[i] = fastTrack->mGeneration;
230 }
231
232 // now process added tracks
233 unsigned addedTracks = currentTrackMask & ~previousTrackMask;
234 while (addedTracks != 0) {
235 int i = __builtin_ctz(addedTracks);
236 addedTracks &= ~(1 << i);
237 const FastTrack* fastTrack = &current->mFastTracks[i];
238 AudioBufferProvider *bufferProvider = fastTrack->mBufferProvider;
239 ALOG_ASSERT(bufferProvider != NULL && fastTrackNames[i] == -1);
240 if (mixer != NULL) {
Andy Hunge8a1ced2014-05-09 15:02:21 -0700241 name = mixer->getTrackName(fastTrack->mChannelMask,
242 fastTrack->mFormat, AUDIO_SESSION_OUTPUT_MIX);
Glenn Kasten22340022014-04-07 12:04:41 -0700243 ALOG_ASSERT(name >= 0);
244 fastTrackNames[i] = name;
245 mixer->setBufferProvider(name, bufferProvider);
246 mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::MAIN_BUFFER,
Andy Hung45d68d32014-05-23 21:13:31 -0700247 (void *) mMixerBuffer);
Glenn Kasten22340022014-04-07 12:04:41 -0700248 // newly allocated track names default to full scale volume
Andy Hung1258c1a2014-05-23 21:22:17 -0700249 mixer->setParameter(
250 name,
251 AudioMixer::TRACK,
252 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hungef7c7fb2014-05-12 16:51:41 -0700253 mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::FORMAT,
254 (void *)(uintptr_t)fastTrack->mFormat);
Glenn Kasten22340022014-04-07 12:04:41 -0700255 mixer->enable(name);
256 }
257 generations[i] = fastTrack->mGeneration;
258 }
259
260 // finally process (potentially) modified tracks; these use the same slot
261 // but may have a different buffer provider or volume provider
262 unsigned modifiedTracks = currentTrackMask & previousTrackMask;
263 while (modifiedTracks != 0) {
264 int i = __builtin_ctz(modifiedTracks);
265 modifiedTracks &= ~(1 << i);
266 const FastTrack* fastTrack = &current->mFastTracks[i];
267 if (fastTrack->mGeneration != generations[i]) {
268 // this track was actually modified
269 AudioBufferProvider *bufferProvider = fastTrack->mBufferProvider;
270 ALOG_ASSERT(bufferProvider != NULL);
271 if (mixer != NULL) {
272 name = fastTrackNames[i];
273 ALOG_ASSERT(name >= 0);
274 mixer->setBufferProvider(name, bufferProvider);
275 if (fastTrack->mVolumeProvider == NULL) {
276 mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0,
Glenn Kastenc56f3422014-03-21 17:53:17 -0700277 (void *) MAX_GAIN_INT);
Glenn Kasten22340022014-04-07 12:04:41 -0700278 mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1,
Glenn Kastenc56f3422014-03-21 17:53:17 -0700279 (void *) MAX_GAIN_INT);
Glenn Kasten288ed212012-04-25 17:52:27 -0700280 }
Glenn Kasten22340022014-04-07 12:04:41 -0700281 mixer->setParameter(name, AudioMixer::RESAMPLE,
282 AudioMixer::REMOVE, NULL);
Andy Hung1258c1a2014-05-23 21:22:17 -0700283 mixer->setParameter(
284 name,
285 AudioMixer::TRACK,
286 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hungef7c7fb2014-05-12 16:51:41 -0700287 mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::FORMAT,
288 (void *)(uintptr_t)fastTrack->mFormat);
Glenn Kasten22340022014-04-07 12:04:41 -0700289 mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK,
290 (void *)(uintptr_t) fastTrack->mChannelMask);
291 // already enabled
292 }
293 generations[i] = fastTrack->mGeneration;
294 }
295 }
296
297 fastTracksGen = current->mFastTracksGen;
298
299 dumpState->mNumTracks = popcount(currentTrackMask);
300 }
301}
302
303void FastMixer::onWork()
304{
305 const FastMixerState * const current = (const FastMixerState *) this->current;
306 FastMixerDumpState * const dumpState = (FastMixerDumpState *) this->dumpState;
307 const FastMixerState::Command command = this->command;
308 const size_t frameCount = current->mFrameCount;
309
310 if ((command & FastMixerState::MIX) && (mixer != NULL) && isWarm) {
Andy Hungef7c7fb2014-05-12 16:51:41 -0700311 ALOG_ASSERT(mMixerBuffer != NULL);
Glenn Kasten22340022014-04-07 12:04:41 -0700312 // for each track, update volume and check for underrun
313 unsigned currentTrackMask = current->mTrackMask;
314 while (currentTrackMask != 0) {
315 int i = __builtin_ctz(currentTrackMask);
316 currentTrackMask &= ~(1 << i);
317 const FastTrack* fastTrack = &current->mFastTracks[i];
318
319 // Refresh the per-track timestamp
320 if (timestampStatus == NO_ERROR) {
321 uint32_t trackFramesWrittenButNotPresented =
322 nativeFramesWrittenButNotPresented;
323 uint32_t trackFramesWritten = fastTrack->mBufferProvider->framesReleased();
324 // Can't provide an AudioTimestamp before first frame presented,
325 // or during the brief 32-bit wraparound window
326 if (trackFramesWritten >= trackFramesWrittenButNotPresented) {
327 AudioTimestamp perTrackTimestamp;
328 perTrackTimestamp.mPosition =
329 trackFramesWritten - trackFramesWrittenButNotPresented;
330 perTrackTimestamp.mTime = timestamp.mTime;
331 fastTrack->mBufferProvider->onTimestamp(perTrackTimestamp);
332 }
333 }
334
335 int name = fastTrackNames[i];
336 ALOG_ASSERT(name >= 0);
337 if (fastTrack->mVolumeProvider != NULL) {
Glenn Kastenc56f3422014-03-21 17:53:17 -0700338 gain_minifloat_packed_t vlr = fastTrack->mVolumeProvider->getVolumeLR();
Glenn Kasten22340022014-04-07 12:04:41 -0700339 mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0,
Glenn Kastenc56f3422014-03-21 17:53:17 -0700340 (void *) (uintptr_t)
341 (float_from_gain(gain_minifloat_unpack_left(vlr)) * MAX_GAIN_INT));
Glenn Kasten22340022014-04-07 12:04:41 -0700342 mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1,
Glenn Kastenc56f3422014-03-21 17:53:17 -0700343 (void *) (uintptr_t)
344 (float_from_gain(gain_minifloat_unpack_right(vlr)) * MAX_GAIN_INT));
Glenn Kasten22340022014-04-07 12:04:41 -0700345 }
346 // FIXME The current implementation of framesReady() for fast tracks
347 // takes a tryLock, which can block
348 // up to 1 ms. If enough active tracks all blocked in sequence, this would result
349 // in the overall fast mix cycle being delayed. Should use a non-blocking FIFO.
350 size_t framesReady = fastTrack->mBufferProvider->framesReady();
351 if (ATRACE_ENABLED()) {
352 // I wish we had formatted trace names
353 char traceName[16];
354 strcpy(traceName, "fRdy");
355 traceName[4] = i + (i < 10 ? '0' : 'A' - 10);
356 traceName[5] = '\0';
357 ATRACE_INT(traceName, framesReady);
358 }
359 FastTrackDump *ftDump = &dumpState->mTracks[i];
360 FastTrackUnderruns underruns = ftDump->mUnderruns;
361 if (framesReady < frameCount) {
362 if (framesReady == 0) {
363 underruns.mBitFields.mEmpty++;
364 underruns.mBitFields.mMostRecent = UNDERRUN_EMPTY;
365 mixer->disable(name);
Glenn Kasten09474df2012-05-10 14:48:07 -0700366 } else {
Glenn Kasten22340022014-04-07 12:04:41 -0700367 // allow mixing partial buffer
368 underruns.mBitFields.mPartial++;
369 underruns.mBitFields.mMostRecent = UNDERRUN_PARTIAL;
Glenn Kasten288ed212012-04-25 17:52:27 -0700370 mixer->enable(name);
371 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700372 } else {
Glenn Kasten22340022014-04-07 12:04:41 -0700373 underruns.mBitFields.mFull++;
374 underruns.mBitFields.mMostRecent = UNDERRUN_FULL;
375 mixer->enable(name);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700376 }
Glenn Kasten22340022014-04-07 12:04:41 -0700377 ftDump->mUnderruns = underruns;
378 ftDump->mFramesReady = framesReady;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700379 }
380
Glenn Kasten22340022014-04-07 12:04:41 -0700381 int64_t pts;
382 if (outputSink == NULL || (OK != outputSink->getNextWriteTimestamp(&pts))) {
383 pts = AudioBufferProvider::kInvalidPTS;
384 }
385
386 // process() is CPU-bound
387 mixer->process(pts);
Andy Hung45d68d32014-05-23 21:13:31 -0700388 mMixerBufferState = MIXED;
389 } else if (mMixerBufferState == MIXED) {
390 mMixerBufferState = UNDEFINED;
Glenn Kasten22340022014-04-07 12:04:41 -0700391 }
392 //bool didFullWrite = false; // dumpsys could display a count of partial writes
Andy Hung45d68d32014-05-23 21:13:31 -0700393 if ((command & FastMixerState::WRITE) && (outputSink != NULL) && (mMixerBuffer != NULL)) {
394 if (mMixerBufferState == UNDEFINED) {
Andy Hung1258c1a2014-05-23 21:22:17 -0700395 memset(mMixerBuffer, 0, mMixerBufferSize);
Andy Hung45d68d32014-05-23 21:13:31 -0700396 mMixerBufferState = ZEROED;
Glenn Kasten22340022014-04-07 12:04:41 -0700397 }
Andy Hung1258c1a2014-05-23 21:22:17 -0700398 void *buffer = mSinkBuffer != NULL ? mSinkBuffer : mMixerBuffer;
399 if (format.mFormat != mMixerBufferFormat) { // sink format not the same as mixer format
400 memcpy_by_audio_format(buffer, format.mFormat, mMixerBuffer, mMixerBufferFormat,
401 frameCount * Format_channelCount(format));
402 }
Glenn Kasten22340022014-04-07 12:04:41 -0700403 // if non-NULL, then duplicate write() to this non-blocking sink
404 NBAIO_Sink* teeSink;
405 if ((teeSink = current->mTeeSink) != NULL) {
Andy Hung45d68d32014-05-23 21:13:31 -0700406 (void) teeSink->write(mMixerBuffer, frameCount);
Glenn Kasten22340022014-04-07 12:04:41 -0700407 }
408 // FIXME write() is non-blocking and lock-free for a properly implemented NBAIO sink,
409 // but this code should be modified to handle both non-blocking and blocking sinks
410 dumpState->mWriteSequence++;
411 ATRACE_BEGIN("write");
Andy Hung1258c1a2014-05-23 21:22:17 -0700412 ssize_t framesWritten = outputSink->write(buffer, frameCount);
Glenn Kasten22340022014-04-07 12:04:41 -0700413 ATRACE_END();
414 dumpState->mWriteSequence++;
415 if (framesWritten >= 0) {
416 ALOG_ASSERT((size_t) framesWritten <= frameCount);
417 totalNativeFramesWritten += framesWritten;
418 dumpState->mFramesWritten = totalNativeFramesWritten;
419 //if ((size_t) framesWritten == frameCount) {
420 // didFullWrite = true;
421 //}
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700422 } else {
Glenn Kasten22340022014-04-07 12:04:41 -0700423 dumpState->mWriteErrors++;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700424 }
Glenn Kasten22340022014-04-07 12:04:41 -0700425 attemptedWrite = true;
426 // FIXME count # of writes blocked excessively, CPU usage, etc. for dump
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700427
Glenn Kasten22340022014-04-07 12:04:41 -0700428 timestampStatus = outputSink->getTimestamp(timestamp);
429 if (timestampStatus == NO_ERROR) {
430 uint32_t totalNativeFramesPresented = timestamp.mPosition;
431 if (totalNativeFramesPresented <= totalNativeFramesWritten) {
432 nativeFramesWrittenButNotPresented =
433 totalNativeFramesWritten - totalNativeFramesPresented;
434 } else {
435 // HAL reported that more frames were presented than were written
436 timestampStatus = INVALID_OPERATION;
437 }
438 }
439 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700440}
441
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700442FastMixerDumpState::FastMixerDumpState(
443#ifdef FAST_MIXER_STATISTICS
444 uint32_t samplingN
445#endif
Glenn Kasten22340022014-04-07 12:04:41 -0700446 ) : FastThreadDumpState(),
447 mWriteSequence(0), mFramesWritten(0),
448 mNumTracks(0), mWriteErrors(0),
449 mSampleRate(0), mFrameCount(0),
Glenn Kasten1295bb4d2012-05-31 07:43:43 -0700450 mTrackMask(0)
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700451{
Glenn Kasten153b9fe2013-07-15 11:23:36 -0700452#ifdef FAST_MIXER_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700453 increaseSamplingN(samplingN);
Glenn Kasten153b9fe2013-07-15 11:23:36 -0700454#endif
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700455}
456
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700457#ifdef FAST_MIXER_STATISTICS
458void FastMixerDumpState::increaseSamplingN(uint32_t samplingN)
459{
460 if (samplingN <= mSamplingN || samplingN > kSamplingN || roundup(samplingN) != samplingN) {
461 return;
462 }
463 uint32_t additional = samplingN - mSamplingN;
464 // sample arrays aren't accessed atomically with respect to the bounds,
465 // so clearing reduces chance for dumpsys to read random uninitialized samples
466 memset(&mMonotonicNs[mSamplingN], 0, sizeof(mMonotonicNs[0]) * additional);
467 memset(&mLoadNs[mSamplingN], 0, sizeof(mLoadNs[0]) * additional);
468#ifdef CPU_FREQUENCY_STATISTICS
469 memset(&mCpukHz[mSamplingN], 0, sizeof(mCpukHz[0]) * additional);
470#endif
471 mSamplingN = samplingN;
472}
473#endif
474
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700475FastMixerDumpState::~FastMixerDumpState()
476{
477}
478
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700479// helper function called by qsort()
480static int compare_uint32_t(const void *pa, const void *pb)
481{
482 uint32_t a = *(const uint32_t *)pa;
483 uint32_t b = *(const uint32_t *)pb;
484 if (a < b) {
485 return -1;
486 } else if (a > b) {
487 return 1;
488 } else {
489 return 0;
490 }
491}
492
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700493void FastMixerDumpState::dump(int fd) const
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700494{
Glenn Kasten868c0ab2012-06-13 14:59:17 -0700495 if (mCommand == FastMixerState::INITIAL) {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700496 dprintf(fd, " FastMixer not initialized\n");
Glenn Kasten868c0ab2012-06-13 14:59:17 -0700497 return;
498 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700499#define COMMAND_MAX 32
500 char string[COMMAND_MAX];
501 switch (mCommand) {
502 case FastMixerState::INITIAL:
503 strcpy(string, "INITIAL");
504 break;
505 case FastMixerState::HOT_IDLE:
506 strcpy(string, "HOT_IDLE");
507 break;
508 case FastMixerState::COLD_IDLE:
509 strcpy(string, "COLD_IDLE");
510 break;
511 case FastMixerState::EXIT:
512 strcpy(string, "EXIT");
513 break;
514 case FastMixerState::MIX:
515 strcpy(string, "MIX");
516 break;
517 case FastMixerState::WRITE:
518 strcpy(string, "WRITE");
519 break;
520 case FastMixerState::MIX_WRITE:
521 strcpy(string, "MIX_WRITE");
522 break;
523 default:
524 snprintf(string, COMMAND_MAX, "%d", mCommand);
525 break;
526 }
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700527 double measuredWarmupMs = (mMeasuredWarmupTs.tv_sec * 1000.0) +
Glenn Kasten288ed212012-04-25 17:52:27 -0700528 (mMeasuredWarmupTs.tv_nsec / 1000000.0);
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700529 double mixPeriodSec = (double) mFrameCount / (double) mSampleRate;
Elliott Hughes87cebad2014-05-22 10:14:43 -0700530 dprintf(fd, " FastMixer command=%s writeSequence=%u framesWritten=%u\n"
531 " numTracks=%u writeErrors=%u underruns=%u overruns=%u\n"
532 " sampleRate=%u frameCount=%zu measuredWarmup=%.3g ms, warmupCycles=%u\n"
533 " mixPeriod=%.2f ms\n",
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700534 string, mWriteSequence, mFramesWritten,
Glenn Kasten21e8c502012-04-12 09:39:42 -0700535 mNumTracks, mWriteErrors, mUnderruns, mOverruns,
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700536 mSampleRate, mFrameCount, measuredWarmupMs, mWarmupCycles,
537 mixPeriodSec * 1e3);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700538#ifdef FAST_MIXER_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700539 // find the interval of valid samples
540 uint32_t bounds = mBounds;
541 uint32_t newestOpen = bounds & 0xFFFF;
542 uint32_t oldestClosed = bounds >> 16;
543 uint32_t n = (newestOpen - oldestClosed) & 0xFFFF;
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700544 if (n > mSamplingN) {
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700545 ALOGE("too many samples %u", n);
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700546 n = mSamplingN;
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700547 }
548 // statistics for monotonic (wall clock) time, thread raw CPU load in time, CPU clock frequency,
549 // and adjusted CPU load in MHz normalized for CPU clock frequency
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700550 CentralTendencyStatistics wall, loadNs;
551#ifdef CPU_FREQUENCY_STATISTICS
552 CentralTendencyStatistics kHz, loadMHz;
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700553 uint32_t previousCpukHz = 0;
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700554#endif
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700555 // Assuming a normal distribution for cycle times, three standard deviations on either side of
556 // the mean account for 99.73% of the population. So if we take each tail to be 1/1000 of the
557 // sample set, we get 99.8% combined, or close to three standard deviations.
558 static const uint32_t kTailDenominator = 1000;
559 uint32_t *tail = n >= kTailDenominator ? new uint32_t[n] : NULL;
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700560 // loop over all the samples
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700561 for (uint32_t j = 0; j < n; ++j) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700562 size_t i = oldestClosed++ & (mSamplingN - 1);
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700563 uint32_t wallNs = mMonotonicNs[i];
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700564 if (tail != NULL) {
565 tail[j] = wallNs;
566 }
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700567 wall.sample(wallNs);
568 uint32_t sampleLoadNs = mLoadNs[i];
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700569 loadNs.sample(sampleLoadNs);
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700570#ifdef CPU_FREQUENCY_STATISTICS
571 uint32_t sampleCpukHz = mCpukHz[i];
Glenn Kastenc059bd42012-05-14 17:41:09 -0700572 // skip bad kHz samples
573 if ((sampleCpukHz & ~0xF) != 0) {
574 kHz.sample(sampleCpukHz >> 4);
575 if (sampleCpukHz == previousCpukHz) {
576 double megacycles = (double) sampleLoadNs * (double) (sampleCpukHz >> 4) * 1e-12;
577 double adjMHz = megacycles / mixPeriodSec; // _not_ wallNs * 1e9
578 loadMHz.sample(adjMHz);
579 }
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700580 }
581 previousCpukHz = sampleCpukHz;
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700582#endif
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700583 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800584 if (n) {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700585 dprintf(fd, " Simple moving statistics over last %.1f seconds:\n",
586 wall.n() * mixPeriodSec);
587 dprintf(fd, " wall clock time in ms per mix cycle:\n"
588 " mean=%.2f min=%.2f max=%.2f stddev=%.2f\n",
589 wall.mean()*1e-6, wall.minimum()*1e-6, wall.maximum()*1e-6,
590 wall.stddev()*1e-6);
591 dprintf(fd, " raw CPU load in us per mix cycle:\n"
592 " mean=%.0f min=%.0f max=%.0f stddev=%.0f\n",
593 loadNs.mean()*1e-3, loadNs.minimum()*1e-3, loadNs.maximum()*1e-3,
594 loadNs.stddev()*1e-3);
Marco Nelissenb2208842014-02-07 14:00:50 -0800595 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700596 dprintf(fd, " No FastMixer statistics available currently\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800597 }
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700598#ifdef CPU_FREQUENCY_STATISTICS
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700599 dprintf(fd, " CPU clock frequency in MHz:\n"
600 " mean=%.0f min=%.0f max=%.0f stddev=%.0f\n",
601 kHz.mean()*1e-3, kHz.minimum()*1e-3, kHz.maximum()*1e-3, kHz.stddev()*1e-3);
602 dprintf(fd, " adjusted CPU load in MHz (i.e. normalized for CPU clock frequency):\n"
603 " mean=%.1f min=%.1f max=%.1f stddev=%.1f\n",
604 loadMHz.mean(), loadMHz.minimum(), loadMHz.maximum(), loadMHz.stddev());
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700605#endif
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700606 if (tail != NULL) {
607 qsort(tail, n, sizeof(uint32_t), compare_uint32_t);
608 // assume same number of tail samples on each side, left and right
609 uint32_t count = n / kTailDenominator;
610 CentralTendencyStatistics left, right;
611 for (uint32_t i = 0; i < count; ++i) {
612 left.sample(tail[i]);
613 right.sample(tail[n - (i + 1)]);
614 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700615 dprintf(fd, " Distribution of mix cycle times in ms for the tails (> ~3 stddev outliers):\n"
616 " left tail: mean=%.2f min=%.2f max=%.2f stddev=%.2f\n"
617 " right tail: mean=%.2f min=%.2f max=%.2f stddev=%.2f\n",
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700618 left.mean()*1e-6, left.minimum()*1e-6, left.maximum()*1e-6, left.stddev()*1e-6,
619 right.mean()*1e-6, right.minimum()*1e-6, right.maximum()*1e-6,
620 right.stddev()*1e-6);
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700621 delete[] tail;
622 }
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700623#endif
Glenn Kasten1295bb4d2012-05-31 07:43:43 -0700624 // The active track mask and track states are updated non-atomically.
625 // So if we relied on isActive to decide whether to display,
626 // then we might display an obsolete track or omit an active track.
627 // Instead we always display all tracks, with an indication
628 // of whether we think the track is active.
629 uint32_t trackMask = mTrackMask;
Elliott Hughes87cebad2014-05-22 10:14:43 -0700630 dprintf(fd, " Fast tracks: kMaxFastTracks=%u activeMask=%#x\n",
Glenn Kasten1295bb4d2012-05-31 07:43:43 -0700631 FastMixerState::kMaxFastTracks, trackMask);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700632 dprintf(fd, " Index Active Full Partial Empty Recent Ready\n");
Glenn Kasten1295bb4d2012-05-31 07:43:43 -0700633 for (uint32_t i = 0; i < FastMixerState::kMaxFastTracks; ++i, trackMask >>= 1) {
634 bool isActive = trackMask & 1;
635 const FastTrackDump *ftDump = &mTracks[i];
636 const FastTrackUnderruns& underruns = ftDump->mUnderruns;
637 const char *mostRecent;
638 switch (underruns.mBitFields.mMostRecent) {
639 case UNDERRUN_FULL:
640 mostRecent = "full";
641 break;
642 case UNDERRUN_PARTIAL:
643 mostRecent = "partial";
644 break;
645 case UNDERRUN_EMPTY:
646 mostRecent = "empty";
647 break;
648 default:
649 mostRecent = "?";
650 break;
651 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700652 dprintf(fd, " %5u %6s %4u %7u %5u %7s %5zu\n", i, isActive ? "yes" : "no",
Glenn Kasten1295bb4d2012-05-31 07:43:43 -0700653 (underruns.mBitFields.mFull) & UNDERRUN_MASK,
654 (underruns.mBitFields.mPartial) & UNDERRUN_MASK,
655 (underruns.mBitFields.mEmpty) & UNDERRUN_MASK,
656 mostRecent, ftDump->mFramesReady);
657 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700658}
659
660} // namespace android