1# Copyright (c) 2011 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 os
6
7from autotest_lib.client.bin import utils
8from autotest_lib.client.common_lib import error
9from autotest_lib.client.cros.audio import audio_helper
10from autotest_lib.client.cros.audio import audio_test_data
11from autotest_lib.client.cros.audio import cmd_utils
12from autotest_lib.client.cros.audio import cras_utils
13
14
15TEST_DURATION = 1
16
17class audio_CrasLoopback(audio_helper.cras_rms_test):
18    """Verifies audio playback and capture function."""
19    version = 1
20
21    @staticmethod
22    def wait_for_active_stream_count(expected_count):
23        utils.poll_for_condition(
24            lambda: cras_utils.get_active_stream_count() == expected_count,
25            exception=error.TestError(
26                'Timeout waiting active stream count to become %d' %
27                 expected_count))
28
29
30    def run_once(self):
31        """Entry point of this test."""
32
33        # Generate sine raw file that lasts 5 seconds.
34        raw_path = os.path.join(self.bindir, '5SEC.raw')
35        data_format = dict(file_type='raw', sample_format='S16_LE',
36                channel=2, rate=48000)
37        raw_file = audio_test_data.GenerateAudioTestData(
38            path=raw_path,
39            data_format=data_format,
40            duration_secs=5,
41            frequencies=[440, 440],
42            volume_scale=0.9)
43
44        recorded_file = os.path.join(self.resultsdir, 'cras_recorded.raw')
45
46        self.wait_for_active_stream_count(0)
47        p = cmd_utils.popen(cras_utils.playback_cmd(raw_file.path))
48        try:
49            self.wait_for_active_stream_count(1)
50            cras_utils.capture(recorded_file, duration=TEST_DURATION)
51
52            # Make sure the audio is still playing.
53            if p.poll() != None:
54                raise error.TestError('playback stopped')
55        finally:
56            cmd_utils.kill_or_log_returncode(p)
57            raw_file.delete()
58
59        rms_value = audio_helper.get_rms(recorded_file)[0]
60        self.write_perf_keyval({'rms_value': rms_value})
61
62