FastMixer.cpp revision 0ddd56316262ac74a95e9edb595697c163136d6d
1/*
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
17// <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
23#define LOG_TAG "FastMixer"
24//#define LOG_NDEBUG 0
25
26#define ATRACE_TAG ATRACE_TAG_AUDIO
27
28#include <sys/atomics.h>
29#include <time.h>
30#include <utils/Log.h>
31#include <utils/Trace.h>
32#include <system/audio.h>
33#ifdef FAST_MIXER_STATISTICS
34#include <cpustats/CentralTendencyStatistics.h>
35#ifdef CPU_FREQUENCY_STATISTICS
36#include <cpustats/ThreadCpuUsage.h>
37#endif
38#endif
39#include "AudioMixer.h"
40#include "FastMixer.h"
41
42#define FAST_HOT_IDLE_NS     1000000L   // 1 ms: time to sleep while hot idling
43#define FAST_DEFAULT_NS    999999999L   // ~1 sec: default time to sleep
44#define MIN_WARMUP_CYCLES          2    // minimum number of loop cycles to wait for warmup
45#define MAX_WARMUP_CYCLES         10    // maximum number of loop cycles to wait for warmup
46
47namespace android {
48
49// Fast mixer thread
50bool FastMixer::threadLoop()
51{
52    static const FastMixerState initial;
53    const FastMixerState *previous = &initial, *current = &initial;
54    FastMixerState preIdle; // copy of state before we went into idle
55    struct timespec oldTs = {0, 0};
56    bool oldTsValid = false;
57    long slopNs = 0;    // accumulated time we've woken up too early (> 0) or too late (< 0)
58    long sleepNs = -1;  // -1: busy wait, 0: sched_yield, > 0: nanosleep
59    int fastTrackNames[FastMixerState::kMaxFastTracks]; // handles used by mixer to identify tracks
60    int generations[FastMixerState::kMaxFastTracks];    // last observed mFastTracks[i].mGeneration
61    unsigned i;
62    for (i = 0; i < FastMixerState::kMaxFastTracks; ++i) {
63        fastTrackNames[i] = -1;
64        generations[i] = 0;
65    }
66    NBAIO_Sink *outputSink = NULL;
67    int outputSinkGen = 0;
68    AudioMixer* mixer = NULL;
69    short *mixBuffer = NULL;
70    enum {UNDEFINED, MIXED, ZEROED} mixBufferState = UNDEFINED;
71    NBAIO_Format format = Format_Invalid;
72    unsigned sampleRate = 0;
73    int fastTracksGen = 0;
74    long periodNs = 0;      // expected period; the time required to render one mix buffer
75    long underrunNs = 0;    // underrun likely when write cycle is greater than this value
76    long overrunNs = 0;     // overrun likely when write cycle is less than this value
77    long forceNs = 0;       // if overrun detected, force the write cycle to take this much time
78    long warmupNs = 0;      // warmup complete when write cycle is greater than to this value
79    FastMixerDumpState dummyDumpState, *dumpState = &dummyDumpState;
80    bool ignoreNextOverrun = true;  // used to ignore initial overrun and first after an underrun
81#ifdef FAST_MIXER_STATISTICS
82    struct timespec oldLoad = {0, 0};    // previous value of clock_gettime(CLOCK_THREAD_CPUTIME_ID)
83    bool oldLoadValid = false;  // whether oldLoad is valid
84    uint32_t bounds = 0;
85    bool full = false;      // whether we have collected at least kSamplingN samples
86#ifdef CPU_FREQUENCY_STATISTICS
87    ThreadCpuUsage tcu;     // for reading the current CPU clock frequency in kHz
88#endif
89#endif
90    unsigned coldGen = 0;   // last observed mColdGen
91    bool isWarm = false;    // true means ready to mix, false means wait for warmup before mixing
92    struct timespec measuredWarmupTs = {0, 0};  // how long did it take for warmup to complete
93    uint32_t warmupCycles = 0;  // counter of number of loop cycles required to warmup
94    NBAIO_Sink* teeSink = NULL; // if non-NULL, then duplicate write() to this non-blocking sink
95    NBLog::Writer dummyLogWriter, *logWriter = &dummyLogWriter;
96
97    for (;;) {
98
99        // either nanosleep, sched_yield, or busy wait
100        if (sleepNs >= 0) {
101            if (sleepNs > 0) {
102                ALOG_ASSERT(sleepNs < 1000000000);
103                const struct timespec req = {0, sleepNs};
104                nanosleep(&req, NULL);
105            } else {
106                sched_yield();
107            }
108        }
109        // default to long sleep for next cycle
110        sleepNs = FAST_DEFAULT_NS;
111
112        // poll for state change
113        const FastMixerState *next = mSQ.poll();
114        if (next == NULL) {
115            // continue to use the default initial state until a real state is available
116            ALOG_ASSERT(current == &initial && previous == &initial);
117            next = current;
118        }
119
120        FastMixerState::Command command = next->mCommand;
121        if (next != current) {
122
123            logWriter->logTimestamp();
124            logWriter->log("next != current");
125
126            // As soon as possible of learning of a new dump area, start using it
127            dumpState = next->mDumpState != NULL ? next->mDumpState : &dummyDumpState;
128            teeSink = next->mTeeSink;
129            logWriter = next->mNBLogWriter != NULL ? next->mNBLogWriter : &dummyLogWriter;
130
131            // We want to always have a valid reference to the previous (non-idle) state.
132            // However, the state queue only guarantees access to current and previous states.
133            // So when there is a transition from a non-idle state into an idle state, we make a
134            // copy of the last known non-idle state so it is still available on return from idle.
135            // The possible transitions are:
136            //  non-idle -> non-idle    update previous from current in-place
137            //  non-idle -> idle        update previous from copy of current
138            //  idle     -> idle        don't update previous
139            //  idle     -> non-idle    don't update previous
140            if (!(current->mCommand & FastMixerState::IDLE)) {
141                if (command & FastMixerState::IDLE) {
142                    preIdle = *current;
143                    current = &preIdle;
144                    oldTsValid = false;
145                    oldLoadValid = false;
146                    ignoreNextOverrun = true;
147                }
148                previous = current;
149            }
150            current = next;
151        }
152#if !LOG_NDEBUG
153        next = NULL;    // not referenced again
154#endif
155
156        dumpState->mCommand = command;
157
158        switch (command) {
159        case FastMixerState::INITIAL:
160        case FastMixerState::HOT_IDLE:
161            sleepNs = FAST_HOT_IDLE_NS;
162            continue;
163        case FastMixerState::COLD_IDLE:
164            // only perform a cold idle command once
165            // FIXME consider checking previous state and only perform if previous != COLD_IDLE
166            if (current->mColdGen != coldGen) {
167                int32_t *coldFutexAddr = current->mColdFutexAddr;
168                ALOG_ASSERT(coldFutexAddr != NULL);
169                int32_t old = android_atomic_dec(coldFutexAddr);
170                if (old <= 0) {
171                    logWriter->log("wait");
172                    __futex_syscall4(coldFutexAddr, FUTEX_WAIT_PRIVATE, old - 1, NULL);
173                }
174                // This may be overly conservative; there could be times that the normal mixer
175                // requests such a brief cold idle that it doesn't require resetting this flag.
176                isWarm = false;
177                measuredWarmupTs.tv_sec = 0;
178                measuredWarmupTs.tv_nsec = 0;
179                warmupCycles = 0;
180                sleepNs = -1;
181                coldGen = current->mColdGen;
182                bounds = 0;
183                full = false;
184                oldTsValid = !clock_gettime(CLOCK_MONOTONIC, &oldTs);
185            } else {
186                sleepNs = FAST_HOT_IDLE_NS;
187            }
188            continue;
189        case FastMixerState::EXIT:
190            logWriter->log("exit");
191            delete mixer;
192            delete[] mixBuffer;
193            return false;
194        case FastMixerState::MIX:
195        case FastMixerState::WRITE:
196        case FastMixerState::MIX_WRITE:
197            break;
198        default:
199            LOG_FATAL("bad command %d", command);
200        }
201
202        // there is a non-idle state available to us; did the state change?
203        size_t frameCount = current->mFrameCount;
204        if (current != previous) {
205
206            // handle state change here, but since we want to diff the state,
207            // we're prepared for previous == &initial the first time through
208            unsigned previousTrackMask;
209
210            // check for change in output HAL configuration
211            NBAIO_Format previousFormat = format;
212            if (current->mOutputSinkGen != outputSinkGen) {
213                outputSink = current->mOutputSink;
214                outputSinkGen = current->mOutputSinkGen;
215                if (outputSink == NULL) {
216                    format = Format_Invalid;
217                    sampleRate = 0;
218                } else {
219                    format = outputSink->format();
220                    sampleRate = Format_sampleRate(format);
221                    ALOG_ASSERT(Format_channelCount(format) == 2);
222                }
223                dumpState->mSampleRate = sampleRate;
224            }
225
226            if ((format != previousFormat) || (frameCount != previous->mFrameCount)) {
227                // FIXME to avoid priority inversion, don't delete here
228                delete mixer;
229                mixer = NULL;
230                delete[] mixBuffer;
231                mixBuffer = NULL;
232                if (frameCount > 0 && sampleRate > 0) {
233                    // FIXME new may block for unbounded time at internal mutex of the heap
234                    //       implementation; it would be better to have normal mixer allocate for us
235                    //       to avoid blocking here and to prevent possible priority inversion
236                    mixer = new AudioMixer(frameCount, sampleRate, FastMixerState::kMaxFastTracks);
237                    mixBuffer = new short[frameCount * 2];
238                    periodNs = (frameCount * 1000000000LL) / sampleRate;    // 1.00
239                    underrunNs = (frameCount * 1750000000LL) / sampleRate;  // 1.75
240                    overrunNs = (frameCount * 500000000LL) / sampleRate;    // 0.50
241                    forceNs = (frameCount * 950000000LL) / sampleRate;      // 0.95
242                    warmupNs = (frameCount * 500000000LL) / sampleRate;     // 0.50
243                } else {
244                    periodNs = 0;
245                    underrunNs = 0;
246                    overrunNs = 0;
247                    forceNs = 0;
248                    warmupNs = 0;
249                }
250                mixBufferState = UNDEFINED;
251#if !LOG_NDEBUG
252                for (i = 0; i < FastMixerState::kMaxFastTracks; ++i) {
253                    fastTrackNames[i] = -1;
254                }
255#endif
256                // we need to reconfigure all active tracks
257                previousTrackMask = 0;
258                fastTracksGen = current->mFastTracksGen - 1;
259                dumpState->mFrameCount = frameCount;
260            } else {
261                previousTrackMask = previous->mTrackMask;
262            }
263
264            // check for change in active track set
265            unsigned currentTrackMask = current->mTrackMask;
266            dumpState->mTrackMask = currentTrackMask;
267            if (current->mFastTracksGen != fastTracksGen) {
268                logWriter->logf("gen %d", current->mFastTracksGen);
269                ALOG_ASSERT(mixBuffer != NULL);
270                int name;
271
272                // process removed tracks first to avoid running out of track names
273                unsigned removedTracks = previousTrackMask & ~currentTrackMask;
274                if (removedTracks) {
275                    logWriter->logf("removed %#x", removedTracks);
276                }
277                while (removedTracks != 0) {
278                    i = __builtin_ctz(removedTracks);
279                    removedTracks &= ~(1 << i);
280                    const FastTrack* fastTrack = &current->mFastTracks[i];
281                    ALOG_ASSERT(fastTrack->mBufferProvider == NULL);
282                    if (mixer != NULL) {
283                        name = fastTrackNames[i];
284                        ALOG_ASSERT(name >= 0);
285                        mixer->deleteTrackName(name);
286                    }
287#if !LOG_NDEBUG
288                    fastTrackNames[i] = -1;
289#endif
290                    // don't reset track dump state, since other side is ignoring it
291                    generations[i] = fastTrack->mGeneration;
292                }
293
294                // now process added tracks
295                unsigned addedTracks = currentTrackMask & ~previousTrackMask;
296                if (addedTracks) {
297                    logWriter->logf("added %#x", addedTracks);
298                }
299                while (addedTracks != 0) {
300                    i = __builtin_ctz(addedTracks);
301                    addedTracks &= ~(1 << i);
302                    const FastTrack* fastTrack = &current->mFastTracks[i];
303                    AudioBufferProvider *bufferProvider = fastTrack->mBufferProvider;
304                    ALOG_ASSERT(bufferProvider != NULL && fastTrackNames[i] == -1);
305                    if (bufferProvider == NULL ||
306                            bufferProvider->getValid() != AudioBufferProvider::kValid) {
307                        logWriter->logTimestamp();
308                        logWriter->logf("added invalid %#x", i);
309                    }
310                    if (mixer != NULL) {
311                        // calling getTrackName with default channel mask and a random invalid
312                        //   sessionId (no effects here)
313                        name = mixer->getTrackName(AUDIO_CHANNEL_OUT_STEREO, -555);
314                        ALOG_ASSERT(name >= 0);
315                        fastTrackNames[i] = name;
316                        mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::FAST_INDEX,
317                                (void *) i);
318                        mixer->setBufferProvider(name, bufferProvider);
319                        mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::MAIN_BUFFER,
320                                (void *) mixBuffer);
321                        // newly allocated track names default to full scale volume
322                        if (fastTrack->mSampleRate != 0 && fastTrack->mSampleRate != sampleRate) {
323                            mixer->setParameter(name, AudioMixer::RESAMPLE,
324                                    AudioMixer::SAMPLE_RATE, (void*) fastTrack->mSampleRate);
325                        }
326                        mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK,
327                                (void *) fastTrack->mChannelMask);
328                        mixer->enable(name);
329                    }
330                    generations[i] = fastTrack->mGeneration;
331                }
332
333                // finally process (potentially) modified tracks; these use the same slot
334                // but may have a different buffer provider or volume provider
335                unsigned modifiedTracks = currentTrackMask & previousTrackMask;
336                if (modifiedTracks) {
337                    logWriter->logf("pot. mod. %#x", modifiedTracks);
338                }
339                unsigned actuallyModifiedTracks = 0;
340                while (modifiedTracks != 0) {
341                    i = __builtin_ctz(modifiedTracks);
342                    modifiedTracks &= ~(1 << i);
343                    const FastTrack* fastTrack = &current->mFastTracks[i];
344                    if (fastTrack->mGeneration != generations[i]) {
345                        actuallyModifiedTracks |= 1 << i;
346                        AudioBufferProvider *bufferProvider = fastTrack->mBufferProvider;
347                        ALOG_ASSERT(bufferProvider != NULL);
348                        if (bufferProvider == NULL ||
349                                bufferProvider->getValid() != AudioBufferProvider::kValid) {
350                            logWriter->logTimestamp();
351                            logWriter->logf("modified invalid %#x", i);
352                        }
353                        if (mixer != NULL) {
354                            name = fastTrackNames[i];
355                            ALOG_ASSERT(name >= 0);
356                            mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::FAST_INDEX,
357                                    (void *) i);
358                            mixer->setBufferProvider(name, bufferProvider);
359                            if (fastTrack->mVolumeProvider == NULL) {
360                                mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0,
361                                        (void *)0x1000);
362                                mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1,
363                                        (void *)0x1000);
364                            }
365                            if (fastTrack->mSampleRate != 0 &&
366                                    fastTrack->mSampleRate != sampleRate) {
367                                mixer->setParameter(name, AudioMixer::RESAMPLE,
368                                        AudioMixer::SAMPLE_RATE, (void*) fastTrack->mSampleRate);
369                            } else {
370                                mixer->setParameter(name, AudioMixer::RESAMPLE,
371                                        AudioMixer::REMOVE, NULL);
372                            }
373                            mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK,
374                                    (void *) fastTrack->mChannelMask);
375                            // already enabled
376                        }
377                        generations[i] = fastTrack->mGeneration;
378                    }
379                }
380                if (actuallyModifiedTracks) {
381                    logWriter->logf("act. mod. %#x", actuallyModifiedTracks);
382                }
383
384                fastTracksGen = current->mFastTracksGen;
385
386                dumpState->mNumTracks = popcount(currentTrackMask);
387            }
388
389#if 1   // FIXME shouldn't need this
390            // only process state change once
391            previous = current;
392#endif
393        }
394
395        // do work using current state here
396        if ((command & FastMixerState::MIX) && (mixer != NULL) && isWarm) {
397            ALOG_ASSERT(mixBuffer != NULL);
398            // for each track, update volume and check for underrun
399            unsigned currentTrackMask = current->mTrackMask;
400            while (currentTrackMask != 0) {
401                i = __builtin_ctz(currentTrackMask);
402                currentTrackMask &= ~(1 << i);
403                const FastTrack* fastTrack = &current->mFastTracks[i];
404                int name = fastTrackNames[i];
405                ALOG_ASSERT(name >= 0);
406                if (fastTrack->mVolumeProvider != NULL) {
407                    uint32_t vlr = fastTrack->mVolumeProvider->getVolumeLR();
408                    mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0,
409                            (void *)(vlr & 0xFFFF));
410                    mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1,
411                            (void *)(vlr >> 16));
412                }
413                // FIXME The current implementation of framesReady() for fast tracks
414                // takes a tryLock, which can block
415                // up to 1 ms.  If enough active tracks all blocked in sequence, this would result
416                // in the overall fast mix cycle being delayed.  Should use a non-blocking FIFO.
417                size_t framesReady = fastTrack->mBufferProvider->framesReady();
418                if (ATRACE_ENABLED()) {
419                    // I wish we had formatted trace names
420                    char traceName[16];
421                    strcpy(traceName, "framesReady");
422                    traceName[11] = i + (i < 10 ? '0' : 'A' - 10);
423                    traceName[12] = '\0';
424                    ATRACE_INT(traceName, framesReady);
425                }
426                FastTrackDump *ftDump = &dumpState->mTracks[i];
427                FastTrackUnderruns underruns = ftDump->mUnderruns;
428                if (framesReady < frameCount) {
429                    if (framesReady == 0) {
430                        underruns.mBitFields.mEmpty++;
431                        underruns.mBitFields.mMostRecent = UNDERRUN_EMPTY;
432                        mixer->disable(name);
433                    } else {
434                        // allow mixing partial buffer
435                        underruns.mBitFields.mPartial++;
436                        underruns.mBitFields.mMostRecent = UNDERRUN_PARTIAL;
437                        mixer->enable(name);
438                    }
439                } else {
440                    underruns.mBitFields.mFull++;
441                    underruns.mBitFields.mMostRecent = UNDERRUN_FULL;
442                    mixer->enable(name);
443                }
444                ftDump->mUnderruns = underruns;
445                ftDump->mFramesReady = framesReady;
446                AudioBufferProvider *bufferProvider = fastTrack->mBufferProvider;
447                if (bufferProvider == NULL ||
448                        bufferProvider->getValid() != AudioBufferProvider::kValid) {
449                    logWriter->logTimestamp();
450                    logWriter->logf("mixing invalid %#x", i);
451                }
452            }
453
454            int64_t pts;
455            if (outputSink == NULL || (OK != outputSink->getNextWriteTimestamp(&pts)))
456                pts = AudioBufferProvider::kInvalidPTS;
457
458            // process() is CPU-bound
459            mixer->process(pts);
460            mixBufferState = MIXED;
461        } else if (mixBufferState == MIXED) {
462            mixBufferState = UNDEFINED;
463        }
464        bool attemptedWrite = false;
465        //bool didFullWrite = false;    // dumpsys could display a count of partial writes
466        if ((command & FastMixerState::WRITE) && (outputSink != NULL) && (mixBuffer != NULL)) {
467            if (mixBufferState == UNDEFINED) {
468                memset(mixBuffer, 0, frameCount * 2 * sizeof(short));
469                mixBufferState = ZEROED;
470            }
471            if (teeSink != NULL) {
472                (void) teeSink->write(mixBuffer, frameCount);
473            }
474            // FIXME write() is non-blocking and lock-free for a properly implemented NBAIO sink,
475            //       but this code should be modified to handle both non-blocking and blocking sinks
476            dumpState->mWriteSequence++;
477            ATRACE_BEGIN("write");
478            ssize_t framesWritten = outputSink->write(mixBuffer, frameCount);
479            ATRACE_END();
480            dumpState->mWriteSequence++;
481            if (framesWritten >= 0) {
482                ALOG_ASSERT(framesWritten <= frameCount);
483                dumpState->mFramesWritten += framesWritten;
484                //if ((size_t) framesWritten == frameCount) {
485                //    didFullWrite = true;
486                //}
487            } else {
488                dumpState->mWriteErrors++;
489            }
490            attemptedWrite = true;
491            // FIXME count # of writes blocked excessively, CPU usage, etc. for dump
492        }
493
494        // To be exactly periodic, compute the next sleep time based on current time.
495        // This code doesn't have long-term stability when the sink is non-blocking.
496        // FIXME To avoid drift, use the local audio clock or watch the sink's fill status.
497        struct timespec newTs;
498        int rc = clock_gettime(CLOCK_MONOTONIC, &newTs);
499        if (rc == 0) {
500            logWriter->logTimestamp(newTs);
501            if (oldTsValid) {
502                time_t sec = newTs.tv_sec - oldTs.tv_sec;
503                long nsec = newTs.tv_nsec - oldTs.tv_nsec;
504                ALOGE_IF(sec < 0 || (sec == 0 && nsec < 0),
505                        "clock_gettime(CLOCK_MONOTONIC) failed: was %ld.%09ld but now %ld.%09ld",
506                        oldTs.tv_sec, oldTs.tv_nsec, newTs.tv_sec, newTs.tv_nsec);
507                if (nsec < 0) {
508                    --sec;
509                    nsec += 1000000000;
510                }
511                // To avoid an initial underrun on fast tracks after exiting standby,
512                // do not start pulling data from tracks and mixing until warmup is complete.
513                // Warmup is considered complete after the earlier of:
514                //      MIN_WARMUP_CYCLES write() attempts and last one blocks for at least warmupNs
515                //      MAX_WARMUP_CYCLES write() attempts.
516                // This is overly conservative, but to get better accuracy requires a new HAL API.
517                if (!isWarm && attemptedWrite) {
518                    measuredWarmupTs.tv_sec += sec;
519                    measuredWarmupTs.tv_nsec += nsec;
520                    if (measuredWarmupTs.tv_nsec >= 1000000000) {
521                        measuredWarmupTs.tv_sec++;
522                        measuredWarmupTs.tv_nsec -= 1000000000;
523                    }
524                    ++warmupCycles;
525                    if ((nsec > warmupNs && warmupCycles >= MIN_WARMUP_CYCLES) ||
526                            (warmupCycles >= MAX_WARMUP_CYCLES)) {
527                        isWarm = true;
528                        dumpState->mMeasuredWarmupTs = measuredWarmupTs;
529                        dumpState->mWarmupCycles = warmupCycles;
530                    }
531                }
532                sleepNs = -1;
533              if (isWarm) {
534                if (sec > 0 || nsec > underrunNs) {
535                    ATRACE_NAME("underrun");
536                    // FIXME only log occasionally
537                    ALOGV("underrun: time since last cycle %d.%03ld sec",
538                            (int) sec, nsec / 1000000L);
539                    dumpState->mUnderruns++;
540                    ignoreNextOverrun = true;
541                } else if (nsec < overrunNs) {
542                    if (ignoreNextOverrun) {
543                        ignoreNextOverrun = false;
544                    } else {
545                        // FIXME only log occasionally
546                        ALOGV("overrun: time since last cycle %d.%03ld sec",
547                                (int) sec, nsec / 1000000L);
548                        dumpState->mOverruns++;
549                    }
550                    // This forces a minimum cycle time. It:
551                    //   - compensates for an audio HAL with jitter due to sample rate conversion
552                    //   - works with a variable buffer depth audio HAL that never pulls at a rate
553                    //     < than overrunNs per buffer.
554                    //   - recovers from overrun immediately after underrun
555                    // It doesn't work with a non-blocking audio HAL.
556                    sleepNs = forceNs - nsec;
557                } else {
558                    ignoreNextOverrun = false;
559                }
560              }
561#ifdef FAST_MIXER_STATISTICS
562              if (isWarm) {
563                // advance the FIFO queue bounds
564                size_t i = bounds & (FastMixerDumpState::kSamplingN - 1);
565                bounds = (bounds & 0xFFFF0000) | ((bounds + 1) & 0xFFFF);
566                if (full) {
567                    bounds += 0x10000;
568                } else if (!(bounds & (FastMixerDumpState::kSamplingN - 1))) {
569                    full = true;
570                }
571                // compute the delta value of clock_gettime(CLOCK_MONOTONIC)
572                uint32_t monotonicNs = nsec;
573                if (sec > 0 && sec < 4) {
574                    monotonicNs += sec * 1000000000;
575                }
576                // compute the raw CPU load = delta value of clock_gettime(CLOCK_THREAD_CPUTIME_ID)
577                uint32_t loadNs = 0;
578                struct timespec newLoad;
579                rc = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &newLoad);
580                if (rc == 0) {
581                    if (oldLoadValid) {
582                        sec = newLoad.tv_sec - oldLoad.tv_sec;
583                        nsec = newLoad.tv_nsec - oldLoad.tv_nsec;
584                        if (nsec < 0) {
585                            --sec;
586                            nsec += 1000000000;
587                        }
588                        loadNs = nsec;
589                        if (sec > 0 && sec < 4) {
590                            loadNs += sec * 1000000000;
591                        }
592                    } else {
593                        // first time through the loop
594                        oldLoadValid = true;
595                    }
596                    oldLoad = newLoad;
597                }
598#ifdef CPU_FREQUENCY_STATISTICS
599                // get the absolute value of CPU clock frequency in kHz
600                int cpuNum = sched_getcpu();
601                uint32_t kHz = tcu.getCpukHz(cpuNum);
602                kHz = (kHz << 4) | (cpuNum & 0xF);
603#endif
604                // save values in FIFO queues for dumpsys
605                // these stores #1, #2, #3 are not atomic with respect to each other,
606                // or with respect to store #4 below
607                dumpState->mMonotonicNs[i] = monotonicNs;
608                dumpState->mLoadNs[i] = loadNs;
609#ifdef CPU_FREQUENCY_STATISTICS
610                dumpState->mCpukHz[i] = kHz;
611#endif
612                // this store #4 is not atomic with respect to stores #1, #2, #3 above, but
613                // the newest open and oldest closed halves are atomic with respect to each other
614                dumpState->mBounds = bounds;
615                ATRACE_INT("cycle_ms", monotonicNs / 1000000);
616                ATRACE_INT("load_us", loadNs / 1000);
617              }
618#endif
619            } else {
620                // first time through the loop
621                oldTsValid = true;
622                sleepNs = periodNs;
623                ignoreNextOverrun = true;
624            }
625            oldTs = newTs;
626        } else {
627            // monotonic clock is broken
628            oldTsValid = false;
629            sleepNs = periodNs;
630        }
631
632
633    }   // for (;;)
634
635    // never return 'true'; Thread::_threadLoop() locks mutex which can result in priority inversion
636}
637
638FastMixerDumpState::FastMixerDumpState() :
639    mCommand(FastMixerState::INITIAL), mWriteSequence(0), mFramesWritten(0),
640    mNumTracks(0), mWriteErrors(0), mUnderruns(0), mOverruns(0),
641    mSampleRate(0), mFrameCount(0), /* mMeasuredWarmupTs({0, 0}), */ mWarmupCycles(0),
642    mTrackMask(0)
643#ifdef FAST_MIXER_STATISTICS
644    , mBounds(0)
645#endif
646{
647    mMeasuredWarmupTs.tv_sec = 0;
648    mMeasuredWarmupTs.tv_nsec = 0;
649    // sample arrays aren't accessed atomically with respect to the bounds,
650    // so clearing reduces chance for dumpsys to read random uninitialized samples
651    memset(&mMonotonicNs, 0, sizeof(mMonotonicNs));
652    memset(&mLoadNs, 0, sizeof(mLoadNs));
653#ifdef CPU_FREQUENCY_STATISTICS
654    memset(&mCpukHz, 0, sizeof(mCpukHz));
655#endif
656}
657
658FastMixerDumpState::~FastMixerDumpState()
659{
660}
661
662// helper function called by qsort()
663static int compare_uint32_t(const void *pa, const void *pb)
664{
665    uint32_t a = *(const uint32_t *)pa;
666    uint32_t b = *(const uint32_t *)pb;
667    if (a < b) {
668        return -1;
669    } else if (a > b) {
670        return 1;
671    } else {
672        return 0;
673    }
674}
675
676void FastMixerDumpState::dump(int fd)
677{
678    if (mCommand == FastMixerState::INITIAL) {
679        fdprintf(fd, "FastMixer not initialized\n");
680        return;
681    }
682#define COMMAND_MAX 32
683    char string[COMMAND_MAX];
684    switch (mCommand) {
685    case FastMixerState::INITIAL:
686        strcpy(string, "INITIAL");
687        break;
688    case FastMixerState::HOT_IDLE:
689        strcpy(string, "HOT_IDLE");
690        break;
691    case FastMixerState::COLD_IDLE:
692        strcpy(string, "COLD_IDLE");
693        break;
694    case FastMixerState::EXIT:
695        strcpy(string, "EXIT");
696        break;
697    case FastMixerState::MIX:
698        strcpy(string, "MIX");
699        break;
700    case FastMixerState::WRITE:
701        strcpy(string, "WRITE");
702        break;
703    case FastMixerState::MIX_WRITE:
704        strcpy(string, "MIX_WRITE");
705        break;
706    default:
707        snprintf(string, COMMAND_MAX, "%d", mCommand);
708        break;
709    }
710    double measuredWarmupMs = (mMeasuredWarmupTs.tv_sec * 1000.0) +
711            (mMeasuredWarmupTs.tv_nsec / 1000000.0);
712    double mixPeriodSec = (double) mFrameCount / (double) mSampleRate;
713    fdprintf(fd, "FastMixer command=%s writeSequence=%u framesWritten=%u\n"
714                 "          numTracks=%u writeErrors=%u underruns=%u overruns=%u\n"
715                 "          sampleRate=%u frameCount=%u measuredWarmup=%.3g ms, warmupCycles=%u\n"
716                 "          mixPeriod=%.2f ms\n",
717                 string, mWriteSequence, mFramesWritten,
718                 mNumTracks, mWriteErrors, mUnderruns, mOverruns,
719                 mSampleRate, mFrameCount, measuredWarmupMs, mWarmupCycles,
720                 mixPeriodSec * 1e3);
721#ifdef FAST_MIXER_STATISTICS
722    // find the interval of valid samples
723    uint32_t bounds = mBounds;
724    uint32_t newestOpen = bounds & 0xFFFF;
725    uint32_t oldestClosed = bounds >> 16;
726    uint32_t n = (newestOpen - oldestClosed) & 0xFFFF;
727    if (n > kSamplingN) {
728        ALOGE("too many samples %u", n);
729        n = kSamplingN;
730    }
731    // statistics for monotonic (wall clock) time, thread raw CPU load in time, CPU clock frequency,
732    // and adjusted CPU load in MHz normalized for CPU clock frequency
733    CentralTendencyStatistics wall, loadNs;
734#ifdef CPU_FREQUENCY_STATISTICS
735    CentralTendencyStatistics kHz, loadMHz;
736    uint32_t previousCpukHz = 0;
737#endif
738    // Assuming a normal distribution for cycle times, three standard deviations on either side of
739    // the mean account for 99.73% of the population.  So if we take each tail to be 1/1000 of the
740    // sample set, we get 99.8% combined, or close to three standard deviations.
741    static const uint32_t kTailDenominator = 1000;
742    uint32_t *tail = n >= kTailDenominator ? new uint32_t[n] : NULL;
743    // loop over all the samples
744    for (uint32_t j = 0; j < n; ++j) {
745        size_t i = oldestClosed++ & (kSamplingN - 1);
746        uint32_t wallNs = mMonotonicNs[i];
747        if (tail != NULL) {
748            tail[j] = wallNs;
749        }
750        wall.sample(wallNs);
751        uint32_t sampleLoadNs = mLoadNs[i];
752        loadNs.sample(sampleLoadNs);
753#ifdef CPU_FREQUENCY_STATISTICS
754        uint32_t sampleCpukHz = mCpukHz[i];
755        // skip bad kHz samples
756        if ((sampleCpukHz & ~0xF) != 0) {
757            kHz.sample(sampleCpukHz >> 4);
758            if (sampleCpukHz == previousCpukHz) {
759                double megacycles = (double) sampleLoadNs * (double) (sampleCpukHz >> 4) * 1e-12;
760                double adjMHz = megacycles / mixPeriodSec;  // _not_ wallNs * 1e9
761                loadMHz.sample(adjMHz);
762            }
763        }
764        previousCpukHz = sampleCpukHz;
765#endif
766    }
767    fdprintf(fd, "Simple moving statistics over last %.1f seconds:\n", wall.n() * mixPeriodSec);
768    fdprintf(fd, "  wall clock time in ms per mix cycle:\n"
769                 "    mean=%.2f min=%.2f max=%.2f stddev=%.2f\n",
770                 wall.mean()*1e-6, wall.minimum()*1e-6, wall.maximum()*1e-6, wall.stddev()*1e-6);
771    fdprintf(fd, "  raw CPU load in us per mix cycle:\n"
772                 "    mean=%.0f min=%.0f max=%.0f stddev=%.0f\n",
773                 loadNs.mean()*1e-3, loadNs.minimum()*1e-3, loadNs.maximum()*1e-3,
774                 loadNs.stddev()*1e-3);
775#ifdef CPU_FREQUENCY_STATISTICS
776    fdprintf(fd, "  CPU clock frequency in MHz:\n"
777                 "    mean=%.0f min=%.0f max=%.0f stddev=%.0f\n",
778                 kHz.mean()*1e-3, kHz.minimum()*1e-3, kHz.maximum()*1e-3, kHz.stddev()*1e-3);
779    fdprintf(fd, "  adjusted CPU load in MHz (i.e. normalized for CPU clock frequency):\n"
780                 "    mean=%.1f min=%.1f max=%.1f stddev=%.1f\n",
781                 loadMHz.mean(), loadMHz.minimum(), loadMHz.maximum(), loadMHz.stddev());
782#endif
783    if (tail != NULL) {
784        qsort(tail, n, sizeof(uint32_t), compare_uint32_t);
785        // assume same number of tail samples on each side, left and right
786        uint32_t count = n / kTailDenominator;
787        CentralTendencyStatistics left, right;
788        for (uint32_t i = 0; i < count; ++i) {
789            left.sample(tail[i]);
790            right.sample(tail[n - (i + 1)]);
791        }
792        fdprintf(fd, "Distribution of mix cycle times in ms for the tails (> ~3 stddev outliers):\n"
793                     "  left tail: mean=%.2f min=%.2f max=%.2f stddev=%.2f\n"
794                     "  right tail: mean=%.2f min=%.2f max=%.2f stddev=%.2f\n",
795                     left.mean()*1e-6, left.minimum()*1e-6, left.maximum()*1e-6, left.stddev()*1e-6,
796                     right.mean()*1e-6, right.minimum()*1e-6, right.maximum()*1e-6,
797                     right.stddev()*1e-6);
798        delete[] tail;
799    }
800#endif
801    // The active track mask and track states are updated non-atomically.
802    // So if we relied on isActive to decide whether to display,
803    // then we might display an obsolete track or omit an active track.
804    // Instead we always display all tracks, with an indication
805    // of whether we think the track is active.
806    uint32_t trackMask = mTrackMask;
807    fdprintf(fd, "Fast tracks: kMaxFastTracks=%u activeMask=%#x\n",
808            FastMixerState::kMaxFastTracks, trackMask);
809    fdprintf(fd, "Index Active Full Partial Empty  Recent Ready\n");
810    for (uint32_t i = 0; i < FastMixerState::kMaxFastTracks; ++i, trackMask >>= 1) {
811        bool isActive = trackMask & 1;
812        const FastTrackDump *ftDump = &mTracks[i];
813        const FastTrackUnderruns& underruns = ftDump->mUnderruns;
814        const char *mostRecent;
815        switch (underruns.mBitFields.mMostRecent) {
816        case UNDERRUN_FULL:
817            mostRecent = "full";
818            break;
819        case UNDERRUN_PARTIAL:
820            mostRecent = "partial";
821            break;
822        case UNDERRUN_EMPTY:
823            mostRecent = "empty";
824            break;
825        default:
826            mostRecent = "?";
827            break;
828        }
829        fdprintf(fd, "%5u %6s %4u %7u %5u %7s %5u\n", i, isActive ? "yes" : "no",
830                (underruns.mBitFields.mFull) & UNDERRUN_MASK,
831                (underruns.mBitFields.mPartial) & UNDERRUN_MASK,
832                (underruns.mBitFields.mEmpty) & UNDERRUN_MASK,
833                mostRecent, ftDump->mFramesReady);
834    }
835}
836
837}   // namespace android
838