aboutsummaryrefslogtreecommitdiff
path: root/apps/OboeTester/app/src/main/java/com/mobileer/oboetester/AudioStreamBase.java
blob: 14eb163e424f8947c7c42ee5654ac600a6817a88 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/*
 * Copyright 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mobileer.oboetester;

import java.io.IOException;
import java.util.Locale;

/**
 * Base class for any audio input or output.
 */
public abstract class AudioStreamBase {

    private StreamConfiguration mRequestedStreamConfiguration;
    private StreamConfiguration mActualStreamConfiguration;
    private AudioStreamBase.DoubleStatistics mLatencyStatistics;
    private SampleRateMonitor mSampleRateMonitor = new SampleRateMonitor();
    private int mBufferSizeInFrames;

    private class SampleRateMonitor {
        private static final int SIZE = 16; // power of 2
        private static final long MASK = SIZE - 1L;
        private long[] times = new long[SIZE];
        private long[] frames = new long[SIZE];
        private long cursor;

        void add(long numFrames) {
            int index = (int) (cursor & MASK);
            frames[index] = numFrames;
            times[index] = System.currentTimeMillis();
            cursor++;
        }

        int getRate() {
            if (cursor < 2) return 0;
            long numValid = Math.min((long)SIZE, cursor);
            int oldestIndex = (int)((cursor - numValid) & MASK);
            int newestIndex = (int)((cursor - 1) & MASK);
            long deltaTime = times[newestIndex] - times[oldestIndex];
            long deltaFrames = frames[newestIndex] - frames[oldestIndex];
            if (deltaTime <= 0) {
                return -1;
            }
            long sampleRate = (deltaFrames * 1000) / deltaTime;
            return (int) sampleRate;
        }

        void reset() {
            cursor = 0;
        }
    }

    public StreamStatus getStreamStatus() {
        StreamStatus status = new StreamStatus();
        status.bufferSize = getBufferSizeInFrames();
        status.xRunCount = getXRunCount();
        status.framesRead = getFramesRead();
        status.framesWritten = getFramesWritten();
        status.callbackCount = getCallbackCount();
        status.latency = getLatency();
        mLatencyStatistics.add(status.latency);
        status.callbackTimeStr = getCallbackTimeStr();
        status.cpuLoad = getCpuLoad();
        status.state = getState();
        mSampleRateMonitor.add(status.framesRead);
        status.measuredRate = mSampleRateMonitor.getRate();
        return status;
    }

    public DoubleStatistics getLatencyStatistics() {
        return mLatencyStatistics;
    }

    public void setPerformanceHintEnabled(boolean checked) {
    }
    public void setHearWorkload(boolean checked) {
    }

    public static class DoubleStatistics {
        private double sum;
        private int count;
        private double minimum = Double.MAX_VALUE;
        private double maximum = Double.MIN_VALUE;

        void add(double statistic) {
            if (statistic <= 0.0) return;
            sum += statistic;
            count++;
            minimum = Math.min(statistic, minimum);
            maximum = Math.max(statistic, maximum);
        }

        double getAverage() {
            return sum / count;
        }

        public String dump() {
            if (count == 0) return "?";
            return String.format(Locale.getDefault(), "%3.1f/%3.1f/%3.1f ms", minimum, getAverage(), maximum);
        }
    }

    /**
     * Changes dynamic at run-time.
     */
    public static class StreamStatus {
        public int bufferSize;
        public int xRunCount;
        public long framesWritten;
        public long framesRead;
        public double latency; // msec
        public int state;
        public long callbackCount;
        public int framesPerCallback;
        public float cpuLoad;
        public String callbackTimeStr;
        public int measuredRate;

