blob: 28b9d7795e594cebd5febad537e7f8aa44a2c476 [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 <sys/atomics.h>
30#include <time.h>
31#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>
34#ifdef FAST_MIXER_STATISTICS
35#include <cpustats/CentralTendencyStatistics.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
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070040#include "AudioMixer.h"
41#include "FastMixer.h"
42
43#define FAST_HOT_IDLE_NS 1000000L // 1 ms: time to sleep while hot idling
44#define FAST_DEFAULT_NS 999999999L // ~1 sec: default time to sleep
Glenn Kasteneb157162012-06-13 14:59:07 -070045#define MIN_WARMUP_CYCLES 2 // minimum number of loop cycles to wait for warmup
Glenn Kasten288ed212012-04-25 17:52:27 -070046#define MAX_WARMUP_CYCLES 10 // maximum number of loop cycles to wait for warmup
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070047
Glenn Kasten7fc97ba2013-07-16 17:18:58 -070048#define FCC_2 2 // fixed channel count assumption
49
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070050namespace android {
51
52// Fast mixer thread
53bool FastMixer::threadLoop()
54{
55 static const FastMixerState initial;
56 const FastMixerState *previous = &initial, *current = &initial;
57 FastMixerState preIdle; // copy of state before we went into idle
58 struct timespec oldTs = {0, 0};
59 bool oldTsValid = false;
60 long slopNs = 0; // accumulated time we've woken up too early (> 0) or too late (< 0)
61 long sleepNs = -1; // -1: busy wait, 0: sched_yield, > 0: nanosleep
62 int fastTrackNames[FastMixerState::kMaxFastTracks]; // handles used by mixer to identify tracks
63 int generations[FastMixerState::kMaxFastTracks]; // last observed mFastTracks[i].mGeneration
64 unsigned i;
65 for (i = 0; i < FastMixerState::kMaxFastTracks; ++i) {
66 fastTrackNames[i] = -1;
67 generations[i] = 0;
68 }
69 NBAIO_Sink *outputSink = NULL;
70 int outputSinkGen = 0;
71 AudioMixer* mixer = NULL;
72 short *mixBuffer = NULL;
73 enum {UNDEFINED, MIXED, ZEROED} mixBufferState = UNDEFINED;
74 NBAIO_Format format = Format_Invalid;
75 unsigned sampleRate = 0;
76 int fastTracksGen = 0;
77 long periodNs = 0; // expected period; the time required to render one mix buffer
Glenn Kasten288ed212012-04-25 17:52:27 -070078 long underrunNs = 0; // underrun likely when write cycle is greater than this value
79 long overrunNs = 0; // overrun likely when write cycle is less than this value
Glenn Kasten972af222012-06-13 17:14:03 -070080 long forceNs = 0; // if overrun detected, force the write cycle to take this much time
Glenn Kasten288ed212012-04-25 17:52:27 -070081 long warmupNs = 0; // warmup complete when write cycle is greater than to this value
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070082 FastMixerDumpState dummyDumpState, *dumpState = &dummyDumpState;
83 bool ignoreNextOverrun = true; // used to ignore initial overrun and first after an underrun
84#ifdef FAST_MIXER_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -070085 struct timespec oldLoad = {0, 0}; // previous value of clock_gettime(CLOCK_THREAD_CPUTIME_ID)
86 bool oldLoadValid = false; // whether oldLoad is valid
87 uint32_t bounds = 0;
Glenn Kasten4182c4e2013-07-15 14:45:07 -070088 bool full = false; // whether we have collected at least mSamplingN samples
Glenn Kasten0a14c4c2012-06-13 14:58:49 -070089#ifdef CPU_FREQUENCY_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -070090 ThreadCpuUsage tcu; // for reading the current CPU clock frequency in kHz
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070091#endif
Glenn Kasten0a14c4c2012-06-13 14:58:49 -070092#endif
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070093 unsigned coldGen = 0; // last observed mColdGen
Glenn Kasten288ed212012-04-25 17:52:27 -070094 bool isWarm = false; // true means ready to mix, false means wait for warmup before mixing
95 struct timespec measuredWarmupTs = {0, 0}; // how long did it take for warmup to complete
96 uint32_t warmupCycles = 0; // counter of number of loop cycles required to warmup
Glenn Kastenfbae5da2012-05-21 09:17:20 -070097 NBAIO_Sink* teeSink = NULL; // if non-NULL, then duplicate write() to this non-blocking sink
Glenn Kasten9e58b552013-01-18 15:09:48 -080098 NBLog::Writer dummyLogWriter, *logWriter = &dummyLogWriter;
Glenn Kasten732845c2013-08-23 09:26:31 -070099 uint32_t totalNativeFramesWritten = 0; // copied to dumpState->mFramesWritten
100
101 // next 2 fields are valid only when timestampStatus == NO_ERROR
102 AudioTimestamp timestamp;
103 uint32_t nativeFramesWrittenButNotPresented = 0; // the = 0 is to silence the compiler
104 status_t timestampStatus = INVALID_OPERATION;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700105
106 for (;;) {
107
108 // either nanosleep, sched_yield, or busy wait
109 if (sleepNs >= 0) {
110 if (sleepNs > 0) {
111 ALOG_ASSERT(sleepNs < 1000000000);
112 const struct timespec req = {0, sleepNs};
113 nanosleep(&req, NULL);
114 } else {
115 sched_yield();
116 }
117 }
118 // default to long sleep for next cycle
119 sleepNs = FAST_DEFAULT_NS;
120
121 // poll for state change
122 const FastMixerState *next = mSQ.poll();
123 if (next == NULL) {
124 // continue to use the default initial state until a real state is available
125 ALOG_ASSERT(current == &initial && previous == &initial);
126 next = current;
127 }
128
129 FastMixerState::Command command = next->mCommand;
130 if (next != current) {
131
132 // As soon as possible of learning of a new dump area, start using it
133 dumpState = next->mDumpState != NULL ? next->mDumpState : &dummyDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -0700134 teeSink = next->mTeeSink;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800135 logWriter = next->mNBLogWriter != NULL ? next->mNBLogWriter : &dummyLogWriter;
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800136 if (mixer != NULL) {
137 mixer->setLog(logWriter);
138 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700139
140 // We want to always have a valid reference to the previous (non-idle) state.
141 // However, the state queue only guarantees access to current and previous states.
142 // So when there is a transition from a non-idle state into an idle state, we make a
143 // copy of the last known non-idle state so it is still available on return from idle.
144 // The possible transitions are:
145 // non-idle -> non-idle update previous from current in-place
146 // non-idle -> idle update previous from copy of current
147 // idle -> idle don't update previous
148 // idle -> non-idle don't update previous
149 if (!(current->mCommand & FastMixerState::IDLE)) {
150 if (command & FastMixerState::IDLE) {
151 preIdle = *current;
152 current = &preIdle;
153 oldTsValid = false;
Glenn Kasten153b9fe2013-07-15 11:23:36 -0700154#ifdef FAST_MIXER_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700155 oldLoadValid = false;
Glenn Kasten153b9fe2013-07-15 11:23:36 -0700156#endif
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700157 ignoreNextOverrun = true;
158 }
159 previous = current;
160 }
161 current = next;
162 }
163#if !LOG_NDEBUG
164 next = NULL; // not referenced again
165#endif
166
167 dumpState->mCommand = command;
168
169 switch (command) {
170 case FastMixerState::INITIAL:
171 case FastMixerState::HOT_IDLE:
172 sleepNs = FAST_HOT_IDLE_NS;
173 continue;
174 case FastMixerState::COLD_IDLE:
175 // only perform a cold idle command once
Glenn Kasten21e8c502012-04-12 09:39:42 -0700176 // FIXME consider checking previous state and only perform if previous != COLD_IDLE
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700177 if (current->mColdGen != coldGen) {
178 int32_t *coldFutexAddr = current->mColdFutexAddr;
179 ALOG_ASSERT(coldFutexAddr != NULL);
180 int32_t old = android_atomic_dec(coldFutexAddr);
181 if (old <= 0) {
182 __futex_syscall4(coldFutexAddr, FUTEX_WAIT_PRIVATE, old - 1, NULL);
183 }
Glenn Kastena07f17c2013-04-23 12:39:37 -0700184 int policy = sched_getscheduler(0);
185 if (!(policy == SCHED_FIFO || policy == SCHED_RR)) {
186 ALOGE("did not receive expected priority boost");
187 }
Glenn Kasten288ed212012-04-25 17:52:27 -0700188 // This may be overly conservative; there could be times that the normal mixer
189 // requests such a brief cold idle that it doesn't require resetting this flag.
190 isWarm = false;
191 measuredWarmupTs.tv_sec = 0;
192 measuredWarmupTs.tv_nsec = 0;
193 warmupCycles = 0;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700194 sleepNs = -1;
195 coldGen = current->mColdGen;
Glenn Kasten153b9fe2013-07-15 11:23:36 -0700196#ifdef FAST_MIXER_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700197 bounds = 0;
198 full = false;
Glenn Kasten153b9fe2013-07-15 11:23:36 -0700199#endif
Glenn Kasten04a4ca42012-06-01 10:49:51 -0700200 oldTsValid = !clock_gettime(CLOCK_MONOTONIC, &oldTs);
Glenn Kasten732845c2013-08-23 09:26:31 -0700201 timestampStatus = INVALID_OPERATION;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700202 } else {
203 sleepNs = FAST_HOT_IDLE_NS;
204 }
205 continue;
206 case FastMixerState::EXIT:
207 delete mixer;
208 delete[] mixBuffer;
209 return false;
210 case FastMixerState::MIX:
211 case FastMixerState::WRITE:
212 case FastMixerState::MIX_WRITE:
213 break;
214 default:
215 LOG_FATAL("bad command %d", command);
216 }
217
218 // there is a non-idle state available to us; did the state change?
219 size_t frameCount = current->mFrameCount;
220 if (current != previous) {
221
222 // handle state change here, but since we want to diff the state,
223 // we're prepared for previous == &initial the first time through
224 unsigned previousTrackMask;
225
226 // check for change in output HAL configuration
227 NBAIO_Format previousFormat = format;
228 if (current->mOutputSinkGen != outputSinkGen) {
229 outputSink = current->mOutputSink;
230 outputSinkGen = current->mOutputSinkGen;
231 if (outputSink == NULL) {
232 format = Format_Invalid;
233 sampleRate = 0;
234 } else {
235 format = outputSink->format();
236 sampleRate = Format_sampleRate(format);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -0700237 ALOG_ASSERT(Format_channelCount(format) == FCC_2);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700238 }
Glenn Kasten21e8c502012-04-12 09:39:42 -0700239 dumpState->mSampleRate = sampleRate;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700240 }
241
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800242 if ((!Format_isEqual(format, previousFormat)) || (frameCount != previous->mFrameCount)) {
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700243 // FIXME to avoid priority inversion, don't delete here
244 delete mixer;
245 mixer = NULL;
246 delete[] mixBuffer;
247 mixBuffer = NULL;
248 if (frameCount > 0 && sampleRate > 0) {
249 // FIXME new may block for unbounded time at internal mutex of the heap
250 // implementation; it would be better to have normal mixer allocate for us
251 // to avoid blocking here and to prevent possible priority inversion
252 mixer = new AudioMixer(frameCount, sampleRate, FastMixerState::kMaxFastTracks);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -0700253 mixBuffer = new short[frameCount * FCC_2];
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700254 periodNs = (frameCount * 1000000000LL) / sampleRate; // 1.00
255 underrunNs = (frameCount * 1750000000LL) / sampleRate; // 1.75
Glenn Kasten0d27c652012-08-07 10:38:59 -0700256 overrunNs = (frameCount * 500000000LL) / sampleRate; // 0.50
257 forceNs = (frameCount * 950000000LL) / sampleRate; // 0.95
Glenn Kasten288ed212012-04-25 17:52:27 -0700258 warmupNs = (frameCount * 500000000LL) / sampleRate; // 0.50
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700259 } else {
260 periodNs = 0;
261 underrunNs = 0;
262 overrunNs = 0;
Glenn Kasten972af222012-06-13 17:14:03 -0700263 forceNs = 0;
264 warmupNs = 0;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700265 }
266 mixBufferState = UNDEFINED;
267#if !LOG_NDEBUG
268 for (i = 0; i < FastMixerState::kMaxFastTracks; ++i) {
269 fastTrackNames[i] = -1;
270 }
271#endif
272 // we need to reconfigure all active tracks
273 previousTrackMask = 0;
274 fastTracksGen = current->mFastTracksGen - 1;
Glenn Kasten21e8c502012-04-12 09:39:42 -0700275 dumpState->mFrameCount = frameCount;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700276 } else {
277 previousTrackMask = previous->mTrackMask;
278 }
279
280 // check for change in active track set
281 unsigned currentTrackMask = current->mTrackMask;
Glenn Kasten1295bb4d2012-05-31 07:43:43 -0700282 dumpState->mTrackMask = currentTrackMask;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700283 if (current->mFastTracksGen != fastTracksGen) {
284 ALOG_ASSERT(mixBuffer != NULL);
285 int name;
286
287 // process removed tracks first to avoid running out of track names
288 unsigned removedTracks = previousTrackMask & ~currentTrackMask;
289 while (removedTracks != 0) {
290 i = __builtin_ctz(removedTracks);
291 removedTracks &= ~(1 << i);
292 const FastTrack* fastTrack = &current->mFastTracks[i];
Glenn Kasten288ed212012-04-25 17:52:27 -0700293 ALOG_ASSERT(fastTrack->mBufferProvider == NULL);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700294 if (mixer != NULL) {
295 name = fastTrackNames[i];
296 ALOG_ASSERT(name >= 0);
297 mixer->deleteTrackName(name);
298 }
299#if !LOG_NDEBUG
300 fastTrackNames[i] = -1;
301#endif
Glenn Kasten288ed212012-04-25 17:52:27 -0700302 // don't reset track dump state, since other side is ignoring it
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700303 generations[i] = fastTrack->mGeneration;
304 }
305
306 // now process added tracks
307 unsigned addedTracks = currentTrackMask & ~previousTrackMask;
308 while (addedTracks != 0) {
309 i = __builtin_ctz(addedTracks);
310 addedTracks &= ~(1 << i);
311 const FastTrack* fastTrack = &current->mFastTracks[i];
312 AudioBufferProvider *bufferProvider = fastTrack->mBufferProvider;
313 ALOG_ASSERT(bufferProvider != NULL && fastTrackNames[i] == -1);
314 if (mixer != NULL) {
Jean-Michel Trivife3156e2012-09-10 18:58:27 -0700315 // calling getTrackName with default channel mask and a random invalid
316 // sessionId (no effects here)
317 name = mixer->getTrackName(AUDIO_CHANNEL_OUT_STEREO, -555);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700318 ALOG_ASSERT(name >= 0);
319 fastTrackNames[i] = name;
320 mixer->setBufferProvider(name, bufferProvider);
321 mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::MAIN_BUFFER,
322 (void *) mixBuffer);
323 // newly allocated track names default to full scale volume
Glenn Kasten21e8c502012-04-12 09:39:42 -0700324 if (fastTrack->mSampleRate != 0 && fastTrack->mSampleRate != sampleRate) {
325 mixer->setParameter(name, AudioMixer::RESAMPLE,
326 AudioMixer::SAMPLE_RATE, (void*) fastTrack->mSampleRate);
327 }
328 mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK,
329 (void *) fastTrack->mChannelMask);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700330 mixer->enable(name);
331 }
332 generations[i] = fastTrack->mGeneration;
333 }
334
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800335 // finally process (potentially) modified tracks; these use the same slot
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700336 // but may have a different buffer provider or volume provider
337 unsigned modifiedTracks = currentTrackMask & previousTrackMask;
338 while (modifiedTracks != 0) {
339 i = __builtin_ctz(modifiedTracks);
340 modifiedTracks &= ~(1 << i);
341 const FastTrack* fastTrack = &current->mFastTracks[i];
342 if (fastTrack->mGeneration != generations[i]) {
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800343 // this track was actually modified
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700344 AudioBufferProvider *bufferProvider = fastTrack->mBufferProvider;
345 ALOG_ASSERT(bufferProvider != NULL);
346 if (mixer != NULL) {
347 name = fastTrackNames[i];
348 ALOG_ASSERT(name >= 0);
349 mixer->setBufferProvider(name, bufferProvider);
350 if (fastTrack->mVolumeProvider == NULL) {
351 mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0,
352 (void *)0x1000);
353 mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1,
354 (void *)0x1000);
355 }
Glenn Kasten21e8c502012-04-12 09:39:42 -0700356 if (fastTrack->mSampleRate != 0 &&
357 fastTrack->mSampleRate != sampleRate) {
358 mixer->setParameter(name, AudioMixer::RESAMPLE,
359 AudioMixer::SAMPLE_RATE, (void*) fastTrack->mSampleRate);
360 } else {
361 mixer->setParameter(name, AudioMixer::RESAMPLE,
362 AudioMixer::REMOVE, NULL);
363 }
364 mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK,
365 (void *) fastTrack->mChannelMask);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700366 // already enabled
367 }
368 generations[i] = fastTrack->mGeneration;
369 }
370 }
371
372 fastTracksGen = current->mFastTracksGen;
373
374 dumpState->mNumTracks = popcount(currentTrackMask);
375 }
376
377#if 1 // FIXME shouldn't need this
378 // only process state change once
379 previous = current;
380#endif
381 }
382
383 // do work using current state here
Glenn Kasten288ed212012-04-25 17:52:27 -0700384 if ((command & FastMixerState::MIX) && (mixer != NULL) && isWarm) {
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700385 ALOG_ASSERT(mixBuffer != NULL);
Glenn Kasten288ed212012-04-25 17:52:27 -0700386 // for each track, update volume and check for underrun
387 unsigned currentTrackMask = current->mTrackMask;
388 while (currentTrackMask != 0) {
389 i = __builtin_ctz(currentTrackMask);
390 currentTrackMask &= ~(1 << i);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700391 const FastTrack* fastTrack = &current->mFastTracks[i];
Glenn Kasten732845c2013-08-23 09:26:31 -0700392
393 // Refresh the per-track timestamp
394 if (timestampStatus == NO_ERROR) {
395 uint32_t trackFramesWrittenButNotPresented;
396 uint32_t trackSampleRate = fastTrack->mSampleRate;
397 // There is currently no sample rate conversion for fast tracks currently
398 if (trackSampleRate != 0 && trackSampleRate != sampleRate) {
399 trackFramesWrittenButNotPresented =
400 ((int64_t) nativeFramesWrittenButNotPresented * trackSampleRate) /
401 sampleRate;
402 } else {
403 trackFramesWrittenButNotPresented = nativeFramesWrittenButNotPresented;
404 }
405 uint32_t trackFramesWritten = fastTrack->mBufferProvider->framesReleased();
406 // Can't provide an AudioTimestamp before first frame presented,
407 // or during the brief 32-bit wraparound window
408 if (trackFramesWritten >= trackFramesWrittenButNotPresented) {
409 AudioTimestamp perTrackTimestamp;
410 perTrackTimestamp.mPosition =
411 trackFramesWritten - trackFramesWrittenButNotPresented;
412 perTrackTimestamp.mTime = timestamp.mTime;
413 fastTrack->mBufferProvider->onTimestamp(perTrackTimestamp);
414 }
415 }
416
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700417 int name = fastTrackNames[i];
418 ALOG_ASSERT(name >= 0);
419 if (fastTrack->mVolumeProvider != NULL) {
420 uint32_t vlr = fastTrack->mVolumeProvider->getVolumeLR();
421 mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0,
422 (void *)(vlr & 0xFFFF));
423 mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1,
424 (void *)(vlr >> 16));
425 }
Glenn Kasten288ed212012-04-25 17:52:27 -0700426 // FIXME The current implementation of framesReady() for fast tracks
427 // takes a tryLock, which can block
428 // up to 1 ms. If enough active tracks all blocked in sequence, this would result
429 // in the overall fast mix cycle being delayed. Should use a non-blocking FIFO.
430 size_t framesReady = fastTrack->mBufferProvider->framesReady();
Alex Rayb3a83642012-11-30 19:42:28 -0800431 if (ATRACE_ENABLED()) {
432 // I wish we had formatted trace names
433 char traceName[16];
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800434 strcpy(traceName, "fRdy");
435 traceName[4] = i + (i < 10 ? '0' : 'A' - 10);
436 traceName[5] = '\0';
Alex Rayb3a83642012-11-30 19:42:28 -0800437 ATRACE_INT(traceName, framesReady);
438 }
Glenn Kasten288ed212012-04-25 17:52:27 -0700439 FastTrackDump *ftDump = &dumpState->mTracks[i];
Glenn Kasten09474df2012-05-10 14:48:07 -0700440 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten288ed212012-04-25 17:52:27 -0700441 if (framesReady < frameCount) {
Glenn Kasten288ed212012-04-25 17:52:27 -0700442 if (framesReady == 0) {
Glenn Kasten09474df2012-05-10 14:48:07 -0700443 underruns.mBitFields.mEmpty++;
444 underruns.mBitFields.mMostRecent = UNDERRUN_EMPTY;
Glenn Kasten288ed212012-04-25 17:52:27 -0700445 mixer->disable(name);
446 } else {
447 // allow mixing partial buffer
Glenn Kasten09474df2012-05-10 14:48:07 -0700448 underruns.mBitFields.mPartial++;
449 underruns.mBitFields.mMostRecent = UNDERRUN_PARTIAL;
Glenn Kasten288ed212012-04-25 17:52:27 -0700450 mixer->enable(name);
451 }
Glenn Kasten09474df2012-05-10 14:48:07 -0700452 } else {
453 underruns.mBitFields.mFull++;
454 underruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten288ed212012-04-25 17:52:27 -0700455 mixer->enable(name);
456 }
Glenn Kasten09474df2012-05-10 14:48:07 -0700457 ftDump->mUnderruns = underruns;
Glenn Kasten1295bb4d2012-05-31 07:43:43 -0700458 ftDump->mFramesReady = framesReady;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700459 }
John Grossman2c3b2da2012-08-02 17:08:54 -0700460
461 int64_t pts;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700462 if (outputSink == NULL || (OK != outputSink->getNextWriteTimestamp(&pts))) {
John Grossman2c3b2da2012-08-02 17:08:54 -0700463 pts = AudioBufferProvider::kInvalidPTS;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700464 }
John Grossman2c3b2da2012-08-02 17:08:54 -0700465
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700466 // process() is CPU-bound
John Grossman2c3b2da2012-08-02 17:08:54 -0700467 mixer->process(pts);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700468 mixBufferState = MIXED;
469 } else if (mixBufferState == MIXED) {
470 mixBufferState = UNDEFINED;
471 }
Glenn Kasten288ed212012-04-25 17:52:27 -0700472 bool attemptedWrite = false;
473 //bool didFullWrite = false; // dumpsys could display a count of partial writes
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700474 if ((command & FastMixerState::WRITE) && (outputSink != NULL) && (mixBuffer != NULL)) {
475 if (mixBufferState == UNDEFINED) {
Glenn Kasten7fc97ba2013-07-16 17:18:58 -0700476 memset(mixBuffer, 0, frameCount * FCC_2 * sizeof(short));
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700477 mixBufferState = ZEROED;
478 }
Glenn Kastenfbae5da2012-05-21 09:17:20 -0700479 if (teeSink != NULL) {
480 (void) teeSink->write(mixBuffer, frameCount);
481 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700482 // FIXME write() is non-blocking and lock-free for a properly implemented NBAIO sink,
483 // but this code should be modified to handle both non-blocking and blocking sinks
484 dumpState->mWriteSequence++;
Simon Wilson2d590962012-11-29 15:18:50 -0800485 ATRACE_BEGIN("write");
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700486 ssize_t framesWritten = outputSink->write(mixBuffer, frameCount);
Simon Wilson2d590962012-11-29 15:18:50 -0800487 ATRACE_END();
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700488 dumpState->mWriteSequence++;
489 if (framesWritten >= 0) {
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800490 ALOG_ASSERT((size_t) framesWritten <= frameCount);
Glenn Kasten732845c2013-08-23 09:26:31 -0700491 totalNativeFramesWritten += framesWritten;
492 dumpState->mFramesWritten = totalNativeFramesWritten;
Glenn Kasten288ed212012-04-25 17:52:27 -0700493 //if ((size_t) framesWritten == frameCount) {
494 // didFullWrite = true;
495 //}
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700496 } else {
497 dumpState->mWriteErrors++;
498 }
Glenn Kasten288ed212012-04-25 17:52:27 -0700499 attemptedWrite = true;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700500 // FIXME count # of writes blocked excessively, CPU usage, etc. for dump
Glenn Kasten732845c2013-08-23 09:26:31 -0700501
502 timestampStatus = outputSink->getTimestamp(timestamp);
503 if (timestampStatus == NO_ERROR) {
504 uint32_t totalNativeFramesPresented = timestamp.mPosition;
505 if (totalNativeFramesPresented <= totalNativeFramesWritten) {
506 nativeFramesWrittenButNotPresented =
507 totalNativeFramesWritten - totalNativeFramesPresented;
508 } else {
509 // HAL reported that more frames were presented than were written
510 timestampStatus = INVALID_OPERATION;
511 }
512 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700513 }
514
515 // To be exactly periodic, compute the next sleep time based on current time.
516 // This code doesn't have long-term stability when the sink is non-blocking.
517 // FIXME To avoid drift, use the local audio clock or watch the sink's fill status.
518 struct timespec newTs;
519 int rc = clock_gettime(CLOCK_MONOTONIC, &newTs);
520 if (rc == 0) {
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800521 //logWriter->logTimestamp(newTs);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700522 if (oldTsValid) {
523 time_t sec = newTs.tv_sec - oldTs.tv_sec;
524 long nsec = newTs.tv_nsec - oldTs.tv_nsec;
Glenn Kasten80b32732012-09-24 11:29:00 -0700525 ALOGE_IF(sec < 0 || (sec == 0 && nsec < 0),
526 "clock_gettime(CLOCK_MONOTONIC) failed: was %ld.%09ld but now %ld.%09ld",
527 oldTs.tv_sec, oldTs.tv_nsec, newTs.tv_sec, newTs.tv_nsec);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700528 if (nsec < 0) {
529 --sec;
530 nsec += 1000000000;
531 }
Glenn Kasten288ed212012-04-25 17:52:27 -0700532 // To avoid an initial underrun on fast tracks after exiting standby,
533 // do not start pulling data from tracks and mixing until warmup is complete.
534 // Warmup is considered complete after the earlier of:
Glenn Kasteneb157162012-06-13 14:59:07 -0700535 // MIN_WARMUP_CYCLES write() attempts and last one blocks for at least warmupNs
Glenn Kasten288ed212012-04-25 17:52:27 -0700536 // MAX_WARMUP_CYCLES write() attempts.
537 // This is overly conservative, but to get better accuracy requires a new HAL API.
538 if (!isWarm && attemptedWrite) {
539 measuredWarmupTs.tv_sec += sec;
540 measuredWarmupTs.tv_nsec += nsec;
541 if (measuredWarmupTs.tv_nsec >= 1000000000) {
542 measuredWarmupTs.tv_sec++;
543 measuredWarmupTs.tv_nsec -= 1000000000;
544 }
545 ++warmupCycles;
Glenn Kasteneb157162012-06-13 14:59:07 -0700546 if ((nsec > warmupNs && warmupCycles >= MIN_WARMUP_CYCLES) ||
Glenn Kasten288ed212012-04-25 17:52:27 -0700547 (warmupCycles >= MAX_WARMUP_CYCLES)) {
548 isWarm = true;
549 dumpState->mMeasuredWarmupTs = measuredWarmupTs;
550 dumpState->mWarmupCycles = warmupCycles;
551 }
552 }
Glenn Kasten972af222012-06-13 17:14:03 -0700553 sleepNs = -1;
Glenn Kasten3d198252013-07-10 17:20:54 -0700554 if (isWarm) {
555 if (sec > 0 || nsec > underrunNs) {
556 ATRACE_NAME("underrun");
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700557 // FIXME only log occasionally
Glenn Kasten3d198252013-07-10 17:20:54 -0700558 ALOGV("underrun: time since last cycle %d.%03ld sec",
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700559 (int) sec, nsec / 1000000L);
Glenn Kasten3d198252013-07-10 17:20:54 -0700560 dumpState->mUnderruns++;
561 ignoreNextOverrun = true;
562 } else if (nsec < overrunNs) {
563 if (ignoreNextOverrun) {
564 ignoreNextOverrun = false;
565 } else {
566 // FIXME only log occasionally
567 ALOGV("overrun: time since last cycle %d.%03ld sec",
568 (int) sec, nsec / 1000000L);
569 dumpState->mOverruns++;
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700570 }
Glenn Kasten3d198252013-07-10 17:20:54 -0700571 // This forces a minimum cycle time. It:
572 // - compensates for an audio HAL with jitter due to sample rate conversion
573 // - works with a variable buffer depth audio HAL that never pulls at a
574 // rate < than overrunNs per buffer.
575 // - recovers from overrun immediately after underrun
576 // It doesn't work with a non-blocking audio HAL.
577 sleepNs = forceNs - nsec;
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700578 } else {
Glenn Kasten3d198252013-07-10 17:20:54 -0700579 ignoreNextOverrun = false;
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700580 }
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700581 }
Glenn Kasten3d198252013-07-10 17:20:54 -0700582#ifdef FAST_MIXER_STATISTICS
583 if (isWarm) {
584 // advance the FIFO queue bounds
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700585 size_t i = bounds & (dumpState->mSamplingN - 1);
Glenn Kasten3d198252013-07-10 17:20:54 -0700586 bounds = (bounds & 0xFFFF0000) | ((bounds + 1) & 0xFFFF);
587 if (full) {
588 bounds += 0x10000;
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700589 } else if (!(bounds & (dumpState->mSamplingN - 1))) {
Glenn Kasten3d198252013-07-10 17:20:54 -0700590 full = true;
591 }
592 // compute the delta value of clock_gettime(CLOCK_MONOTONIC)
593 uint32_t monotonicNs = nsec;
594 if (sec > 0 && sec < 4) {
595 monotonicNs += sec * 1000000000;
596 }
597 // compute raw CPU load = delta value of clock_gettime(CLOCK_THREAD_CPUTIME_ID)
598 uint32_t loadNs = 0;
599 struct timespec newLoad;
600 rc = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &newLoad);
601 if (rc == 0) {
602 if (oldLoadValid) {
603 sec = newLoad.tv_sec - oldLoad.tv_sec;
604 nsec = newLoad.tv_nsec - oldLoad.tv_nsec;
605 if (nsec < 0) {
606 --sec;
607 nsec += 1000000000;
608 }
609 loadNs = nsec;
610 if (sec > 0 && sec < 4) {
611 loadNs += sec * 1000000000;
612 }
613 } else {
614 // first time through the loop
615 oldLoadValid = true;
616 }
617 oldLoad = newLoad;
618 }
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700619#ifdef CPU_FREQUENCY_STATISTICS
Glenn Kasten3d198252013-07-10 17:20:54 -0700620 // get the absolute value of CPU clock frequency in kHz
621 int cpuNum = sched_getcpu();
622 uint32_t kHz = tcu.getCpukHz(cpuNum);
623 kHz = (kHz << 4) | (cpuNum & 0xF);
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700624#endif
Glenn Kasten3d198252013-07-10 17:20:54 -0700625 // save values in FIFO queues for dumpsys
626 // these stores #1, #2, #3 are not atomic with respect to each other,
627 // or with respect to store #4 below
628 dumpState->mMonotonicNs[i] = monotonicNs;
629 dumpState->mLoadNs[i] = loadNs;
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700630#ifdef CPU_FREQUENCY_STATISTICS
Glenn Kasten3d198252013-07-10 17:20:54 -0700631 dumpState->mCpukHz[i] = kHz;
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700632#endif
Glenn Kasten3d198252013-07-10 17:20:54 -0700633 // this store #4 is not atomic with respect to stores #1, #2, #3 above, but
634 // the newest open & oldest closed halves are atomic with respect to each other
635 dumpState->mBounds = bounds;
636 ATRACE_INT("cycle_ms", monotonicNs / 1000000);
637 ATRACE_INT("load_us", loadNs / 1000);
638 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700639#endif
640 } else {
641 // first time through the loop
642 oldTsValid = true;
643 sleepNs = periodNs;
644 ignoreNextOverrun = true;
645 }
646 oldTs = newTs;
647 } else {
648 // monotonic clock is broken
649 oldTsValid = false;
650 sleepNs = periodNs;
651 }
652
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700653
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700654 } // for (;;)
655
656 // never return 'true'; Thread::_threadLoop() locks mutex which can result in priority inversion
657}
658
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700659FastMixerDumpState::FastMixerDumpState(
660#ifdef FAST_MIXER_STATISTICS
661 uint32_t samplingN
662#endif
663 ) :
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700664 mCommand(FastMixerState::INITIAL), mWriteSequence(0), mFramesWritten(0),
Glenn Kasten21e8c502012-04-12 09:39:42 -0700665 mNumTracks(0), mWriteErrors(0), mUnderruns(0), mOverruns(0),
Glenn Kasten1295bb4d2012-05-31 07:43:43 -0700666 mSampleRate(0), mFrameCount(0), /* mMeasuredWarmupTs({0, 0}), */ mWarmupCycles(0),
667 mTrackMask(0)
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700668#ifdef FAST_MIXER_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700669 , mSamplingN(0), mBounds(0)
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700670#endif
671{
Glenn Kasten288ed212012-04-25 17:52:27 -0700672 mMeasuredWarmupTs.tv_sec = 0;
673 mMeasuredWarmupTs.tv_nsec = 0;
Glenn Kasten153b9fe2013-07-15 11:23:36 -0700674#ifdef FAST_MIXER_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700675 increaseSamplingN(samplingN);
Glenn Kasten153b9fe2013-07-15 11:23:36 -0700676#endif
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700677}
678
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700679#ifdef FAST_MIXER_STATISTICS
680void FastMixerDumpState::increaseSamplingN(uint32_t samplingN)
681{
682 if (samplingN <= mSamplingN || samplingN > kSamplingN || roundup(samplingN) != samplingN) {
683 return;
684 }
685 uint32_t additional = samplingN - mSamplingN;
686 // sample arrays aren't accessed atomically with respect to the bounds,
687 // so clearing reduces chance for dumpsys to read random uninitialized samples
688 memset(&mMonotonicNs[mSamplingN], 0, sizeof(mMonotonicNs[0]) * additional);
689 memset(&mLoadNs[mSamplingN], 0, sizeof(mLoadNs[0]) * additional);
690#ifdef CPU_FREQUENCY_STATISTICS
691 memset(&mCpukHz[mSamplingN], 0, sizeof(mCpukHz[0]) * additional);
692#endif
693 mSamplingN = samplingN;
694}
695#endif
696
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700697FastMixerDumpState::~FastMixerDumpState()
698{
699}
700
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700701// helper function called by qsort()
702static int compare_uint32_t(const void *pa, const void *pb)
703{
704 uint32_t a = *(const uint32_t *)pa;
705 uint32_t b = *(const uint32_t *)pb;
706 if (a < b) {
707 return -1;
708 } else if (a > b) {
709 return 1;
710 } else {
711 return 0;
712 }
713}
714
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700715void FastMixerDumpState::dump(int fd) const
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700716{
Glenn Kasten868c0ab2012-06-13 14:59:17 -0700717 if (mCommand == FastMixerState::INITIAL) {
718 fdprintf(fd, "FastMixer not initialized\n");
719 return;
720 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700721#define COMMAND_MAX 32
722 char string[COMMAND_MAX];
723 switch (mCommand) {
724 case FastMixerState::INITIAL:
725 strcpy(string, "INITIAL");
726 break;
727 case FastMixerState::HOT_IDLE:
728 strcpy(string, "HOT_IDLE");
729 break;
730 case FastMixerState::COLD_IDLE:
731 strcpy(string, "COLD_IDLE");
732 break;
733 case FastMixerState::EXIT:
734 strcpy(string, "EXIT");
735 break;
736 case FastMixerState::MIX:
737 strcpy(string, "MIX");
738 break;
739 case FastMixerState::WRITE:
740 strcpy(string, "WRITE");
741 break;
742 case FastMixerState::MIX_WRITE:
743 strcpy(string, "MIX_WRITE");
744 break;
745 default:
746 snprintf(string, COMMAND_MAX, "%d", mCommand);
747 break;
748 }
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700749 double measuredWarmupMs = (mMeasuredWarmupTs.tv_sec * 1000.0) +
Glenn Kasten288ed212012-04-25 17:52:27 -0700750 (mMeasuredWarmupTs.tv_nsec / 1000000.0);
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700751 double mixPeriodSec = (double) mFrameCount / (double) mSampleRate;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700752 fdprintf(fd, "FastMixer command=%s writeSequence=%u framesWritten=%u\n"
Glenn Kasten21e8c502012-04-12 09:39:42 -0700753 " numTracks=%u writeErrors=%u underruns=%u overruns=%u\n"
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700754 " sampleRate=%u frameCount=%u measuredWarmup=%.3g ms, warmupCycles=%u\n"
755 " mixPeriod=%.2f ms\n",
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700756 string, mWriteSequence, mFramesWritten,
Glenn Kasten21e8c502012-04-12 09:39:42 -0700757 mNumTracks, mWriteErrors, mUnderruns, mOverruns,
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700758 mSampleRate, mFrameCount, measuredWarmupMs, mWarmupCycles,
759 mixPeriodSec * 1e3);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700760#ifdef FAST_MIXER_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700761 // find the interval of valid samples
762 uint32_t bounds = mBounds;
763 uint32_t newestOpen = bounds & 0xFFFF;
764 uint32_t oldestClosed = bounds >> 16;
765 uint32_t n = (newestOpen - oldestClosed) & 0xFFFF;
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700766 if (n > mSamplingN) {
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700767 ALOGE("too many samples %u", n);
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700768 n = mSamplingN;
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700769 }
770 // statistics for monotonic (wall clock) time, thread raw CPU load in time, CPU clock frequency,
771 // and adjusted CPU load in MHz normalized for CPU clock frequency
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700772 CentralTendencyStatistics wall, loadNs;
773#ifdef CPU_FREQUENCY_STATISTICS
774 CentralTendencyStatistics kHz, loadMHz;
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700775 uint32_t previousCpukHz = 0;
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700776#endif
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700777 // Assuming a normal distribution for cycle times, three standard deviations on either side of
778 // the mean account for 99.73% of the population. So if we take each tail to be 1/1000 of the
779 // sample set, we get 99.8% combined, or close to three standard deviations.
780 static const uint32_t kTailDenominator = 1000;
781 uint32_t *tail = n >= kTailDenominator ? new uint32_t[n] : NULL;
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700782 // loop over all the samples
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700783 for (uint32_t j = 0; j < n; ++j) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700784 size_t i = oldestClosed++ & (mSamplingN - 1);
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700785 uint32_t wallNs = mMonotonicNs[i];
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700786 if (tail != NULL) {
787 tail[j] = wallNs;
788 }
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700789 wall.sample(wallNs);
790 uint32_t sampleLoadNs = mLoadNs[i];
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700791 loadNs.sample(sampleLoadNs);
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700792#ifdef CPU_FREQUENCY_STATISTICS
793 uint32_t sampleCpukHz = mCpukHz[i];
Glenn Kastenc059bd42012-05-14 17:41:09 -0700794 // skip bad kHz samples
795 if ((sampleCpukHz & ~0xF) != 0) {
796 kHz.sample(sampleCpukHz >> 4);
797 if (sampleCpukHz == previousCpukHz) {
798 double megacycles = (double) sampleLoadNs * (double) (sampleCpukHz >> 4) * 1e-12;
799 double adjMHz = megacycles / mixPeriodSec; // _not_ wallNs * 1e9
800 loadMHz.sample(adjMHz);
801 }
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700802 }
803 previousCpukHz = sampleCpukHz;
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700804#endif
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700805 }
806 fdprintf(fd, "Simple moving statistics over last %.1f seconds:\n", wall.n() * mixPeriodSec);
807 fdprintf(fd, " wall clock time in ms per mix cycle:\n"
808 " mean=%.2f min=%.2f max=%.2f stddev=%.2f\n",
809 wall.mean()*1e-6, wall.minimum()*1e-6, wall.maximum()*1e-6, wall.stddev()*1e-6);
810 fdprintf(fd, " raw CPU load in us per mix cycle:\n"
811 " mean=%.0f min=%.0f max=%.0f stddev=%.0f\n",
812 loadNs.mean()*1e-3, loadNs.minimum()*1e-3, loadNs.maximum()*1e-3,
813 loadNs.stddev()*1e-3);
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700814#ifdef CPU_FREQUENCY_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700815 fdprintf(fd, " CPU clock frequency in MHz:\n"
816 " mean=%.0f min=%.0f max=%.0f stddev=%.0f\n",
817 kHz.mean()*1e-3, kHz.minimum()*1e-3, kHz.maximum()*1e-3, kHz.stddev()*1e-3);
818 fdprintf(fd, " adjusted CPU load in MHz (i.e. normalized for CPU clock frequency):\n"
819 " mean=%.1f min=%.1f max=%.1f stddev=%.1f\n",
820 loadMHz.mean(), loadMHz.minimum(), loadMHz.maximum(), loadMHz.stddev());
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700821#endif
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700822 if (tail != NULL) {
823 qsort(tail, n, sizeof(uint32_t), compare_uint32_t);
824 // assume same number of tail samples on each side, left and right
825 uint32_t count = n / kTailDenominator;
826 CentralTendencyStatistics left, right;
827 for (uint32_t i = 0; i < count; ++i) {
828 left.sample(tail[i]);
829 right.sample(tail[n - (i + 1)]);
830 }
831 fdprintf(fd, "Distribution of mix cycle times in ms for the tails (> ~3 stddev outliers):\n"
832 " left tail: mean=%.2f min=%.2f max=%.2f stddev=%.2f\n"
833 " right tail: mean=%.2f min=%.2f max=%.2f stddev=%.2f\n",
834 left.mean()*1e-6, left.minimum()*1e-6, left.maximum()*1e-6, left.stddev()*1e-6,
835 right.mean()*1e-6, right.minimum()*1e-6, right.maximum()*1e-6,
836 right.stddev()*1e-6);
837 delete[] tail;
838 }
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700839#endif
Glenn Kasten1295bb4d2012-05-31 07:43:43 -0700840 // The active track mask and track states are updated non-atomically.
841 // So if we relied on isActive to decide whether to display,
842 // then we might display an obsolete track or omit an active track.
843 // Instead we always display all tracks, with an indication
844 // of whether we think the track is active.
845 uint32_t trackMask = mTrackMask;
846 fdprintf(fd, "Fast tracks: kMaxFastTracks=%u activeMask=%#x\n",
847 FastMixerState::kMaxFastTracks, trackMask);
848 fdprintf(fd, "Index Active Full Partial Empty Recent Ready\n");
849 for (uint32_t i = 0; i < FastMixerState::kMaxFastTracks; ++i, trackMask >>= 1) {
850 bool isActive = trackMask & 1;
851 const FastTrackDump *ftDump = &mTracks[i];
852 const FastTrackUnderruns& underruns = ftDump->mUnderruns;
853 const char *mostRecent;
854 switch (underruns.mBitFields.mMostRecent) {
855 case UNDERRUN_FULL:
856 mostRecent = "full";
857 break;
858 case UNDERRUN_PARTIAL:
859 mostRecent = "partial";
860 break;
861 case UNDERRUN_EMPTY:
862 mostRecent = "empty";
863 break;
864 default:
865 mostRecent = "?";
866 break;
867 }
868 fdprintf(fd, "%5u %6s %4u %7u %5u %7s %5u\n", i, isActive ? "yes" : "no",
869 (underruns.mBitFields.mFull) & UNDERRUN_MASK,
870 (underruns.mBitFields.mPartial) & UNDERRUN_MASK,
871 (underruns.mBitFields.mEmpty) & UNDERRUN_MASK,
872 mostRecent, ftDump->mFramesReady);
873 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700874}
875
876} // namespace android