1# Copyright (c) 2012 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import logging
6
7from autotest_lib.client.bin import test
8from autotest_lib.client.common_lib import error
9from autotest_lib.client.cros.audio import audio_helper
10
11
12_DEFAULT_VOLUME_LEVEL = 100
13_DEFAULT_CAPTURE_GAIN = 2500
14
15_LATENCY_DIFF_LIMIT_US = 3000
16_NOISE_THRESHOLD = 1600
17
18class audio_LoopbackLatency(test.test):
19    """Verifies if the measured latency is as accurate as reported"""
20    version = 1
21
22    def initialize(self,
23                   default_volume_level=_DEFAULT_VOLUME_LEVEL,
24                   default_capture_gain=_DEFAULT_CAPTURE_GAIN):
25        """Setup the deps for the test.
26
27        Args:
28            default_volume_level: The default volume level.
29            defalut_capture_gain: The default capture gain.
30
31        Raises: error.TestError if the deps can't be run
32        """
33        self._volume_level = default_volume_level
34        self._capture_gain = default_capture_gain
35
36        super(audio_LoopbackLatency, self).initialize()
37
38    def run_once(self):
39        """Entry point of this test"""
40        audio_helper.set_volume_levels(self._volume_level, self._capture_gain)
41        success = False
42
43        # Run loopback latency check once, which takes at most 1 sec to
44        # complete and parse the latency values measured in loopback path
45        # and reported by system.  Assert the difference is within
46        # acceptable range.
47        result = audio_helper.loopback_latency_check(n=_NOISE_THRESHOLD)
48        if result:
49            diff = abs(result[0] - result[1])
50            logging.info('Tested latency with threshold %d.\nMeasured %d,'
51                         'reported %d uS, diff %d us\n', _NOISE_THRESHOLD,
52                         result[0], result[1], diff)
53
54            # Difference between measured and reported latency should
55            # within _LATENCY_DIFF_LIMIT_US.
56            if diff < _LATENCY_DIFF_LIMIT_US:
57                success = True
58        else:
59            # Raise error if audio is not detected at all in the loopback path.
60            raise error.TestError('Audio not detected at threshold %d' %
61                                  _NOISE_THRESHOLD)
62
63        if not success:
64            # Test fails when latency difference is greater then the limit.
65            raise error.TestFail('Latency difference too much, diff limit '
66                                 '%d us, measured %d us, reported %d us' %
67                                 (_LATENCY_DIFF_LIMIT_US, result[0], result[1]))
68