aboutsummaryrefslogtreecommitdiff
path: root/apps/OboeTester/app/src/main/java/com/mobileer/oboetester/ManualGlitchActivity.java
blob: 9281cd592c301aa7fff08cd263b570c6c2c1482a (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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
/*
 * Copyright 2019 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 android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;

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

public class ManualGlitchActivity extends GlitchActivity {

    public static final String KEY_BUFFER_BURSTS = "buffer_bursts";
    public static final int VALUE_DEFAULT_BUFFER_BURSTS = 2;

    public static final String KEY_TOLERANCE = "tolerance";
    private static final float DEFAULT_TOLERANCE = 0.10f;

    private static final long MIN_DISPLAY_PERIOD_MILLIS = 500;
    private static final int WAVEFORM_SIZE = 400;

    private TextView mTextTolerance;
    private SeekBar mFaderTolerance;
    protected ExponentialTaper mTaperTolerance;

    private CheckBox mForceGlitchesBox;
    private CheckBox mAutoScopeBox;
    private WaveformView mWaveformView;
    private LinearLayout mLayoutGlitch;


    private NumberedRadioButtons mInputChannelBoxes;
    private NumberedRadioButtons mOutputChannelBoxes;
    private float[] mWaveform = new float[WAVEFORM_SIZE];
    private long mLastDisplayTime;

    private float   mTolerance = DEFAULT_TOLERANCE;

    private SeekBar.OnSeekBarChangeListener mToleranceListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            setToleranceProgress(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    };

    protected void setToleranceProgress(int progress) {
        float tolerance = (float) mTaperTolerance.linearToExponential(
                ((double)progress) / FADER_PROGRESS_MAX);
        setTolerance(tolerance);
        mTextTolerance.setText("Tolerance = " + String.format(Locale.getDefault(), "%5.3f", tolerance));
    }

    static class NumberedRadioButtons {
        LinearLayout mRow;
        RadioButton[] mRadioButtons;

        public interface SelectionListener {
            void onSelected(int index);
        }

        NumberedRadioButtons(Context context, int numBoxes, SelectionListener listener, String prompt) {
            mRow = new LinearLayout(context);
            mRow.setOrientation(LinearLayout.HORIZONTAL);
            TextView textView = new TextView(context);
            textView.setText(prompt);
            mRow.addView(textView);
            RadioGroup rg = new RadioGroup(context);
            rg.setOrientation(LinearLayout.HORIZONTAL);
            mRadioButtons = new RadioButton[numBoxes];
            for (int i = 0; i < numBoxes; i++) {
                mRadioButtons[i] = new RadioButton(context);
                mRadioButtons[i].setText("" + i);
                mRadioButtons[i].setId(i);
                rg.addView(mRadioButtons[i]);
            }
            mRow.addView(rg);

            //set listener to radio button group
            rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    listener.onSelected(checkedId);
                 }
            });

            mRadioButtons[0].setChecked(true);
        }

        public View getView() {
            return mRow;
        }

        public void setMaxEnabled(int max) {
            max = Math.min(max, mRadioButtons.length);
            for (int i = 0; i < mRadioButtons.length; i++) {
                mRadioButtons[i].setEnabled(i < max);
            }
            mRadioButtons[0].setChecked(true);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mTextTolerance = (TextView) findViewById(R.id.textTolerance);
        mFaderTolerance = (SeekBar) findViewById(R.id.faderTolerance);
        mTaperTolerance = new ExponentialTaper(0.0, 0.5, 100.0);
        mFaderTolerance.setOnSeekBarChangeListener(mToleranceListener);
        setToleranceFader(DEFAULT_TOLERANCE);

        mForceGlitchesBox = (CheckBox) findViewById(R.id.boxForceGlitch);
        mAutoScopeBox = (CheckBox) findViewById(R.id.boxAutoScope);
        mWaveformView = (WaveformView) findViewById(R.id.waveview_audio);

        mLayoutGlitch = (LinearLayout) findViewById(R.id.layoutGlitch);
        mInputChannelBoxes = new NumberedRadioButtons(this, 8,
                (int index) -> setInputChannel(index), "IN:");
        mLayoutGlitch.addView(mInputChannelBoxes.getView());
        mOutputChannelBoxes = new NumberedRadioButtons(this, 8,
                (int index) -> setOutputChannel(index), "OUT:");
        mLayoutGlitch.addView(mOutputChannelBoxes.getView());
    }

    private void setToleranceFader(float tolerance) {
        int progress = (int) Math.round((mTaperTolerance.exponentialToLinear(
                tolerance) * FADER_PROGRESS_MAX));
        mFaderTolerance.setProgress(progress);
    }

    @Override
    protected void inflateActivity() {
        setContentView(R.layout.activity_manual_glitches);
    }

    void configureStreamsFromBundle(Bundle bundle) {
        // Configure settings
        StreamConfiguration requestedInConfig = mAudioInputTester.requestedConfiguration;
        StreamConfiguration requestedOutConfig = mAudioOutTester.requestedConfiguration;
        IntentBasedTestSupport.configureStreamsFromBundle(bundle, requestedInConfig, requestedOutConfig);

        // Extract custom parameters from the bundle.
        float tolerance = bundle.getFloat(KEY_TOLERANCE, DEFAULT_TOLERANCE);
        setToleranceFader(tolerance);
        setTolerance(tolerance);
        mTolerance = tolerance;
    }

    @Override
    public void giveAdvice(String s) {
        mWaveformView.post(() -> {
            mWaveformView.setMessage(s);
            mWaveformView.invalidate();
        });
    }

    public void startAudioTest() throws IOException {
        super.startAudioTest();

        setToleranceProgress(mFaderTolerance.getProgress());
        int inChannels = mAudioInputTester.getCurrentAudioStream().getChannelCount();
        mInputChannelBoxes.setMaxEnabled(inChannels);
        int outChannels = mAudioOutTester.getCurrentAudioStream().getChannelCount();
        mOutputChannelBoxes.setMaxEnabled(outChannels);
    }

    @Override
    public void startTestUsingBundle() {
        configureStreamsFromBundle(mBundleFromIntent);

        int durationSeconds = IntentBasedTestSupport.getDurationSeconds(mBundleFromIntent);
        int numBursts = mBundleFromIntent.getInt(KEY_BUFFER_BURSTS, VALUE_DEFAULT_BUFFER_BURSTS);

        try {
            openStartAudioTestUI();
            int sizeFrames = mAudioOutTester.getCurrentAudioStream().getFramesPerBurst() * numBursts;
            mAudioOutTester.getCurrentAudioStream().setBufferSizeInFrames(sizeFrames);

            // Schedule the end of the test.
            Handler handler = new Handler(Looper.getMainLooper()); // UI thread
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stopAutomaticTest();
                }
            }, durationSeconds * 1000);
        } catch (IOException e) {
            String report = "Open failed: " + e.getMessage();
            maybeWriteTestResult(report);
            mTestRunningByIntent = false;
        } finally {
            mBundleFromIntent = null;
        }

    }

    void stopAutomaticTest() {
        String report = getCommonTestReport()
                + String.format(Locale.getDefault(), "tolerance = %5.3f\n", mTolerance)
                + mLastGlitchReport;
        onStopAudioTest(null);
        maybeWriteTestResult(report);
        mTestRunningByIntent = false;
    }

    // Only call from UI thread.
    @Override
    public void onTestBegan() {
        mAutoScopeBox.setChecked(true);
        mWaveformView.clearSampleData();
        mWaveformView.postInvalidate();
        super.onTestBegan();
    }

    // Called on UI thread
    @Override
    protected void onGlitchDetected() {
        if (mAutoScopeBox.isChecked()) {
            mAutoScopeBox.setChecked(false); // stop auto drawing of waveform
            mLastDisplayTime = 0; // force draw first glitch
        }
        long now = System.currentTimeMillis();
        Log.i(TAG,"onGlitchDetected: glitch");
        if ((now - mLastDisplayTime) > MIN_DISPLAY_PERIOD_MILLIS) {
            mLastDisplayTime = now;
            int numSamples = getGlitch(mWaveform);
            mWaveformView.setSampleData(mWaveform, 0, numSamples);
            int glitchLength = getGlitchLength();
            int[] cursors = new int[glitchLength > 0 ? 2 : 1];
            int startOfGlitch = getSinePeriod();
            cursors[0] = startOfGlitch;
            if (glitchLength > 0) {
                cursors[1] = startOfGlitch + getGlitchLength();
            }
            mWaveformView.setCursorData(cursors);
            Log.i(TAG,"onGlitchDetected: glitch, numSamples = " + numSamples);
            mWaveformView.postInvalidate();
        }
    }
    @Override
    protected void maybeDisplayWaveform() {
        if (!mAutoScopeBox.isChecked()) return;
        long now = System.currentTimeMillis();
        if ((now - mLastDisplayTime) > MIN_DISPLAY_PERIOD_MILLIS) {
            mLastDisplayTime = now;
            int numSamples = getRecentSamples(mWaveform);
            mWaveformView.setSampleData(mWaveform, 0, numSamples);
            mWaveformView.setCursorData(null);
            mWaveformView.postInvalidate();
        }
    }

    private native int getGlitch(float[] mWaveform);
    private native int getRecentSamples(float[] mWaveform);

    public void onForceGlitchClicked(View view) {
        setForcedGlitchDuration(mForceGlitchesBox.isChecked() ? 100 : 0);
    }
}