aboutsummaryrefslogtreecommitdiff
path: root/android/WALT/app/src/main/java/org/chromium/latency/walt/AudioFragment.java
blob: 3db3723550a3c52cc924a8bb0698094616eaf94f (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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/*
 * Copyright (C) 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 org.chromium.latency.walt;

import static org.chromium.latency.walt.Utils.getIntPreference;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * A simple {@link Fragment} subclass.
 */
public class AudioFragment extends Fragment implements View.OnClickListener,
        BaseTest.TestStateListener {

    enum AudioTestType {
        CONTINUOUS_PLAYBACK,
        CONTINUOUS_RECORDING,
        COLD_PLAYBACK,
        COLD_RECORDING,
        DISPLAY_WAVEFORM
    }

    private SimpleLogger logger;
    private TextView textView;
    private AudioTest audioTest;
    private View startButton;
    private View stopButton;
    private Spinner modeSpinner;
    private LineChart chart;
    private HistogramChart latencyChart;
    private View chartLayout;

    private static final int PERMISSION_REQUEST_RECORD_AUDIO = 1;

    public AudioFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        logger = SimpleLogger.getInstance(getContext());

        audioTest = new AudioTest(getActivity());
        audioTest.setTestStateListener(this);

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_audio, container, false);
        textView = (TextView) view.findViewById(R.id.txt_box_audio);
        textView.setMovementMethod(new ScrollingMovementMethod());
        startButton = view.findViewById(R.id.button_start_audio);
        stopButton = view.findViewById(R.id.button_stop_audio);
        chartLayout = view.findViewById(R.id.chart_layout);
        chart = (LineChart) view.findViewById(R.id.chart);
        latencyChart = (HistogramChart) view.findViewById(R.id.latency_chart);

        view.findViewById(R.id.button_close_chart).setOnClickListener(this);
        enableButtons();

        // Configure the audio mode spinner
        modeSpinner = (Spinner) view.findViewById(R.id.spinner_audio_mode);
        ArrayAdapter<CharSequence> modeAdapter = ArrayAdapter.createFromResource(getContext(),
                R.array.audio_mode_array, android.R.layout.simple_spinner_item);
        modeAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
        modeSpinner.setAdapter(modeAdapter);

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();

        // Register this fragment class as the listener for some button clicks
        startButton.setOnClickListener(this);
        stopButton.setOnClickListener(this);

        textView.setText(logger.getLogText());
        logger.registerReceiver(logReceiver);
    }

    @Override
    public void onPause() {
        logger.unregisterReceiver(logReceiver);
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        audioTest.teardown();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_start_audio:
                chartLayout.setVisibility(View.GONE);
                disableButtons();
                AudioTestType testType = getSelectedTestType();
                switch (testType) {
                    case CONTINUOUS_PLAYBACK:
                    case CONTINUOUS_RECORDING:
                    case DISPLAY_WAVEFORM:
                        audioTest.setAudioMode(AudioTest.AudioMode.CONTINUOUS);
                        audioTest.setPeriod(AudioTest.CONTINUOUS_TEST_PERIOD);
                        break;
                    case COLD_PLAYBACK:
                    case COLD_RECORDING:
                        audioTest.setAudioMode(AudioTest.AudioMode.CONTINUOUS);
                        audioTest.setPeriod(AudioTest.COLD_TEST_PERIOD);
                        break;
                }
                if (testType == AudioTestType.DISPLAY_WAVEFORM) {
                    // Only need to record 1 beep to display wave
                    audioTest.setRecordingRepetitions(1);
                } else {
                    audioTest.setRecordingRepetitions(
                            getIntPreference(getContext(), R.string.preference_audio_in_reps, 5));
                }
                if (testType == AudioTestType.CONTINUOUS_PLAYBACK ||
                        testType == AudioTestType.COLD_PLAYBACK ||
                        testType == AudioTestType.CONTINUOUS_RECORDING ||
                        testType == AudioTestType.COLD_RECORDING) {
                    latencyChart.setVisibility(View.VISIBLE);
                    latencyChart.clearData();
                    latencyChart.setLegendEnabled(false);
                    final String description =
                            getResources().getStringArray(R.array.audio_mode_array)[
                                    modeSpinner.getSelectedItemPosition()] + " [ms]";
                    latencyChart.setDescription(description);
                }
                switch (testType) {
                    case CONTINUOUS_RECORDING:
                    case COLD_RECORDING:
                    case DISPLAY_WAVEFORM:
                        attemptRecordingTest();
                        break;
                    case CONTINUOUS_PLAYBACK:
                    case COLD_PLAYBACK:
                        // Set media volume to max
                        AudioManager am = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
                        am.setStreamVolume(AudioManager.STREAM_MUSIC, am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
                        audioTest.beginPlaybackMeasurement();
                        break;
                }
                break;
            case R.id.button_stop_audio:
                audioTest.stopTest();
                break;
            case R.id.button_close_chart:
                chartLayout.setVisibility(View.GONE);
                break;
        }
    }

    private AudioTestType getSelectedTestType() {
        return AudioTestType.values()[modeSpinner.getSelectedItemPosition()];
    }

    private BroadcastReceiver logReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String msg = intent.getStringExtra("message");
            textView.append(msg + "\n");
        }
    };

    private void attemptRecordingTest() {
        // first see if we already have permission to record audio
        int currentPermission = ContextCompat.checkSelfPermission(this.getContext(),
                Manifest.permission.RECORD_AUDIO);
        if (currentPermission == PackageManager.PERMISSION_GRANTED) {
            disableButtons();
            audioTest.beginRecordingMeasurement();
        } else {
            requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO},
                    PERMISSION_REQUEST_RECORD_AUDIO);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_RECORD_AUDIO:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    disableButtons();
                    audioTest.beginRecordingMeasurement();
                } else {
                    logger.log("Could not get permission to record audio");
                }
                return;
        }
    }

    @Override
    public void onTestStopped() {
        if (getSelectedTestType() == AudioTestType.DISPLAY_WAVEFORM) {
            drawWaveformChart();
        } else {
            if (!audioTest.deltas_mic.isEmpty()) {
                latencyChart.setLegendEnabled(true);
                latencyChart.setLabel(String.format(Locale.US, "Median=%.1f ms", Utils.median(audioTest.deltas_mic)));
            } else if (!audioTest.deltas_queue2wire.isEmpty()) {
                latencyChart.setLegendEnabled(true);
                latencyChart.setLabel(String.format(Locale.US, "Median=%.1f ms", Utils.median(audioTest.deltas_queue2wire)));
            }
        }
        LogUploader.uploadIfAutoEnabled(getContext());
        enableButtons();
    }

    @Override
    public void onTestStoppedWithError() {
        enableButtons();
        latencyChart.setVisibility(View.GONE);
    }

    @Override
    public void onTestPartialResult(double value) {
        latencyChart.addEntry(value);
    }

    private void drawWaveformChart() {
        final short[] wave = AudioTest.getRecordedWave();
        List<Entry> entries = new ArrayList<>();
        int frameRate = audioTest.getOptimalFrameRate();
        for (int i = 0; i < wave.length; i++) {
            float timeStamp = (float) i / frameRate * 1000f;
            entries.add(new Entry(timeStamp, (float) wave[i]));
        }
        LineDataSet dataSet = new LineDataSet(entries, "Waveform");
        dataSet.setColor(Color.BLACK);
        dataSet.setValueTextColor(Color.BLACK);
        dataSet.setCircleColor(ContextCompat.getColor(getContext(), R.color.DarkGreen));
        dataSet.setCircleRadius(1.5f);
        dataSet.setCircleColorHole(Color.DKGRAY);
        LineData lineData = new LineData(dataSet);
        chart.setData(lineData);

        LimitLine line = new LimitLine(audioTest.getThreshold(), "Threshold");
        line.setLineColor(Color.RED);
        line.setLabelPosition(LimitLine.LimitLabelPosition.LEFT_TOP);
        line.setLineWidth(2f);
        line.setTextColor(Color.DKGRAY);
        line.setTextSize(10f);
        chart.getAxisLeft().addLimitLine(line);

        final Description desc = new Description();
        desc.setText("Wave [digital level -32768 to +32767] vs. Time [ms]");
        desc.setTextSize(12f);
        chart.setDescription(desc);
        chart.getLegend().setEnabled(false);
        chart.invalidate();
        chartLayout.setVisibility(View.VISIBLE);
    }

    private void disableButtons() {
        startButton.setEnabled(false);
        stopButton.setEnabled(true);
    }

    private void enableButtons() {
        startButton.setEnabled(true);
        stopButton.setEnabled(false);
    }
}