aboutsummaryrefslogtreecommitdiff
path: root/src/com/android/media/tests/AudioLoopbackTest.java
blob: 1d9bab5a862a41f7b3e7ac78541922596c043167 (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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
/*
 * Copyright (C) 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.
 */
package com.android.media.tests;

import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;

import com.android.ddmlib.NullOutputReceiver;
import com.android.ddmlib.testrunner.TestIdentifier;
import com.android.media.tests.AudioLoopbackTestHelper.LogFileType;
import com.android.media.tests.AudioLoopbackTestHelper.ResultData;
import com.android.tradefed.config.Option;
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.log.LogUtil.CLog;
import com.android.tradefed.result.FileInputStreamSource;
import com.android.tradefed.result.ITestInvocationListener;
import com.android.tradefed.result.InputStreamSource;
import com.android.tradefed.result.LogDataType;
import com.android.tradefed.testtype.IDeviceTest;
import com.android.tradefed.testtype.IRemoteTest;
import com.android.tradefed.util.FileUtil;
import com.android.tradefed.util.RunUtil;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Runs Audio Latency and Audio Glitch test and reports result.
 *
 * <p>Strategy for Audio Latency Stress test: RUN test 1000 times. In each iteration, collect result
 * files from device, parse and collect data in a ResultData object that also keeps track of
 * location to test files for a particular iteration.
 *
 * <p>ANALYZE test results to produce statistics for 1. Latency and Confidence (Min, Max, Mean,
 * Median) 2. Create CSV file with test run data 3. Print bad test data to host log file 4. Get
 * number of test runs with valid data to send to dashboard 5. Produce histogram in host log file;
 * count number of test results that fall into 1 ms wide buckets.
 *
 * <p>UPLOAD test results + log files from “bad” runs; i.e. runs that is missing some or all result
 * data.
 */
public class AudioLoopbackTest implements IDeviceTest, IRemoteTest {

    //===================================================================
    // TEST OPTIONS
    //===================================================================
    @Option(name = "run-key", description = "Run key for the test")
    private String mRunKey = "AudioLoopback";

    @Option(name = "sampling-freq", description = "Sampling Frequency for Loopback app")
    private String mSamplingFreq = "48000";

    @Option(name = "mic-source", description = "Mic Source for Loopback app")
    private String mMicSource = "3";

    @Option(name = "audio-thread", description = "Audio Thread for Loopback app")
    private String mAudioThread = "1";

    @Option(
        name = "audio-level",
        description =
                "Audio Level for Loopback app. A device specific"
                        + "param which makes waveform in loopback test hit 60% to 80% range"
    )
    private String mAudioLevel = "-1";

    @Option(name = "test-type", description = "Test type to be executed")
    private String mTestType = TESTTYPE_LATENCY_STR;

    @Option(name = "buffer-test-duration", description = "Buffer test duration in seconds")
    private String mBufferTestDuration = "10";

    @Option(name = "key-prefix", description = "Key Prefix for reporting")
    private String mKeyPrefix = "48000_Mic3_";

    @Option(name = "iterations", description = "Number of test iterations")
    private int mIterations = 1;

    @Option(name = "baseline_latency", description = "")
    private float mBaselineLatency = 0f;

    //===================================================================
    // CLASS VARIABLES
    //===================================================================
    private static final Map<String, String> METRICS_KEY_MAP = createMetricsKeyMap();
    private Map<LogFileType, LogFileData> mFileDataKeyMap;
    private ITestDevice mDevice;
    private TestRunHelper mTestRunHelper;
    private AudioLoopbackTestHelper mLoopbackTestHelper;

    //===================================================================
    // CONSTANTS
    //===================================================================
    private static final String TESTTYPE_LATENCY_STR = "222";
    private static final String TESTTYPE_GLITCH_STR = "223";
    private static final long TIMEOUT_MS = 5 * 60 * 1000; // 5 min
    private static final long DEVICE_SYNC_MS = 5 * 60 * 1000; // 5 min
    private static final long POLLING_INTERVAL_MS = 5 * 1000;
    private static final int MAX_ATTEMPTS = 3;
    private static final int MAX_NR_OF_LOG_UPLOADS = 100;

    private static final int LATENCY_ITERATIONS_LOWER_BOUND = 1;
    private static final int LATENCY_ITERATIONS_UPPER_BOUND = 10000;
    private static final int GLITCH_ITERATIONS_LOWER_BOUND = 1;
    private static final int GLITCH_ITERATIONS_UPPER_BOUND = 1;

    private static final String DEVICE_TEMP_DIR_PATH = "/sdcard/";
    private static final String FMT_OUTPUT_PREFIX = "output_%1$d_" + System.currentTimeMillis();
    private static final String FMT_DEVICE_FILENAME = FMT_OUTPUT_PREFIX + "%2$s";
    private static final String FMT_DEVICE_PATH = DEVICE_TEMP_DIR_PATH + FMT_DEVICE_FILENAME;

    private static final String AM_CMD =
            "am start -n org.drrickorang.loopback/.LoopbackActivity"
                    + " --ei SF %s --es FileName %s --ei MicSource %s --ei AudioThread %s"
                    + " --ei AudioLevel %s --ei TestType %s --ei BufferTestDuration %s";

    private static final String ERR_PARAMETER_OUT_OF_BOUNDS =
            "Test parameter '%1$s' is out of bounds. Lower limit = %2$d, upper limit = %3$d";

    private static final String KEY_RESULT_LATENCY_MS = "latency_ms";
    private static final String KEY_RESULT_LATENCY_CONFIDENCE = "latency_confidence";
    private static final String KEY_RESULT_RECORDER_BENCHMARK = "recorder_benchmark";
    private static final String KEY_RESULT_RECORDER_OUTLIER = "recorder_outliers";
    private static final String KEY_RESULT_PLAYER_BENCHMARK = "player_benchmark";
    private static final String KEY_RESULT_PLAYER_OUTLIER = "player_outliers";
    private static final String KEY_RESULT_NUMBER_OF_GLITCHES = "number_of_glitches";
    private static final String KEY_RESULT_RECORDER_BUFFER_CALLBACK = "late_recorder_callbacks";
    private static final String KEY_RESULT_PLAYER_BUFFER_CALLBACK = "late_player_callbacks";
    private static final String KEY_RESULT_GLITCHES_PER_HOUR = "glitches_per_hour";
    private static final String KEY_RESULT_TEST_STATUS = "test_status";
    private static final String KEY_RESULT_AUDIO_LEVEL = "audio_level";
    private static final String KEY_RESULT_RMS = "rms";
    private static final String KEY_RESULT_RMS_AVERAGE = "rms_average";
    private static final String KEY_RESULT_SAMPLING_FREQUENCY_CONFIDENCE = "sampling_frequency";
    private static final String KEY_RESULT_PERIOD_CONFIDENCE = "period_confidence";
    private static final String KEY_RESULT_SAMPLING_BLOCK_SIZE = "block_size";

    private static final LogFileType[] LATENCY_TEST_LOGS = {
        LogFileType.RESULT,
        LogFileType.GRAPH,
        LogFileType.WAVE,
        LogFileType.PLAYER_BUFFER,
        LogFileType.PLAYER_BUFFER_HISTOGRAM,
        LogFileType.PLAYER_BUFFER_PERIOD_TIMES,
        LogFileType.RECORDER_BUFFER,
        LogFileType.RECORDER_BUFFER_HISTOGRAM,
        LogFileType.RECORDER_BUFFER_PERIOD_TIMES,
        LogFileType.LOGCAT
    };

    private static final LogFileType[] GLITCH_TEST_LOGS = {
        LogFileType.RESULT,
        LogFileType.GRAPH,
        LogFileType.WAVE,
        LogFileType.PLAYER_BUFFER,
        LogFileType.PLAYER_BUFFER_HISTOGRAM,
        LogFileType.PLAYER_BUFFER_PERIOD_TIMES,
        LogFileType.RECORDER_BUFFER,
        LogFileType.RECORDER_BUFFER_HISTOGRAM,
        LogFileType.RECORDER_BUFFER_PERIOD_TIMES,
        LogFileType.GLITCHES_MILLIS,
        LogFileType.HEAT_MAP,
        LogFileType.LOGCAT
    };

    /**
     * The Audio Latency and Audio Glitch test deals with many various types of log files. To be
     * able to generate log files in a generic manner, this map is provided to get access to log
     * file properties like log name prefix, log name file extension and log type (leveraging
     * tradefed class LogDataType, used when uploading log).
     */
    private final synchronized Map<LogFileType, LogFileData> getLogFileDataKeyMap() {
        if (mFileDataKeyMap != null) {
            return mFileDataKeyMap;
        }

        final Map<LogFileType, LogFileData> result = new HashMap<LogFileType, LogFileData>();

        // Populate dictionary with info about various types of logfiles
        LogFileData l = new LogFileData(".txt", "result", LogDataType.TEXT);
        result.put(LogFileType.RESULT, l);

        l = new LogFileData(".png", "graph", LogDataType.PNG);
        result.put(LogFileType.GRAPH, l);

        l = new LogFileData(".wav", "wave", LogDataType.UNKNOWN);
        result.put(LogFileType.WAVE, l);

        l = new LogFileData("_playerBufferPeriod.txt", "player_buffer", LogDataType.TEXT);
        result.put(LogFileType.PLAYER_BUFFER, l);

        l = new LogFileData("_playerBufferPeriod.png", "player_buffer_histogram", LogDataType.PNG);
        result.put(LogFileType.PLAYER_BUFFER_HISTOGRAM, l);

        String fileExtension = "_playerBufferPeriodTimes.txt";
        String uploadName = "player_buffer_period_times";
        l = new LogFileData(fileExtension, uploadName, LogDataType.TEXT);
        result.put(LogFileType.PLAYER_BUFFER_PERIOD_TIMES, l);

        l = new LogFileData("_recorderBufferPeriod.txt", "recorder_buffer", LogDataType.TEXT);
        result.put(LogFileType.RECORDER_BUFFER, l);

        fileExtension = "_recorderBufferPeriod.png";
        uploadName = "recorder_buffer_histogram";
        l = new LogFileData(fileExtension, uploadName, LogDataType.PNG);
        result.put(LogFileType.RECORDER_BUFFER_HISTOGRAM, l);

        fileExtension = "_recorderBufferPeriodTimes.txt";
        uploadName = "recorder_buffer_period_times";
        l = new LogFileData(fileExtension, uploadName, LogDataType.TEXT);
        result.put(LogFileType.RECORDER_BUFFER_PERIOD_TIMES, l);

        l = new LogFileData("_glitchMillis.txt", "glitches_millis", LogDataType.TEXT);
        result.put(LogFileType.GLITCHES_MILLIS, l);


        l = new LogFileData("_heatMap.png", "heat_map", LogDataType.PNG);
        result.put(LogFileType.HEAT_MAP, l);

        l = new LogFileData(".txt", "logcat", LogDataType.TEXT);
        result.put(LogFileType.LOGCAT, l);

        mFileDataKeyMap = Collections.unmodifiableMap(result);
        return mFileDataKeyMap;
    }

    private static final Map<String, String> createMetricsKeyMap() {
        final Map<String, String> result = new HashMap<String, String>();

        result.put("LatencyMs", KEY_RESULT_LATENCY_MS);
        result.put("LatencyConfidence", KEY_RESULT_LATENCY_CONFIDENCE);
        result.put("SF", KEY_RESULT_SAMPLING_FREQUENCY_CONFIDENCE);
        result.put("Recorder Benchmark", KEY_RESULT_RECORDER_BENCHMARK);
        result.put("Recorder Number of Outliers", KEY_RESULT_RECORDER_OUTLIER);
        result.put("Player Benchmark", KEY_RESULT_PLAYER_BENCHMARK);
        result.put("Player Number of Outliers", KEY_RESULT_PLAYER_OUTLIER);
        result.put("Total Number of Glitches", KEY_RESULT_NUMBER_OF_GLITCHES);
        result.put("kth% Late Recorder Buffer Callbacks", KEY_RESULT_RECORDER_BUFFER_CALLBACK);
        result.put("kth% Late Player Buffer Callbacks", KEY_RESULT_PLAYER_BUFFER_CALLBACK);
        result.put("Glitches Per Hour", KEY_RESULT_GLITCHES_PER_HOUR);
        result.put("Test Status", KEY_RESULT_TEST_STATUS);
        result.put("AudioLevel", KEY_RESULT_AUDIO_LEVEL);
        result.put("RMS", KEY_RESULT_RMS);
        result.put("Average", KEY_RESULT_RMS_AVERAGE);
        result.put("PeriodConfidence", KEY_RESULT_PERIOD_CONFIDENCE);
        result.put("BS", KEY_RESULT_SAMPLING_BLOCK_SIZE);

        return Collections.unmodifiableMap(result);
    }

    //===================================================================
    // ENUMS
    //===================================================================
    public enum TestType {
        GLITCH,
        LATENCY,
        LATENCY_STRESS,
        NONE
    }

    //===================================================================
    // INNER CLASSES
    //===================================================================
    public final class LogFileData {
        private String fileExtension;
        private String filePrefix;
        private LogDataType logDataType;

        private LogFileData(String fileExtension, String filePrefix, LogDataType logDataType) {
            this.fileExtension = fileExtension;
            this.filePrefix = filePrefix;
            this.logDataType = logDataType;
        }
    }

    //===================================================================
    // FUNCTIONS
    //===================================================================

    /** {@inheritDoc} */
    @Override
    public void setDevice(ITestDevice device) {
        mDevice = device;
    }

    /** {@inheritDoc} */
    @Override
    public ITestDevice getDevice() {
        return mDevice;
    }

    /**
     * Test Entry Point
     *
     * <p>{@inheritDoc}
     */
    @Override
    public void run(ITestInvocationListener listener) throws DeviceNotAvailableException {

        initializeTest(listener);

        mTestRunHelper.startTest(1);

        try {
            if (!verifyTestParameters()) {
                return;
            }

            // Stop logcat logging so we can record one logcat log per iteration
            getDevice().stopLogcat();

            // Run test iterations
            for (int i = 0; i < mIterations; i++) {
                CLog.i("---- Iteration " + i + " of " + (mIterations - 1) + " -----");

                final ResultData d = new ResultData();
                d.setIteration(i);
                Map<String, String> resultsDictionary = null;
                resultsDictionary = runTest(d, getSingleTestTimeoutValue());

                mLoopbackTestHelper.addTestData(d, resultsDictionary);
            }

            mLoopbackTestHelper.processTestData();
        } finally {
            Map<String, String> metrics = uploadLogsReturnMetrics(listener);
            CLog.i("Uploading metrics values:\n" + Arrays.toString(metrics.entrySet().toArray()));
            mTestRunHelper.endTest(metrics);
            deleteAllTempFiles();
            getDevice().startLogcat();
        }
    }

    private void initializeTest(ITestInvocationListener listener)
            throws UnsupportedOperationException, DeviceNotAvailableException {

        mFileDataKeyMap = getLogFileDataKeyMap();
        TestIdentifier testId = new TestIdentifier(getClass().getCanonicalName(), mRunKey);

        // Allocate helpers
        mTestRunHelper = new TestRunHelper(listener, testId);
        mLoopbackTestHelper = new AudioLoopbackTestHelper(mIterations);

        getDevice().disableKeyguard();
        getDevice().waitForDeviceAvailable(DEVICE_SYNC_MS);

        getDevice().setDate(new Date());
        CLog.i("syncing device time to host time");
    }

    private Map<String, String> runTest(ResultData data, final long timeout)
            throws DeviceNotAvailableException {

        // start measurement and wait for result file
        final NullOutputReceiver receiver = new NullOutputReceiver();

        final String loopbackCmd = getTestCommand(data.getIteration());
        CLog.i("Loopback cmd: " + loopbackCmd);

        // Clear logcat
        // Seems like getDevice().clearLogcat(); doesn't do anything?
        // Do it through ADB
        getDevice().executeAdbCommand("logcat", "-c");
        final long deviceTestStartTime = getDevice().getDeviceDate();

        getDevice()
                .executeShellCommand(
                        loopbackCmd, receiver, TIMEOUT_MS, TimeUnit.MILLISECONDS, MAX_ATTEMPTS);

        final long loopbackStartTime = System.currentTimeMillis();
        File loopbackReport = null;

        data.setDeviceTestStartTime(deviceTestStartTime);

        // Try to retrieve result file from device.
        final String resultFilename = getDeviceFilename(LogFileType.RESULT, data.getIteration());
        do {
            RunUtil.getDefault().sleep(POLLING_INTERVAL_MS);
            if (getDevice().doesFileExist(resultFilename)) {
                // Store device log files in tmp directory on Host and add to ResultData object
                storeDeviceFilesOnHost(data);
                final String reportFilename = data.getLogFile(LogFileType.RESULT);
                if (reportFilename != null && !reportFilename.isEmpty()) {
                    loopbackReport = new File(reportFilename);
                    if (loopbackReport.length() > 0) {
                        break;
                    }
                }
            }

            data.setIsTimedOut(System.currentTimeMillis() - loopbackStartTime >= timeout);
        } while (!data.hasLogFile(LogFileType.RESULT) && !data.isTimedOut());

        // Grab logcat for iteration
        final InputStreamSource lc = getDevice().getLogcatSince(deviceTestStartTime);
        saveLogcatForIteration(data, lc, data.getIteration());

        // Check if test timed out. If so, don't fail the test, but return to upper logic.
        // We accept certain number of individual test timeouts.
        if (data.isTimedOut()) {
            // No device result files retrieved, so no need to parse
            return null;
        }

        // parse result
        Map<String, String> loopbackResult = null;

        try {
            loopbackResult =
                    AudioLoopbackTestHelper.parseKeyValuePairFromFile(
                            loopbackReport, METRICS_KEY_MAP, mKeyPrefix, "=", "%s: %s");
            populateResultData(loopbackResult, data);

            // Trust but verify, so get Audio Level from ADB and compare to value from app
            final int adbAudioLevel =
                    AudioLevelUtility.extractDeviceAudioLevelFromAdbShell(getDevice());
            if (data.getAudioLevel() != adbAudioLevel) {
                final String errMsg =
                        String.format(
                                "App Audio Level (%1$d)differs from ADB level (%2$d)",
                                data.getAudioLevel(), adbAudioLevel);
                mTestRunHelper.reportFailure(errMsg);
            }
        } catch (final IOException ioe) {
            CLog.e(ioe);
            mTestRunHelper.reportFailure("I/O error while parsing Loopback result.");
        } catch (final NumberFormatException ne) {
            CLog.e(ne);
            mTestRunHelper.reportFailure("Number format error parsing Loopback result.");
        }

        return loopbackResult;
    }

    private String getMetricsKey(final String key) {
        return mKeyPrefix + key;
    }
    private final long getSingleTestTimeoutValue() {
        return Long.parseLong(mBufferTestDuration) * 1000 + TIMEOUT_MS;
    }

    private Map<String, String> uploadLogsReturnMetrics(ITestInvocationListener listener)
            throws DeviceNotAvailableException {

        // "resultDictionary" is used to post results to dashboards like BlackBox
        // "results" contains test logs to be uploaded; i.e. to Sponge

        List<ResultData> results = null;
        Map<String, String> resultDictionary = new HashMap<String, String>();

        switch (getTestType()) {
            case GLITCH:
                resultDictionary = mLoopbackTestHelper.getResultDictionaryForIteration(0);
                // Upload all test files to be backward compatible with old test
                results = mLoopbackTestHelper.getAllTestData();
                break;
            case LATENCY:
                {
                    final int nrOfValidResults = mLoopbackTestHelper.processTestData();
                    if (nrOfValidResults == 0) {
                        mTestRunHelper.reportFailure("No good data was collected");
                    } else {
                        // use dictionary collected from single test run
                        resultDictionary = mLoopbackTestHelper.getResultDictionaryForIteration(0);
                    }

                    // Upload all test files to be backward compatible with old test
                    results = mLoopbackTestHelper.getAllTestData();
                }
                break;
            case LATENCY_STRESS:
                {
                    final int nrOfValidResults = mLoopbackTestHelper.processTestData();
                    if (nrOfValidResults == 0) {
                        mTestRunHelper.reportFailure("No good data was collected");
                    } else {
                        mLoopbackTestHelper.populateStressTestMetrics(resultDictionary, mKeyPrefix);
                    }

                    results = mLoopbackTestHelper.getWorstResults(MAX_NR_OF_LOG_UPLOADS);

                    // Save all test data in a spreadsheet style csv file for post test analysis
                    try {
                        saveResultsAsCSVFile(listener);
                    } catch (final IOException e) {
                        CLog.e(e);
                    }
                }
                break;
            default:
                break;
        }

        // Upload relevant logs
        for (final ResultData d : results) {
            final LogFileType[] logFileTypes = getLogFileTypesForCurrentTest();
            for (final LogFileType logType : logFileTypes) {
                uploadLog(listener, logType, d);
            }
        }

        return resultDictionary;
    }

    private TestType getTestType() {
        if (mTestType.equals(TESTTYPE_GLITCH_STR)) {
            if (GLITCH_ITERATIONS_LOWER_BOUND <= mIterations
                    && mIterations <= GLITCH_ITERATIONS_UPPER_BOUND) {
                return TestType.GLITCH;
            }
        }

        if (mTestType.equals(TESTTYPE_LATENCY_STR)) {
            if (mIterations == 1) {
                return TestType.LATENCY;
            }

            if (LATENCY_ITERATIONS_LOWER_BOUND <= mIterations
                    && mIterations <= LATENCY_ITERATIONS_UPPER_BOUND) {
                return TestType.LATENCY_STRESS;
            }
        }

        return TestType.NONE;
    }

    private boolean verifyTestParameters() {
        if (getTestType() != TestType.NONE) {
            return true;
        }

        if (mTestType.equals(TESTTYPE_GLITCH_STR)
                && (mIterations < GLITCH_ITERATIONS_LOWER_BOUND
                        || mIterations > GLITCH_ITERATIONS_UPPER_BOUND)) {
            final String error =
                    String.format(
                            ERR_PARAMETER_OUT_OF_BOUNDS,
                            "iterations",
                            GLITCH_ITERATIONS_LOWER_BOUND,
                            GLITCH_ITERATIONS_UPPER_BOUND);
            mTestRunHelper.reportFailure(error);
            return false;
        }

        if (mTestType.equals(TESTTYPE_LATENCY_STR)
                && (mIterations < LATENCY_ITERATIONS_LOWER_BOUND
                        || mIterations > LATENCY_ITERATIONS_UPPER_BOUND)) {
            final String error =
                    String.format(
                            ERR_PARAMETER_OUT_OF_BOUNDS,
                            "iterations",
                            LATENCY_ITERATIONS_LOWER_BOUND,
                            LATENCY_ITERATIONS_UPPER_BOUND);
            mTestRunHelper.reportFailure(error);
            return false;
        }

        return true;
    }

    private void populateResultData(final Map<String, String> results, ResultData data) {
        if (results == null || results.isEmpty()) {
            return;
        }

        String key = getMetricsKey(KEY_RESULT_LATENCY_MS);
        if (results.containsKey(key)) {
            data.setLatency(Float.parseFloat(results.get(key)));
        }

        key = getMetricsKey(KEY_RESULT_LATENCY_CONFIDENCE);
        if (results.containsKey(key)) {
            data.setConfidence(Float.parseFloat(results.get(key)));
        }

        key = getMetricsKey(KEY_RESULT_AUDIO_LEVEL);
        if (results.containsKey(key)) {
            data.setAudioLevel(Integer.parseInt(results.get(key)));
        }

        key = getMetricsKey(KEY_RESULT_RMS);
        if (results.containsKey(key)) {
            data.setRMS(Float.parseFloat(results.get(key)));
        }

        key = getMetricsKey(KEY_RESULT_RMS_AVERAGE);
        if (results.containsKey(key)) {
            data.setRMSAverage(Float.parseFloat(results.get(key)));
        }

        key = getMetricsKey(KEY_RESULT_PERIOD_CONFIDENCE);
        if (results.containsKey(key)) {
            data.setPeriodConfidence(Float.parseFloat(results.get(key)));
        }

        key = getMetricsKey(KEY_RESULT_SAMPLING_BLOCK_SIZE);
        if (results.containsKey(key)) {
            data.setBlockSize(Integer.parseInt(results.get(key)));
        }
    }

    private void storeDeviceFilesOnHost(ResultData data) throws DeviceNotAvailableException {
        final int iteration = data.getIteration();
        for (final LogFileType log : getLogFileTypesForCurrentTest()) {
            if (getDevice().doesFileExist(getDeviceFilename(log, iteration))) {
                final String deviceFileName = getDeviceFilename(log, iteration);
                final File logFile = getDevice().pullFile(deviceFileName);
                data.setLogFile(log, logFile.getAbsolutePath());
                CLog.i("Delete file from device: " + deviceFileName);
                deleteFileFromDevice(deviceFileName);
            }
        }
    }

    private void deleteAllTempFiles() {
        for (final ResultData d : mLoopbackTestHelper.getAllTestData()) {
            final LogFileType[] logFileTypes = getLogFileTypesForCurrentTest();
            for (final LogFileType logType : logFileTypes) {
                final String logFilename = d.getLogFile(logType);
                if (logFilename == null || logFilename.isEmpty()) {
                    CLog.e("Logfile not found for LogFileType=" + logType.name());
                } else {
                    FileUtil.deleteFile(new File(logFilename));
                }
            }
        }
    }

    private void deleteFileFromDevice(String deviceFileName) throws DeviceNotAvailableException {
        getDevice().executeShellCommand("rm -f " + deviceFileName);
    }

    private final LogFileType[] getLogFileTypesForCurrentTest() {
        switch (getTestType()) {
            case GLITCH:
                return GLITCH_TEST_LOGS;
            case LATENCY:
            case LATENCY_STRESS:
                return LATENCY_TEST_LOGS;
            default:
                return null;
        }
    }

    private String getKeyPrefixForIteration(int iteration) {
        if (mIterations == 1) {
            // If only one run, skip the iteration number
            return mKeyPrefix;
        }
        return mKeyPrefix + iteration + "_";
    }

    private String getDeviceFilename(LogFileType key, int iteration) {
        final Map<LogFileType, LogFileData> map = getLogFileDataKeyMap();
        if (map.containsKey(key)) {
            final LogFileData data = map.get(key);
            return String.format(FMT_DEVICE_PATH, iteration, data.fileExtension);
        }
        return null;
    }

    private void uploadLog(ITestInvocationListener listener, LogFileType key, ResultData data) {
        final Map<LogFileType, LogFileData> map = getLogFileDataKeyMap();
        if (!map.containsKey(key)) {
            return;
        }

        final LogFileData logInfo = map.get(key);
        final String prefix = getKeyPrefixForIteration(data.getIteration()) + logInfo.filePrefix;
        final LogDataType logDataType = logInfo.logDataType;
        final String logFilename = data.getLogFile(key);
        if (logFilename == null || logFilename.isEmpty()) {
            CLog.e("Logfile not found for LogFileType=" + key.name());
        } else {
            File logFile = new File(logFilename);
            InputStreamSource iss = new FileInputStreamSource(logFile);
            listener.testLog(prefix, logDataType, iss);

            // cleanup
            iss.cancel();
        }
    }

    private void saveLogcatForIteration(ResultData data, InputStreamSource logcat, int iteration) {
        if (logcat == null) {
            CLog.i("Logcat could not be saved for iteration " + iteration);
            return;
        }

        //create a temp file
        File temp;
        try {
            temp = FileUtil.createTempFile("logcat_" + iteration + "_", ".txt");
            data.setLogFile(LogFileType.LOGCAT, temp.getAbsolutePath());

            // Copy logcat data into temp file
            Files.copy(logcat.createInputStream(), temp.toPath(), REPLACE_EXISTING);
            logcat.cancel();
        } catch (final IOException e) {
            CLog.i("Error when saving logcat for iteration=" + iteration);
            CLog.e(e);
        }
    }

    private void saveResultsAsCSVFile(ITestInvocationListener listener)
            throws DeviceNotAvailableException, IOException {
        final File csvTmpFile = File.createTempFile("audio_test_data", "csv");
        mLoopbackTestHelper.writeAllResultsToCSVFile(csvTmpFile, getDevice());
        InputStreamSource iss = new FileInputStreamSource(csvTmpFile);
        listener.testLog("audio_test_data", LogDataType.JACOCO_CSV, iss);

        // cleanup
        iss.cancel();
        csvTmpFile.delete();
    }

    private String getTestCommand(int currentIteration) {
        return String.format(
                AM_CMD,
                mSamplingFreq,
                String.format(FMT_OUTPUT_PREFIX, currentIteration),
                mMicSource,
                mAudioThread,
                mAudioLevel,
                mTestType,
                mBufferTestDuration);
    }
}