aboutsummaryrefslogtreecommitdiff
path: root/apps/OboeTester/app/src/main/cpp/OboeStreamCallbackProxy.h
blob: d72eaa966e429e61652437fac601fabf11698f0c (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
259
260
/*
 * Copyright 2017 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.
 */

#ifndef NATIVEOBOE_OBOESTREAMCALLBACKPROXY_H
#define NATIVEOBOE_OBOESTREAMCALLBACKPROXY_H

#include <unistd.h>
#include <sys/types.h>
#include <sys/sysinfo.h>

#include "oboe/Oboe.h"
#include "synth/Synthesizer.h"
#include "synth/SynthTools.h"

class DoubleStatistics {
public:
    void add(double statistic) {
        if (skipCount < kNumberStatisticsToSkip) {
            skipCount++;
        } else {
            if (statistic <= 0.0) return;
            sum = statistic + sum;
            count++;
            minimum = std::min(statistic, minimum.load());
            maximum = std::max(statistic, maximum.load());
        }
    }

    double getAverage() const {
        return sum / count;
    }

    std::string dump() const {
        if (count == 0) return "?";
        char buff[100];
        snprintf(buff, sizeof(buff), "%3.1f/%3.1f/%3.1f ms", minimum.load(), getAverage(), maximum.load());
        std::string buffAsStr = buff;
        return buffAsStr;
    }

    void clear() {
        skipCount = 0;
        sum = 0;
        count = 0;
        minimum = DBL_MAX;
        maximum = 0;
    }

private:
    static constexpr double kNumberStatisticsToSkip = 5; // Skip the first 5 frames
    std::atomic<int> skipCount { 0 };
    std::atomic<double> sum { 0 };
    std::atomic<int> count { 0 };
    std::atomic<double> minimum { DBL_MAX };
    std::atomic<double> maximum { 0 };
};

/**
 * Manage the synthesizer workload that burdens the CPU.
 * Adjust the number of voices according to the requested workload.
 * Trigger noteOn and noteOff messages.
 */
class SynthWorkload {
public:
    SynthWorkload() {
        mSynth.setup(marksynth::kSynthmarkSampleRate, marksynth::kSynthmarkMaxVoices);
    }

    void onCallback(double workload) {
        // If workload changes then restart notes.
        if (workload != mPreviousWorkload) {
            mSynth.allNotesOff();
            mAreNotesOn = false;
            mCountdown = 0; // trigger notes on
            mPreviousWorkload = workload;
        }
        if (mCountdown <= 0) {
            if (mAreNotesOn) {
                mSynth.allNotesOff();
                mAreNotesOn = false;
                mCountdown = mOffFrames;
            } else {
                mSynth.notesOn((int)mPreviousWorkload);
                mAreNotesOn = true;
                mCountdown = mOnFrames;
            }
        }
    }

    /**
     * Render the notes into a stereo buffer.
     * Passing a nullptr will cause the calculated results to be discarded.
     * The workload should be the same.
     * @param buffer a real stereo buffer or nullptr
     * @param numFrames
     */
    void renderStereo(float *buffer, int numFrames) {
        if (buffer == nullptr) {
            int framesLeft = numFrames;
            while (framesLeft > 0) {
                int framesThisTime = std::min(kDummyBufferSizeInFrames, framesLeft);
                // Do the work then throw it away.
                mSynth.renderStereo(&mDummyStereoBuffer[0], framesThisTime);
                framesLeft -= framesThisTime;
            }
        } else {
            mSynth.renderStereo(buffer, numFrames);
        }
        mCountdown -= numFrames;
    }

private:
    marksynth::Synthesizer   mSynth;
    static constexpr int     kDummyBufferSizeInFrames = 32;
    float                    mDummyStereoBuffer[kDummyBufferSizeInFrames * 2];
    double                   mPreviousWorkload = 1.0;
    bool                     mAreNotesOn = false;
    int                      mCountdown = 0;
    int                      mOnFrames = (int) (0.2 * 48000);
    int                      mOffFrames = (int) (0.3 * 48000);
};

class OboeStreamCallbackProxy : public oboe::AudioStreamCallback {
public:

    void setCallback(oboe::AudioStreamCallback *callback) {
        mCallback = callback;
        setCallbackCount(0);
        mStatistics.clear();
        mPreviousMask = 0;
    }

    static void setCallbackReturnStop(bool b) {
        mCallbackReturnStop = b;
    }

    int64_t getCallbackCount() {
        return mCallbackCount;
    }

    void setCallbackCount(int64_t count) {
        mCallbackCount = count;
    }

    int32_t getFramesPerCallback() {
        return mFramesPerCallback.load();
    }

    /**
     * Called when the stream is ready to process audio.
     */
    oboe::DataCallbackResult onAudioReady(
            oboe::AudioStream *audioStream,
            void *audioData,
            int numFrames) override;

    /**
     * Specify the amount of artificial workload that will waste CPU cycles
     * and increase the CPU load.
     * @param workload typically ranges from 0 to 400
     */
    void setWorkload(int32_t workload) {
        mNumWorkloadVoices = std::max(0, workload);
    }

    int32_t getWorkload() const {
        return mNumWorkloadVoices;
    }

    void setHearWorkload(bool enabled) {
        mHearWorkload = enabled;
    }

    /**
     * This is the callback duration relative to the real-time equivalent.
     * So it may be higher than 1.0.
     * @return low pass filtered value for the fractional CPU load
     */
    float getCpuLoad() const {
        return mCpuLoad;
    }

    /**
     * Calling this will atomically reset the max to zero so only call
     * this from one client.
     *
     * @return last value of the maximum unfiltered CPU load.
     */
    float getAndResetMaxCpuLoad() {
        return mMaxCpuLoad.exchange(0.0f);
    }

    std::string getCallbackTimeString() const {
        return mStatistics.dump();
    }

    static int64_t getNanoseconds(clockid_t clockId = CLOCK_MONOTONIC);

    /**
     * @param cpuIndex
     * @return 0 on success or a negative errno
     */
    int setCpuAffinity(int cpuIndex) {
        cpu_set_t cpu_set;
        CPU_ZERO(&cpu_set);
        CPU_SET(cpuIndex, &cpu_set);
        int err = sched_setaffinity((pid_t) 0, sizeof(cpu_set_t), &cpu_set);
        return err == 0 ? 0 : -errno;
    }

    int applyCpuAffinityMask(uint32_t mask) {
        cpu_set_t cpu_set;
        CPU_ZERO(&cpu_set);
        int cpuCount = get_nprocs();
        for (int cpuIndex = 0; cpuIndex < cpuCount; cpuIndex++) {
            if (mask & (1 << cpuIndex)) {
                CPU_SET(cpuIndex, &cpu_set);
            }
        }
        int err = sched_setaffinity((pid_t) 0, sizeof(cpu_set_t), &cpu_set);
        return err == 0 ? 0 : -errno;
    }

    void setCpuAffinityMask(uint32_t mask) {
        mCpuAffinityMask = mask;
    }

private:
    static constexpr double    kNsToMsScaler = 0.000001;
    std::atomic<float>         mCpuLoad{0.0f};
    std::atomic<float >        mMaxCpuLoad{0.0f};
    int64_t                    mPreviousCallbackTimeNs = 0;
    DoubleStatistics           mStatistics;
    int32_t                    mNumWorkloadVoices = 0;
    SynthWorkload              mSynthWorkload;
    bool                       mHearWorkload = false;

    oboe::AudioStreamCallback *mCallback = nullptr;
    static bool                mCallbackReturnStop;
    int64_t                    mCallbackCount = 0;
    std::atomic<int32_t>       mFramesPerCallback{0};

    std::atomic<uint32_t>      mCpuAffinityMask{0};
    std::atomic<uint32_t>      mPreviousMask{0};
};

#endif //NATIVEOBOE_OBOESTREAMCALLBACKPROXY_H