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