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