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
10import threading
11
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 chameleon_audio_helper
15from autotest_lib.client.cros.chameleon import chameleon_audio_ids
16from autotest_lib.server.cros.audio import audio_test
17
18
19class audio_AudioAfterSuspend(audio_test.AudioTest):
20    """Server side audio test.
21
22    This test talks to a Chameleon board and a Cros device to verify
23    audio function of the Cros device.
24
25    """
26    version = 1
27    DELAY_BEFORE_RECORD_SECONDS = 0.5
28    RECORD_SECONDS = 5
29    RESUME_TIMEOUT_SECS = 60
30    SHORT_WAIT = 2
31    SUSPEND_SECONDS = 30
32
33    PLUG_CONFIGS = [
34        # (plugged_before_suspend, plugged_after_suspend, plugged_before_resume)
35        (True, True, True),
36        (True, False, False),
37        (True, False, True),
38        (False, True, True),
39        (False, True, False),
40        ]
41
42    def action_plug_jack(self, plug_state):
43        """Calls the audio interface API and plugs/unplugs.
44
45        @param plug_state: plug state to switch to
46
47        """
48        logging.debug('Plugging' if plug_state else 'Unplugging')
49        jack_plugger = self.audio_board.get_jack_plugger()
50        if plug_state:
51            jack_plugger.plug()
52        else:
53            jack_plugger.unplug()
54        time.sleep(self.SHORT_WAIT)
55
56
57    def action_suspend(self, suspend_time=SUSPEND_SECONDS):
58        """Calls the host method suspend.
59
60        @param suspend_time: time to suspend the device for.
61
62        """
63        self.host.suspend(suspend_time=suspend_time)
64
65
66    def suspend_resume(self, plugged_before_suspend, plugged_after_suspend,
67                                plugged_before_resume, test_case):
68        """Performs the mix of suspend/resume and plug/unplug
69
70        @param plugged_before_suspend: plug state before suspend
71        @param plugged_after_suspend: plug state after suspend
72        @param plugged_before_resume: plug state before resume
73        @param test_case: string identifying test case sequence
74
75        """
76
77        # Suspend
78        boot_id = self.host.get_boot_id()
79        thread = threading.Thread(target=self.action_suspend)
80        thread.start()
81        try:
82            self.host.test_wait_for_sleep(self.SUSPEND_SECONDS / 3)
83        except error.TestFail, ex:
84            self.errors.append("%s - %s" % (test_case, str(ex)))
85
86        # Plugged after suspended
87        self.action_plug_jack(plugged_after_suspend)
88
89        # Plugged before resumed
90        self.action_plug_jack(plugged_before_resume)
91        try:
92            self.host.test_wait_for_resume(boot_id, self.RESUME_TIMEOUT_SECS)
93        except error.TestFail, ex:
94            self.errors.append("%s - %s" % (test_case, str(ex)))
95
96
97    def check_correct_audio_node_selected(self):
98        """Checks the node selected by Cras is correct."""
99        audio_test_utils.check_audio_nodes(self.audio_facade, self.audio_nodes)
100
101
102    def play_and_record(self, source_widget, recorder_widget):
103        """Plays and records audio
104
105        @param source_widget: widget to do the playback
106        @param recorder_widget: widget to do the recording
107
108        """
109        audio_test_utils.dump_cros_audio_logs(
110                self.host, self.audio_facade, self.resultsdir,
111                'before_playback')
112
113        self.check_correct_audio_node_selected()
114
115        # Play, wait for some time, and then start recording.
116        # This is to avoid artifact caused by codec initialization.
117        source_widget.set_playback_data(self.golden_file)
118        logging.debug('Start playing %s', self.golden_file.path)
119        source_widget.start_playback()
120
121        time.sleep(self.DELAY_BEFORE_RECORD_SECONDS)
122        logging.debug('Start recording.')
123        recorder_widget.start_recording()
124
125        time.sleep(self.RECORD_SECONDS)
126
127        recorder_widget.stop_recording()
128        logging.debug('Stopped recording.')
129
130        audio_test_utils.dump_cros_audio_logs(
131                self.host, self.audio_facade, self.resultsdir,
132                'after_recording')
133
134        recorder_widget.read_recorded_binary()
135
136
137    def save_and_check_data(self, recorder_widget):
138        """Saves and checks the data from the recorder
139
140        @param recorder_widget: recorder widget to save data from
141
142        @returns (success, error_message): success is True if audio comparison
143                                           is successful, False otherwise.
144                                           error_message contains the error
145                                           message.
146
147        """
148        recorded_file = os.path.join(self.resultsdir, "recorded.raw")
149        logging.debug('Saving recorded data to %s', recorded_file)
150        recorder_widget.save_file(recorded_file)
151
152        # Removes the beginning of recorded data. This is to avoid artifact
153        # caused by codec initialization in the beginning of
154        # recording.
155        recorder_widget.remove_head(2.0)
156
157        # Removes noise by a lowpass filter.
158        recorder_widget.lowpass_filter(self.low_pass_freq)
159        recorded_file = os.path.join(self.resultsdir,
160                                     "recorded_filtered.raw")
161        logging.debug('Saving filtered data to %s', recorded_file)
162        recorder_widget.save_file(recorded_file)
163
164        # Compares data by frequency and returns the result.
165        try:
166            audio_test_utils.check_recorded_frequency(
167                    self.golden_file, recorder_widget,
168                    second_peak_ratio=self.second_peak_ratio,
169                    ignore_frequencies=self.ignore_frequencies)
170        except error.TestFail, e:
171            return (False, e)
172
173        return (True, None)
174
175
176    def run_once(self, host, audio_nodes, golden_data,
177                 bind_from=None, bind_to=None,
178                 source=None, recorder=None, is_internal=False):
179        """Runs the test main workflow
180
181        @param host: A host object representing the DUT.
182        @param audio_nodes: audio nodes supposed to be selected.
183        @param golden_data: audio file and low pass filter frequency
184           the audio file should be test data defined in audio_test_data
185        @param bind_from: audio originating entity to be binded
186            should be defined in chameleon_audio_ids
187        @param bind_to: audio directed_to entity to be binded
188            should be defined in chameleon_audio_ids
189        @param source: source widget entity
190            should be defined in chameleon_audio_ids
191        @param recorder: recorder widget entity
192            should be defined in chameleon_audio_ids
193        @param is_internal: whether internal audio is tested flag
194
195        """
196        if (recorder == chameleon_audio_ids.CrosIds.INTERNAL_MIC and
197            not audio_test_utils.has_internal_microphone(host)):
198            return
199
200        if (source == chameleon_audio_ids.CrosIds.SPEAKER and
201            not audio_test_utils.has_internal_speaker(host)):
202            return
203
204        self.host = host
205        self.audio_nodes = audio_nodes
206        self.is_internal=is_internal
207
208        self.second_peak_ratio = audio_test_utils.DEFAULT_SECOND_PEAK_RATIO
209        self.ignore_frequencies = None
210        if source == chameleon_audio_ids.CrosIds.SPEAKER:
211            self.second_peak_ratio = 0.1
212            self.ignore_frequencies = [50, 60]
213        elif recorder == chameleon_audio_ids.CrosIds.INTERNAL_MIC:
214            self.second_peak_ratio = 0.2
215
216        self.errors = []
217        self.golden_file, self.low_pass_freq = golden_data
218        chameleon_board = self.host.chameleon
219        self.factory = self.create_remote_facade_factory(self.host)
220        self.audio_facade = self.factory.create_audio_facade()
221        chameleon_board.reset()
222        widget_factory = chameleon_audio_helper.AudioWidgetFactory(
223                self.factory, host)
224
225        # Two widgets are binded in the factory if necessary
226        binder_widget = None
227        bind_from_widget = None
228        bind_to_widget = None
229        if bind_from != None and bind_to != None:
230            bind_from_widget = widget_factory.create_widget(bind_from)
231            bind_to_widget = widget_factory.create_widget(bind_to)
232            binder_widget = widget_factory.create_binder(bind_from_widget,
233                                                         bind_to_widget)
234
235        # Additional widgets that could be part of the factory
236        if source == None:
237            source_widget = bind_from_widget
238        else:
239            source_widget = widget_factory.create_widget(source)
240        if recorder == None:
241            recorder_widget = bind_to_widget
242        else:
243            recorder_widget = widget_factory.create_widget(recorder)
244
245        self.audio_board = chameleon_board.get_audio_board()
246
247        # If there is no audio-board, test default state.
248        if self.audio_board == None:
249            plug_configs = [(True,True,True)]
250        else:
251            plug_configs = self.PLUG_CONFIGS
252
253        test_index = 0
254        for (plugged_before_suspend, plugged_after_suspend,
255                 plugged_before_resume) in plug_configs:
256            plugged_after_resume = True
257            test_index += 1
258
259            # Reverse plugged states, when internal audio is tested
260            if self.is_internal:
261                plugged_after_resume = False
262                plugged_before_suspend = not plugged_before_suspend
263                plugged_after_suspend = not plugged_after_suspend
264                plugged_before_resume = not plugged_before_resume
265            test_case = ('TEST CASE %d: %s > suspend > %s > %s > resume > %s' %
266                (test_index, 'PLUG' if plugged_before_suspend else 'UNPLUG',
267                 'PLUG' if plugged_after_suspend else 'UNPLUG',
268                 'PLUG' if plugged_before_resume else 'UNPLUG',
269                 'PLUG' if plugged_after_resume else 'UNPLUG'))
270            logging.info(test_case)
271
272            # Plugged status before suspended
273            self.action_plug_jack(plugged_before_suspend)
274
275            self.suspend_resume(plugged_before_suspend,
276                                plugged_after_suspend,
277                                plugged_before_resume,
278                                test_case)
279
280            # Active (plugged for external) state after resume
281            self.action_plug_jack(plugged_after_resume)
282
283            if binder_widget != None:
284                with chameleon_audio_helper.bind_widgets(binder_widget):
285                    self.play_and_record(source_widget, recorder_widget)
286            else:
287                self.play_and_record(source_widget, recorder_widget)
288
289            success, error_message = self.save_and_check_data(recorder_widget)
290            if not success:
291                self.errors.append('%s: Comparison failed: %s' %
292                                   test_case, error_message)
293
294        if self.errors:
295            raise error.TestFail('; '.join(set(self.errors)))
296