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 audio test using the Chameleon board."""
6
7import logging
8import os
9import time
10
11from autotest_lib.client.bin import utils
12from autotest_lib.client.common_lib import error
13from autotest_lib.client.cros.chameleon import audio_test_utils
14from autotest_lib.client.cros.chameleon import audio_widget_link
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_AudioAfterReboot(audio_test.AudioTest):
21    """Server side audio test.
22
23    This test talks to a Chameleon board and a Cros device to verify
24    audio function of the Cros device after reboot.
25
26    """
27    version = 1
28    DELAY_BEFORE_RECORD_SECONDS = 0.5
29    DELAY_AFTER_BINDING = 0.5
30    RECORD_SECONDS = 5
31    SHORT_WAIT = 2
32    PRC_RECONNECT_TIMEOUT = 60
33
34    def action_plug_jack(self, plug_state):
35        """Calls the audio interface API and plugs/unplugs.
36
37        @param plug_state: plug state to switch to
38
39        """
40        logging.debug('Plugging' if plug_state else 'Unplugging')
41        jack_plugger = self.audio_board.get_jack_plugger()
42        if plug_state:
43            jack_plugger.plug()
44        else:
45            jack_plugger.unplug()
46        time.sleep(self.SHORT_WAIT)
47
48
49    def play_and_record(self, source_widget, recorder_widget=None):
50        """Plays and records (if needed) audio.
51
52        @param source_widget: widget to do the playback
53        @param recorder_widget: widget to do the recording
54            None to skip recording.
55
56        """
57        self.check_correct_audio_node_selected()
58
59        # Play, wait for some time, and then start recording if needed.
60        source_widget.set_playback_data(self.golden_file)
61        logging.debug('Start playing %s', self.golden_file.path)
62        source_widget.start_playback()
63
64        if recorder_widget != None:
65            time.sleep(self.DELAY_BEFORE_RECORD_SECONDS)
66            logging.debug('Start recording.')
67            recorder_widget.start_recording()
68
69            time.sleep(self.RECORD_SECONDS)
70
71            recorder_widget.stop_recording()
72            logging.debug('Stopped recording.')
73
74            audio_test_utils.dump_cros_audio_logs(
75                    self.host, self.audio_facade, self.resultsdir,
76                    'after_recording')
77
78            recorder_widget.read_recorded_binary()
79        else:
80            time.sleep(self.RECORD_SECONDS)
81
82
83    def save_and_check_data(self, recorder_widget):
84        """Saves and checks the data from the recorder.
85
86        @param recorder_widget: recorder widget to save data from
87
88        @raise error.TestFail: if comparison fails
89
90        """
91        recorded_file = os.path.join(self.resultsdir, "recorded.raw")
92        logging.debug('Saving recorded data to %s', recorded_file)
93        recorder_widget.save_file(recorded_file)
94
95        # Removes the beginning of recorded data. This is to avoid artifact
96        # caused by codec initialization in the beginning of recording.
97        recorder_widget.remove_head(2.0)
98
99        # Removes noise by a lowpass filter.
100        recorder_widget.lowpass_filter(self.low_pass_freq)
101        recorded_file = os.path.join(self.resultsdir,
102                                     "recorded_filtered.raw")
103        logging.debug('Saving filtered data to %s', recorded_file)
104        recorder_widget.save_file(recorded_file)
105
106        # Compares data by frequency.
107        audio_test_utils.check_recorded_frequency(
108                self.golden_file, recorder_widget,
109                second_peak_ratio=self.second_peak_ratio,
110                ignore_frequencies=self.ignore_frequencies)
111
112
113    def check_correct_audio_node_selected(self):
114        """Checks the node selected by Cras is correct."""
115        audio_test_utils.check_audio_nodes(self.audio_facade, self.audio_nodes)
116
117
118    def play_reboot_play_and_record (self, source_widget, recorder_widget):
119        """Play audio, then reboot, and play and record.
120
121        @param source_widget: source widget to play with
122        @param recorder_widget: recorder widget to record with
123
124        """
125        self.play_and_record(source_widget)
126
127        # Disconnecs audio bus so Cros device can detects plugger correctly
128        # when the test involes plugger.
129        # For case where audio bus is used but no plugger is used, it is no
130        # harm to disconnect audio bus and reconnect it.
131        if self.use_audio_bus:
132            logging.info('Disconnecting audio bus before reboot')
133            self.widget_link.disconnect_audio_bus()
134
135        self.host.reboot()
136        utils.poll_for_condition(condition=self.factory.ready,
137                                 timeout=self.PRC_RECONNECT_TIMEOUT,)
138        logging.debug('After reboot')
139
140        audio_test_utils.dump_cros_audio_logs(
141                self.host, self.audio_facade, self.resultsdir,
142                'after_reboot')
143
144        self.check_correct_audio_node_selected()
145
146        if self.use_audio_bus:
147            logging.info('Reconnecting audio bus after reboot before playback')
148            self.widget_link.reconnect_audio_bus()
149
150        audio_test_utils.dump_cros_audio_logs(
151                self.host, self.audio_facade, self.resultsdir,
152                'after_bus_reconnect')
153
154        self.play_and_record(source_widget, recorder_widget)
155
156
157    def run_once(self, host, golden_data, audio_nodes, bind_from=None, bind_to=None,
158                 source=None, recorder=None, is_internal=False):
159        """Runs the test main workflow.
160
161        @param host: A host object representing the DUT.
162        @param golden_data: audio file and low pass filter frequency
163           the audio file should be test data defined in audio_test_data
164        @param audio_nodes: audio nodes supposed to be selected
165        @param bind_from: audio originating entity to be binded
166            should be defined in chameleon_audio_ids
167        @param bind_to: audio directed_to entity to be binded
168            should be defined in chameleon_audio_ids
169        @param source: source widget entity
170            should be defined in chameleon_audio_ids
171        @param recorder: recorder widget entity
172            should be defined in chameleon_audio_ids
173        @param is_internal: whether internal audio is tested flag
174
175        """
176        if (recorder == chameleon_audio_ids.CrosIds.INTERNAL_MIC and
177            not audio_test_utils.has_internal_microphone(host)):
178            return
179
180        if (source == chameleon_audio_ids.CrosIds.SPEAKER and
181            not audio_test_utils.has_internal_speaker(host)):
182            return
183
184        self.host = host
185        self.audio_nodes = audio_nodes
186        self.golden_file, self.low_pass_freq = golden_data
187        chameleon_board = self.host.chameleon
188        self.factory = self.create_remote_facade_factory(self.host)
189        self.audio_facade = self.factory.create_audio_facade()
190        chameleon_board.reset()
191        widget_factory = chameleon_audio_helper.AudioWidgetFactory(
192                self.factory, host)
193        self.audio_board = chameleon_board.get_audio_board()
194        self.widget_link = None
195        self.use_audio_bus = False
196
197        self.second_peak_ratio = audio_test_utils.DEFAULT_SECOND_PEAK_RATIO
198        self.ignore_frequencies = None
199        if source == chameleon_audio_ids.CrosIds.SPEAKER:
200            self.second_peak_ratio = 0.1
201            self.ignore_frequencies = [50, 60]
202        elif recorder == chameleon_audio_ids.CrosIds.INTERNAL_MIC:
203            self.second_peak_ratio = 0.2
204
205        # Two widgets are binded in the factory if necessary
206        binder_widget = None
207        bind_from_widget = None
208        bind_to_widget = None
209        if bind_from != None and bind_to != None:
210            bind_from_widget = widget_factory.create_widget(bind_from)
211            bind_to_widget = widget_factory.create_widget(bind_to)
212            binder_widget = widget_factory.create_binder(bind_from_widget,
213                                                         bind_to_widget)
214            self.widget_link = binder_widget.get_link()
215            if isinstance(self.widget_link, audio_widget_link.AudioBusLink):
216                self.use_audio_bus = True
217
218        # Additional widgets that could be part of the factory
219        if source == None:
220            source_widget = bind_from_widget
221        else:
222            source_widget = widget_factory.create_widget(source)
223        if recorder == None:
224            recorder_widget = bind_to_widget
225        else:
226            recorder_widget = widget_factory.create_widget(recorder)
227
228        # Plug for external audio
229        self.action_plug_jack(not is_internal)
230
231        # Play only, reboot, then play and record.
232        if binder_widget != None:
233            with chameleon_audio_helper.bind_widgets(binder_widget):
234                time.sleep(self.DELAY_AFTER_BINDING)
235                self.play_reboot_play_and_record(source_widget, recorder_widget)
236        else:
237            self.play_reboot_play_and_record(source_widget, recorder_widget)
238
239        self.save_and_check_data(recorder_widget)
240