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