1# Copyright 2015 The Chromium OS 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
5"""This is a server side bluetooth playback test using the Chameleon board."""
6
7import logging
8import os
9import time, threading
10
11from autotest_lib.client.bin import utils
12from autotest_lib.client.common_lib import error
13from autotest_lib.client.cros.audio import audio_test_data
14from autotest_lib.client.cros.chameleon import audio_test_utils
15from autotest_lib.client.cros.chameleon import chameleon_audio_helper
16from autotest_lib.client.cros.chameleon import chameleon_audio_ids
17from autotest_lib.server.cros.audio import audio_test
18
19
20class audio_AudioBasicBluetoothPlayback(audio_test.AudioTest):
21    """Server side bluetooth playback audio test.
22
23    This test talks to a Chameleon board and a Cros device to verify
24    bluetooth playback audio function of the Cros device.
25
26    """
27    version = 1
28    DELAY_AFTER_DISABLING_MODULE_SECONDS = 30
29    DELAY_AFTER_DISCONNECT_SECONDS = 5
30    DELAY_AFTER_ENABLING_MODULE_SECONDS = 10
31    DELAY_AFTER_RECONNECT_SECONDS = 5
32    DELAY_BEFORE_RECORD_SECONDS = 0.5
33    RECORD_SECONDS = 5
34    SUSPEND_SECONDS = 30
35    RESUME_TIMEOUT_SECS = 60
36    PRC_RECONNECT_TIMEOUT = 60
37    BLUETOOTH_RECONNECT_TIMEOUT_SECS = 30
38    DELAY_FOR_A2DP_RECONNECT_AFTER_SUSPEND = 10
39
40    def disconnect_connect_bt(self, link):
41        """Performs disconnect and connect BT module
42
43        @param link: binder link to control BT adapter
44
45        """
46
47        logging.info("Disconnecting BT module...")
48        link.adapter_disconnect_module()
49        time.sleep(self.DELAY_AFTER_DISCONNECT_SECONDS)
50        audio_test_utils.check_audio_nodes(self.audio_facade,
51                                           (['INTERNAL_SPEAKER'], None))
52        logging.info("Connecting BT module...")
53        link.adapter_connect_module()
54        time.sleep(self.DELAY_AFTER_RECONNECT_SECONDS)
55
56
57    def disable_enable_bt(self, link):
58        """Performs turn off and then on BT module
59
60        @param link: binder link to control BT adapter
61
62        """
63
64        logging.info("Turning off BT module...")
65        link.disable_bluetooth_module()
66        time.sleep(self.DELAY_AFTER_DISABLING_MODULE_SECONDS)
67        audio_test_utils.check_audio_nodes(self.audio_facade,
68                                           (['INTERNAL_SPEAKER'], None))
69        logging.info("Turning on BT module...")
70        link.enable_bluetooth_module()
71        time.sleep(self.DELAY_AFTER_ENABLING_MODULE_SECONDS)
72        logging.info("Connecting BT module...")
73        link.adapter_connect_module()
74        time.sleep(self.DELAY_AFTER_RECONNECT_SECONDS)
75
76
77    def bluetooth_nodes_plugged(self):
78        """Checks if bluetooth nodes are plugged.
79
80        @returns: True if bluetooth nodes are plugged. False otherwise.
81
82        """
83        return audio_test_utils.bluetooth_nodes_plugged(self.audio_facade)
84
85
86    def dump_logs_after_nodes_changed(self):
87        """Dumps the log after unexpected NodesChanged signal happens."""
88        audio_test_utils.dump_cros_audio_logs(
89                self.host, self.audio_facade, self.resultsdir,
90                'after_nodes_changed')
91
92
93    def run_once(self, host, suspend=False,
94                 disable=False, disconnect=False, check_quality=False):
95        """Running Bluetooth basic audio tests
96
97        @param host: device under test host
98        @param suspend: suspend flag to enable suspend before play/record
99        @param disable: disable flag to disable BT module before play/record
100        @param disconnect: disconnect flag to disconnect BT module
101            before play/record
102        @param check_quality: flag to check audio quality.
103
104        """
105        self.host = host
106        golden_file = audio_test_data.FREQUENCY_TEST_FILE
107
108        factory = self.create_remote_facade_factory(host)
109        self.audio_facade = factory.create_audio_facade()
110
111        chameleon_board = host.chameleon
112        chameleon_board.reset()
113
114        widget_factory = chameleon_audio_helper.AudioWidgetFactory(
115                factory, host)
116
117        source = widget_factory.create_widget(
118            chameleon_audio_ids.CrosIds.BLUETOOTH_HEADPHONE)
119        bluetooth_widget = widget_factory.create_widget(
120            chameleon_audio_ids.PeripheralIds.BLUETOOTH_DATA_RX)
121        recorder = widget_factory.create_widget(
122            chameleon_audio_ids.ChameleonIds.LINEIN)
123
124        binder = widget_factory.create_binder(
125                source, bluetooth_widget, recorder)
126
127        with chameleon_audio_helper.bind_widgets(binder):
128
129            audio_test_utils.dump_cros_audio_logs(
130                    host, self.audio_facade, self.resultsdir, 'after_binding')
131
132            # Checks the node selected by Cras is correct.
133            audio_test_utils.check_audio_nodes(self.audio_facade,
134                                               (['BLUETOOTH'], None))
135
136            self.audio_facade.set_selected_output_volume(80)
137
138            # Starts playing, waits for some time, and then starts recording.
139            # This is to avoid artifact caused by codec initialization.
140            source.set_playback_data(golden_file)
141
142            # Create link to control BT adapter.
143            link = binder.get_binders()[0].get_link()
144
145            if disable:
146                self.disable_enable_bt(link)
147            if disconnect:
148                self.disconnect_connect_bt(link)
149            if suspend:
150                audio_test_utils.suspend_resume(host, self.SUSPEND_SECONDS)
151
152            utils.poll_for_condition(condition=factory.ready,
153                                     timeout=self.PRC_RECONNECT_TIMEOUT,
154                                     desc='multimedia server reconnect')
155
156            if disable or disconnect or suspend:
157                audio_test_utils.dump_cros_audio_logs(
158                        host, self.audio_facade, self.resultsdir,
159                        'after_action')
160
161            # Gives DUT some time to auto-reconnect bluetooth after resume.
162            if suspend:
163                utils.poll_for_condition(
164                        condition=self.bluetooth_nodes_plugged,
165                        timeout=self.BLUETOOTH_RECONNECT_TIMEOUT_SECS,
166                        desc='bluetooth node auto-reconnect after suspend')
167                # Delay some time for A2DP to be reconnected.
168                # Normally this happens several seconds after HSP is
169                # reconnected. However, there is no event what we can wait for,
170                # so just wait some time.
171                time.sleep(self.DELAY_FOR_A2DP_RECONNECT_AFTER_SUSPEND)
172
173            with audio_test_utils.monitor_no_nodes_changed(
174                    self.audio_facade, self.dump_logs_after_nodes_changed):
175                # Checks the node selected by Cras is correct again.
176                audio_test_utils.check_audio_nodes(self.audio_facade,
177                                                   (['BLUETOOTH'], None))
178
179                logging.info('Start playing %s on Cros device',
180                             golden_file.path)
181
182                source.start_playback()
183
184                time.sleep(self.DELAY_BEFORE_RECORD_SECONDS)
185                logging.info('Start recording from Chameleon.')
186                recorder.start_recording()
187
188                time.sleep(self.RECORD_SECONDS)
189
190                recorder.stop_recording()
191                logging.info('Stopped recording from Chameleon.')
192
193                audio_test_utils.dump_cros_audio_logs(
194                        host, self.audio_facade, self.resultsdir,
195                        'after_recording')
196
197                recorder.read_recorded_binary()
198                logging.info('Read recorded binary from Chameleon.')
199
200                recorded_file = os.path.join(self.resultsdir, "recorded.raw")
201                logging.info('Saving recorded data to %s', recorded_file)
202                recorder.save_file(recorded_file)
203
204        # Removes the beginning of recorded data. This is to avoid artifact
205        # caused by Chameleon codec initialization in the beginning of
206        # recording.
207        recorder.remove_head(0.5)
208
209        recorded_file = os.path.join(self.resultsdir, "recorded_clipped.raw")
210        logging.info('Saving clipped data to %s', recorded_file)
211        recorder.save_file(recorded_file)
212
213        # Compares data by frequency. Audio signal recorded by microphone has
214        # gone through analog processing and through the air.
215        # This suffers from codec artifacts and noise on the path.
216        # Comparing data by frequency is more robust than comparing by
217        # correlation, which is suitable for fully-digital audio path like USB
218        # and HDMI.
219        audio_test_utils.check_recorded_frequency(
220                golden_file, recorder, check_anomaly=check_quality)
221