1#!/usr/bin/env python
2#
3# Copyright (C) 2017 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#      http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17
18import logging
19import math
20import os
21
22from time import sleep
23from vts.runners.host import asserts
24from vts.runners.host import base_test
25from vts.runners.host import const
26from vts.runners.host import test_runner
27from vts.utils.python.controllers import android_device
28
29
30class AudioLoopbackTest(base_test.BaseTestClass):
31    """A test module for the Audio Loopback Benchmark."""
32
33    # Threshold for average latency and standard deviation.
34    THRESHOLD = {"MAX_LATENCY": 20000000, }
35
36    TEST_DATA_DIR = "audiotest"
37    FULL_DATA_DIR_PATH = os.path.join("/mnt/sdcard/", TEST_DATA_DIR)
38    TEST_FILE_PREFIX = "out"
39    TEST_FILE_NAME = os.path.join(FULL_DATA_DIR_PATH,
40                                  TEST_FILE_PREFIX + ".txt")
41    ITERATION = 100
42
43    def setUpClass(self):
44        self.dut = self.android_devices[0]
45        self.dut.adb.shell("mkdir -p %s" % self.FULL_DATA_DIR_PATH)
46        # install Loopback.apk
47        self.dut.adb.shell("pm install -r -g /data/local/tmp/Loopback.apk")
48
49    def tearDown(self):
50        self.dut.adb.shell("rm -rf %s" % self.FULL_DATA_DIR_PATH)
51
52    def ProcessTestResults(self, latencies, confidences):
53        """Process test results and upload to web dashboard.
54
55        Calculate the average and standard deviation of latencies from all test run.
56        Only test results with confidence = 1.0 are counted.
57
58        Args:
59           latencies: List of latency (in ns) get from each run. e.g.[8040000]
60           confidences: List of confidence get from each run. e.g. [0.98, 1.0]
61        """
62        total_latency = 0
63        total_run = 0
64        for latency, confidence in zip(latencies, confidences):
65            # filter test runs with confidence < 1.0
66            if confidence < 1.0:
67                latencies.remove(latency)
68            else:
69                total_latency += latency
70                total_run += 1
71        asserts.assertLess(0, total_run, "No valid runs.")
72        self.web.AddProfilingDataUnlabeledVector(
73            "AVG_LATENCY",
74            latencies,
75            x_axis_label="AVG Roundtrip latency (ns)",
76            y_axis_label="Frequency")
77        # calculate the average latency.
78        avg_latency = total_latency / total_run
79        logging.info("avg_latency: %s", avg_latency)
80        asserts.assertLess(avg_latency, self.THRESHOLD["MAX_LATENCY"],
81                           "avg latency exceeds threshold")
82        # calculate the standard deviation of latencies.
83        sd = 0.0
84        for latency in latencies:
85            sd += (latency - avg_latency) * (latency - avg_latency)
86        sd = int(math.sqrt(sd / total_run))
87        logging.info("standard_deviation: %s", sd)
88        self.web.AddProfilingDataUnlabeledVector(
89            "STANDARD_DEVIATION", [sd],
90            x_axis_label="Standard deviation",
91            y_axis_label="Frequency")
92
93    def testRun(self):
94        """Runs test in audio Loopback.apk and process the test results."""
95        latencies = []
96        confidences = []
97        for i in range(0, self.ITERATION):
98            self.dut.shell.Execute(
99                ["rm -f %s/*" % self.FULL_DATA_DIR_PATH])
100            self.dut.shell.Execute([
101                "am start -n org.drrickorang.loopback/.LoopbackActivity "
102                "--es FileName %s/%s --ei AudioLevel 11 --ei TestType 222;" %
103                (self.TEST_DATA_DIR, self.TEST_FILE_PREFIX)
104            ])
105            # wait until the test finished.
106            results = self.dut.shell.Execute(
107                ["ls %s" % self.TEST_FILE_NAME])
108            while results[const.EXIT_CODE][0]:
109                logging.info("Test is running...")
110                sleep(1)
111                results = self.dut.shell.Execute(
112                    ["ls %s" % self.TEST_FILE_NAME])
113
114            results = self.dut.shell.Execute(
115                ["cat %s" % self.TEST_FILE_NAME])
116            asserts.assertFalse(results[const.EXIT_CODE][0],
117                                "Fail to get the test output")
118            stdout_lines = results[const.STDOUT][0].split("\n")
119            for line in stdout_lines:
120                if line.startswith("LatencyMs"):
121                    latencies.append(
122                        int(
123                            float(line.replace("LatencyMs = ", "")) * 1000000))
124                if line.startswith("LatencyConfidence"):
125                    confidences.append(
126                        float(line.replace("LatencyConfidence = ", "")))
127        self.ProcessTestResults(latencies, confidences)
128
129
130if __name__ == "__main__":
131    test_runner.main()
132