        // These are constantly changing.
        String dump(int framesPerBurst) {
            if (bufferSize < 0 || framesWritten < 0) {
                return "idle";
            }
            StringBuffer buffer = new StringBuffer();

            buffer.append("time between callbacks = " + callbackTimeStr + "\n");

            buffer.append("wr "
                    + String.format(Locale.getDefault(), "%Xh", framesWritten)
                    + " - rd " + String.format(Locale.getDefault(), "%Xh", framesRead)
                    + " = " + (framesWritten - framesRead) + " fr"
                    + ", SR = " + ((measuredRate <= 0) ? "?" : measuredRate) + "\n");

            String cpuLoadText = String.format(Locale.getDefault(), "%2d%c", (int)(cpuLoad * 100), '%');
            buffer.append(
                    convertStateToString(state)
                    + ", #cb=" + callbackCount
                    + ", f/cb=" + String.format(Locale.getDefault(), "%3d", framesPerCallback)
                    + ", " + cpuLoadText + " CPU"
                    + "\n");

            buffer.append("buffer size = ");
            if (bufferSize <= 0 || framesPerBurst <= 0) {
                buffer.append("?");
            } else {
                int numBuffers = bufferSize / framesPerBurst;
                int remainder = bufferSize - (numBuffers * framesPerBurst);
                buffer.append(bufferSize + " = (" + numBuffers + " * " + framesPerBurst + ") + " + remainder);
            }
            buffer.append(",   xRun# = " + ((xRunCount < 0) ? "?" : xRunCount));

            return buffer.toString();
        }
        /**
         * Converts ints from Oboe index to human-readable stream state
         */
        private String convertStateToString(int stateId) {
            final String[] STATE_ARRAY = {"Uninit.", "Unknown", "Open", "Starting", "Started",
                    "Pausing", "Paused", "Flushing", "Flushed",
                    "Stopping", "Stopped", "Closing", "Closed", "Disconn."};
            if (stateId < 0 || stateId >= STATE_ARRAY.length) {
                return "Invalid - " + stateId;
            }
            return STATE_ARRAY[stateId];
        }
    }

    /**
     *
     * @param requestedConfiguration
     * @param actualConfiguration
     * @param bufferSizeInFrames
     * @throws IOException
     */
    public void open(StreamConfiguration requestedConfiguration,
                     StreamConfiguration actualConfiguration,
                     int bufferSizeInFrames) throws IOException {
        mRequestedStreamConfiguration = requestedConfiguration;
        mActualStreamConfiguration = actualConfiguration;
        mBufferSizeInFrames = bufferSizeInFrames;
        mLatencyStatistics = new AudioStreamBase.DoubleStatistics();
    }

    public void onStart() {
        mSampleRateMonitor.reset();
    }
    public void onStop() {
        mSampleRateMonitor.reset();
    }

    public abstract boolean isInput();

    public void startPlayback() throws IOException {}

    public void stopPlayback() throws IOException {}

    public abstract void close();

    public int getChannelCount() {
        return mActualStreamConfiguration.getChannelCount();
    }

    public int getSampleRate() {
        return mActualStreamConfiguration.getSampleRate();
    }

    public int getFramesPerBurst() {
        return mActualStreamConfiguration.getFramesPerBurst();
    }

    public int getBufferCapacityInFrames() {
        return mBufferSizeInFrames;
    }

    public int getBufferSizeInFrames() {
        return mBufferSizeInFrames;
    }

    public int setBufferSizeInFrames(int bufferSize) {
        throw new UnsupportedOperationException("bufferSize cannot be changed");
    }

    public long getCallbackCount() { return -1; }

    public int getLastErrorCallbackResult() { return 0; }

    public long getFramesWritten() { return -1; }

    public long getFramesRead() { return -1; }

    public double getLatency() { return -1.0; }

    public float getCpuLoad() { return 0.0f; }
    public float getAndResetMaxCpuLoad() { return 0.0f; }
    public int getAndResetCpuMask() { return 0; }

    public String getCallbackTimeStr() { return "?"; };

    public int getState() { return -1; }

    public void setWorkload(int workload) {}

    public abstract int getXRunCount();

}