blob: df2565cb1eac0e338663bc213b314366eab58f43 [file] [log] [blame]
Hsinyu Chao4b8300e2011-11-15 13:07:32 -08001#!/usr/bin/python
2# Copyright (c) 2012 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
6import logging
7import os
Hsinyu Chaof80337a2012-04-07 18:02:29 +08008import re
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +08009import threading
Hsin-Yu Chaof272d8e2013-04-05 03:28:50 +080010import time
Hsinyu Chao4b8300e2011-11-15 13:07:32 -080011
Hsin-Yu Chao084e9da2012-11-07 15:56:26 +080012from glob import glob
13
Hsinyu Chao4b8300e2011-11-15 13:07:32 -080014from autotest_lib.client.bin import utils
Hsin-Yu Chao084e9da2012-11-07 15:56:26 +080015from autotest_lib.client.bin.input.input_device import *
Hsinyu Chao4b8300e2011-11-15 13:07:32 -080016from autotest_lib.client.common_lib import error
17
18LD_LIBRARY_PATH = 'LD_LIBRARY_PATH'
19
Hsinyu Chaof80337a2012-04-07 18:02:29 +080020_DEFAULT_NUM_CHANNELS = 2
Dylan Reidbf9a5d42012-11-06 16:27:20 -080021_DEFAULT_REC_COMMAND = 'arecord -D hw:0,0 -d 10 -f dat'
Hsinyu Chaof80337a2012-04-07 18:02:29 +080022_DEFAULT_SOX_FORMAT = '-t raw -b 16 -e signed -r 48000 -L'
Hsin-Yu Chao4be6d182013-04-19 14:07:56 +080023
24# Minimum RMS value to pass when checking recorded file.
25_DEFAULT_SOX_RMS_THRESHOLD = 0.08
Hsinyu Chaof80337a2012-04-07 18:02:29 +080026
Hsin-Yu Chao8d093f42012-11-05 18:43:22 +080027_JACK_VALUE_ON_RE = re.compile('.*values=on')
28_HP_JACK_CONTROL_RE = re.compile('numid=(\d+).*Headphone\sJack')
29_MIC_JACK_CONTROL_RE = re.compile('numid=(\d+).*Mic\sJack')
30
Hsinyu Chaof80337a2012-04-07 18:02:29 +080031_SOX_RMS_AMPLITUDE_RE = re.compile('RMS\s+amplitude:\s+(.+)')
Hsinyu Chao2d64e1f2012-05-21 11:18:53 +080032_SOX_ROUGH_FREQ_RE = re.compile('Rough\s+frequency:\s+(.+)')
Hsinyu Chaof80337a2012-04-07 18:02:29 +080033_SOX_FORMAT = '-t raw -b 16 -e signed -r 48000 -L'
34
Hsin-Yu Chao95ee3512012-11-05 20:43:10 +080035_AUDIO_NOT_FOUND_RE = r'Audio\snot\sdetected'
36_MEASURED_LATENCY_RE = r'Measured\sLatency:\s(\d+)\suS'
37_REPORTED_LATENCY_RE = r'Reported\sLatency:\s(\d+)\suS'
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +080038
39class RecordSampleThread(threading.Thread):
40 '''Wraps the execution of arecord in a thread.'''
41 def __init__(self, audio, recordfile):
42 threading.Thread.__init__(self)
43 self._audio = audio
44 self._recordfile = recordfile
45
46 def run(self):
47 self._audio.record_sample(self._recordfile)
48
49
Hsinyu Chao4b8300e2011-11-15 13:07:32 -080050class AudioHelper(object):
51 '''
52 A helper class contains audio related utility functions.
53 '''
Dylan Reidbf9a5d42012-11-06 16:27:20 -080054 def __init__(self, test,
55 sox_format = _DEFAULT_SOX_FORMAT,
Dylan Reid51f289c2012-11-06 17:16:24 -080056 sox_threshold = _DEFAULT_SOX_RMS_THRESHOLD,
Dylan Reidbf9a5d42012-11-06 16:27:20 -080057 record_command = _DEFAULT_REC_COMMAND,
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +080058 num_channels = _DEFAULT_NUM_CHANNELS):
Hsinyu Chao4b8300e2011-11-15 13:07:32 -080059 self._test = test
Dylan Reid51f289c2012-11-06 17:16:24 -080060 self._sox_threshold = sox_threshold
Hsinyu Chaof80337a2012-04-07 18:02:29 +080061 self._sox_format = sox_format
Dylan Reidbf9a5d42012-11-06 16:27:20 -080062 self._rec_cmd = record_command
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +080063 self._num_channels = num_channels
Hsinyu Chao4b8300e2011-11-15 13:07:32 -080064
65 def setup_deps(self, deps):
66 '''
67 Sets up audio related dependencies.
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +080068
69 @param deps: List of dependencies to set up.
Hsinyu Chao4b8300e2011-11-15 13:07:32 -080070 '''
71 for dep in deps:
72 if dep == 'test_tones':
73 dep_dir = os.path.join(self._test.autodir, 'deps', dep)
74 self._test.job.install_pkg(dep, 'dep', dep_dir)
75 self.test_tones_path = os.path.join(dep_dir, 'src', dep)
76 elif dep == 'audioloop':
77 dep_dir = os.path.join(self._test.autodir, 'deps', dep)
78 self._test.job.install_pkg(dep, 'dep', dep_dir)
79 self.audioloop_path = os.path.join(dep_dir, 'src',
80 'looptest')
Hsin-Yu Chao95ee3512012-11-05 20:43:10 +080081 self.loopback_latency_path = os.path.join(dep_dir, 'src',
82 'loopback_latency')
Hsinyu Chao4b8300e2011-11-15 13:07:32 -080083 elif dep == 'sox':
84 dep_dir = os.path.join(self._test.autodir, 'deps', dep)
85 self._test.job.install_pkg(dep, 'dep', dep_dir)
86 self.sox_path = os.path.join(dep_dir, 'bin', dep)
87 self.sox_lib_path = os.path.join(dep_dir, 'lib')
88 if os.environ.has_key(LD_LIBRARY_PATH):
89 paths = os.environ[LD_LIBRARY_PATH].split(':')
90 if not self.sox_lib_path in paths:
91 paths.append(self.sox_lib_path)
92 os.environ[LD_LIBRARY_PATH] = ':'.join(paths)
93 else:
94 os.environ[LD_LIBRARY_PATH] = self.sox_lib_path
95
96 def cleanup_deps(self, deps):
97 '''
98 Cleans up environments which has been setup for dependencies.
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +080099
100 @param deps: List of dependencies to clean up.
Hsinyu Chao4b8300e2011-11-15 13:07:32 -0800101 '''
102 for dep in deps:
103 if dep == 'sox':
104 if (os.environ.has_key(LD_LIBRARY_PATH)
105 and hasattr(self, 'sox_lib_path')):
106 paths = filter(lambda x: x != self.sox_lib_path,
107 os.environ[LD_LIBRARY_PATH].split(':'))
108 os.environ[LD_LIBRARY_PATH] = ':'.join(paths)
109
Derek Basehoree973ce42012-07-10 23:38:32 -0700110 def set_volume_levels(self, volume, capture):
111 '''
112 Sets the volume and capture gain through cras_test_client
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800113
114 @param volume: The playback volume to set.
115 @param capture: The capture gain to set.
Derek Basehoree973ce42012-07-10 23:38:32 -0700116 '''
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800117 logging.info('Setting volume level to %d', volume)
Derek Basehoree973ce42012-07-10 23:38:32 -0700118 utils.system('/usr/bin/cras_test_client --volume %d' % volume)
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800119 logging.info('Setting capture gain to %d', capture)
Derek Basehoree973ce42012-07-10 23:38:32 -0700120 utils.system('/usr/bin/cras_test_client --capture_gain %d' % capture)
121 utils.system('/usr/bin/cras_test_client --dump_server_info')
Dylan Reidc264e012012-11-06 18:26:12 -0800122 utils.system('/usr/bin/cras_test_client --mute 0')
Derek Basehoree973ce42012-07-10 23:38:32 -0700123 utils.system('amixer -c 0 contents')
124
Hsin-Yu Chao084e9da2012-11-07 15:56:26 +0800125 def get_mixer_jack_status(self, jack_reg_exp):
Hsin-Yu Chao8d093f42012-11-05 18:43:22 +0800126 '''
Hsin-Yu Chao084e9da2012-11-07 15:56:26 +0800127 Gets the mixer jack status.
Hsin-Yu Chao8d093f42012-11-05 18:43:22 +0800128
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800129 @param jack_reg_exp: The regular expression to match jack control name.
Hsin-Yu Chao8d093f42012-11-05 18:43:22 +0800130
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800131 @return None if the control does not exist, return True if jack control
Hsin-Yu Chao8d093f42012-11-05 18:43:22 +0800132 is detected plugged, return False otherwise.
133 '''
134 output = utils.system_output('amixer -c0 controls', retain_output=True)
135 numid = None
136 for line in output.split('\n'):
137 m = jack_reg_exp.match(line)
138 if m:
139 numid = m.group(1)
140 break
Hsin-Yu Chao084e9da2012-11-07 15:56:26 +0800141
142 # Proceed only when matched numid is not empty.
143 if numid:
Hsin-Yu Chao8d093f42012-11-05 18:43:22 +0800144 output = utils.system_output('amixer -c0 cget numid=%s' % numid)
145 for line in output.split('\n'):
146 if _JACK_VALUE_ON_RE.match(line):
147 return True
148 return False
149 else:
150 return None
151
152 def get_hp_jack_status(self):
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800153 '''Gets the status of headphone jack'''
Hsin-Yu Chao084e9da2012-11-07 15:56:26 +0800154 status = self.get_mixer_jack_status(_HP_JACK_CONTROL_RE)
155 if status is not None:
156 return status
157
158 # When headphone jack is not found in amixer, lookup input devices
159 # instead.
160 #
161 # TODO(hychao): Check hp/mic jack status dynamically from evdev. And
162 # possibly replace the existing check using amixer.
163 for evdev in glob('/dev/input/event*'):
164 device = InputDevice(evdev)
165 if device.is_hp_jack():
166 return device.get_headphone_insert()
167 else:
168 return None
Hsin-Yu Chao8d093f42012-11-05 18:43:22 +0800169
170 def get_mic_jack_status(self):
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800171 '''Gets the status of mic jack'''
Hsin-Yu Chao084e9da2012-11-07 15:56:26 +0800172 status = self.get_mixer_jack_status(_MIC_JACK_CONTROL_RE)
173 if status is not None:
174 return status
175
176 # When mic jack is not found in amixer, lookup input devices instead.
177 for evdev in glob('/dev/input/event*'):
178 device = InputDevice(evdev)
179 if device.is_mic_jack():
180 return device.get_microphone_insert()
181 else:
182 return None
Hsin-Yu Chao8d093f42012-11-05 18:43:22 +0800183
184 def check_loopback_dongle(self):
185 '''
186 Checks if loopback dongle is equipped correctly.
187 '''
188 # Check Mic Jack
189 mic_jack_status = self.get_mic_jack_status()
190 if mic_jack_status is None:
191 logging.warning('Found no Mic Jack control, skip check.')
192 elif not mic_jack_status:
193 logging.info('Mic jack is not plugged.')
194 return False
195 else:
196 logging.info('Mic jack is plugged.')
197
198 # Check Headphone Jack
199 hp_jack_status = self.get_hp_jack_status()
200 if hp_jack_status is None:
201 logging.warning('Found no Headphone Jack control, skip check.')
202 elif not hp_jack_status:
203 logging.info('Headphone jack is not plugged.')
204 return False
205 else:
206 logging.info('Headphone jack is plugged.')
207
Hsin-Yu Chao3953f522012-11-12 18:39:39 +0800208 # Use latency check to test if audio can be captured through dongle.
209 # We only want to know the basic function of dongle, so no need to
210 # assert the latency accuracy here.
211 latency = self.loopback_latency_check(n=4000)
212 if latency:
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800213 logging.info('Got latency measured %d, reported %d',
214 latency[0], latency[1])
Hsin-Yu Chao3953f522012-11-12 18:39:39 +0800215 else:
216 logging.warning('Latency check fail.')
217 return False
218
Hsin-Yu Chao8d093f42012-11-05 18:43:22 +0800219 return True
220
Hsinyu Chao4b8300e2011-11-15 13:07:32 -0800221 def set_mixer_controls(self, mixer_settings={}, card='0'):
222 '''
223 Sets all mixer controls listed in the mixer settings on card.
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800224
225 @param mixer_settings: Mixer settings to set.
226 @param card: Index of audio card to set mixer settings for.
Hsinyu Chao4b8300e2011-11-15 13:07:32 -0800227 '''
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800228 logging.info('Setting mixer control values on %s', card)
Hsinyu Chao4b8300e2011-11-15 13:07:32 -0800229 for item in mixer_settings:
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800230 logging.info('Setting %s to %s on card %s',
231 item['name'], item['value'], card)
Hsinyu Chao4b8300e2011-11-15 13:07:32 -0800232 cmd = 'amixer -c %s cset name=%s %s'
233 cmd = cmd % (card, item['name'], item['value'])
234 try:
235 utils.system(cmd)
236 except error.CmdError:
237 # A card is allowed not to support all the controls, so don't
238 # fail the test here if we get an error.
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800239 logging.info('amixer command failed: %s', cmd)
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800240
Hsinyu Chao2d64e1f2012-05-21 11:18:53 +0800241 def sox_stat_output(self, infile, channel):
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800242 '''Executes sox stat command.
243
244 @param infile: Input file name.
245 @param channel: The selected channel.
246
247 @return The output of sox stat command
248 '''
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800249 sox_mixer_cmd = self.get_sox_mixer_cmd(infile, channel)
250 stat_cmd = '%s -c 1 %s - -n stat 2>&1' % (self.sox_path,
251 self._sox_format)
252 sox_cmd = '%s | %s' % (sox_mixer_cmd, stat_cmd)
Hsinyu Chao2d64e1f2012-05-21 11:18:53 +0800253 return utils.system_output(sox_cmd, retain_output=True)
254
255 def get_audio_rms(self, sox_output):
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800256 '''Gets the audio RMS value from sox stat output
257
258 @param sox_output: Output of sox stat command.
259
260 @return The RMS value parsed from sox stat output.
261 '''
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800262 for rms_line in sox_output.split('\n'):
263 m = _SOX_RMS_AMPLITUDE_RE.match(rms_line)
264 if m is not None:
265 return float(m.group(1))
266
Hsinyu Chao2d64e1f2012-05-21 11:18:53 +0800267 def get_rough_freq(self, sox_output):
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800268 '''Gets the rough audio frequency from sox stat output
269
270 @param sox_output: Output of sox stat command.
271
272 @return The rough frequency value parsed from sox stat output.
273 '''
274
Hsinyu Chao2d64e1f2012-05-21 11:18:53 +0800275 for rms_line in sox_output.split('\n'):
276 m = _SOX_ROUGH_FREQ_RE.match(rms_line)
277 if m is not None:
278 return int(m.group(1))
279
280
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800281 def get_sox_mixer_cmd(self, infile, channel):
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800282 '''Gets sox mixer command to reduce channel.
283
284 @param infile: Input file name.
285 @param channel: The selected channel to take effect.
286 '''
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800287 # Build up a pan value string for the sox command.
288 if channel == 0:
289 pan_values = '1'
290 else:
291 pan_values = '0'
292 for pan_index in range(1, self._num_channels):
293 if channel == pan_index:
294 pan_values = '%s%s' % (pan_values, ',1')
295 else:
296 pan_values = '%s%s' % (pan_values, ',0')
297
298 return '%s -c 2 %s %s -c 1 %s - mixer %s' % (self.sox_path,
299 self._sox_format, infile, self._sox_format, pan_values)
300
301 def noise_reduce_file(self, in_file, noise_file, out_file):
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800302 '''Runs the sox command to noise-reduce in_file using
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800303 the noise profile from noise_file.
304
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800305 @param in_file: The file to noise reduce.
306 @param noise_file: The file containing the noise profile.
307 This can be created by recording silence.
308 @param out_file: The file contains the noise reduced sound.
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800309
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800310 @return The name of the file containing the noise-reduced data.
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800311 '''
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800312 prof_cmd = '%s -c 2 %s %s -n noiseprof' % (self.sox_path,
313 _SOX_FORMAT, noise_file)
314 reduce_cmd = ('%s -c 2 %s %s -c 2 %s %s noisered' %
315 (self.sox_path, _SOX_FORMAT, in_file, _SOX_FORMAT, out_file))
316 utils.system('%s | %s' % (prof_cmd, reduce_cmd))
317
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800318 def record_sample(self, tmpfile):
319 '''Records a sample from the default input device.
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800320
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800321 @param duration: How long to record in seconds.
322 @param tmpfile: The file to record to.
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800323 '''
Dylan Reidbf9a5d42012-11-06 16:27:20 -0800324 cmd_rec = self._rec_cmd + ' %s' % tmpfile
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800325 logging.info('Command %s recording now', cmd_rec)
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800326 utils.system(cmd_rec)
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800327
Hsin-Yu Chao78c44b22013-04-06 05:33:58 +0800328 def loopback_test_channels(self, noise_file_name, loopback_callback=None,
Hsin-Yu Chao11041d32012-11-13 15:46:13 +0800329 check_recorded_callback=None):
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800330 '''Tests loopback on all channels.
331
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800332 @param noise_file_name: Name of the file contains pre-recorded noise.
333 @param loopback_callback: The callback to do the loopback for
334 one channel.
335 @param check_recorded_callback: The callback to check recorded file.
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800336 '''
337 for channel in xrange(self._num_channels):
Hsin-Yu Chao78c44b22013-04-06 05:33:58 +0800338 reduced_file_name = self.create_wav_file("reduced-%d" % channel)
339 record_file_name = self.create_wav_file("record-%d" % channel)
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800340
Hsin-Yu Chao78c44b22013-04-06 05:33:58 +0800341 record_thread = RecordSampleThread(self, record_file_name)
342 record_thread.start()
343 if loopback_callback:
344 loopback_callback(channel)
345 record_thread.join()
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800346
Hsin-Yu Chao78c44b22013-04-06 05:33:58 +0800347 self.noise_reduce_file(record_file_name, noise_file_name,
348 reduced_file_name)
Hsin-Yu Chao11041d32012-11-13 15:46:13 +0800349
Hsin-Yu Chao78c44b22013-04-06 05:33:58 +0800350 sox_output = self.sox_stat_output(reduced_file_name, channel)
351
352 # Use injected check recorded callback if any.
353 if check_recorded_callback:
354 check_recorded_callback(sox_output)
355 else:
356 self.check_recorded(sox_output)
Dylan Reid51f289c2012-11-06 17:16:24 -0800357
358 def check_recorded(self, sox_output):
359 """Checks if the calculated RMS value is expected.
360
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800361 @param sox_output: The output from sox stat command.
Dylan Reid51f289c2012-11-06 17:16:24 -0800362
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800363 @raises error.TestError if RMS amplitude can't be parsed.
364 @raises error.TestFail if the RMS amplitude of the recording isn't above
Dylan Reid51f289c2012-11-06 17:16:24 -0800365 the threshold.
366 """
367 rms_val = self.get_audio_rms(sox_output)
368
369 # In case we don't get a valid RMS value.
370 if rms_val is None:
371 raise error.TestError(
372 'Failed to generate an audio RMS value from playback.')
373
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800374 logging.info('Got audio RMS value of %f. Minimum pass is %f.',
375 rms_val, self._sox_threshold)
Dylan Reid51f289c2012-11-06 17:16:24 -0800376 if rms_val < self._sox_threshold:
Hsin-Yu Chao84e86d22013-04-03 00:43:01 +0800377 raise error.TestFail(
Dylan Reid51f289c2012-11-06 17:16:24 -0800378 'Audio RMS value %f too low. Minimum pass is %f.' %
379 (rms_val, self._sox_threshold))
Hsin-Yu Chao95ee3512012-11-05 20:43:10 +0800380
381 def loopback_latency_check(self, **args):
382 '''
383 Checks loopback latency.
384
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800385 @param args: additional arguments for loopback_latency.
Hsin-Yu Chao95ee3512012-11-05 20:43:10 +0800386
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800387 @return A tuple containing measured and reported latency in uS.
Hsin-Yu Chao95ee3512012-11-05 20:43:10 +0800388 Return None if no audio detected.
389 '''
390 noise_threshold = str(args['n']) if args.has_key('n') else '400'
391
392 cmd = '%s -n %s' % (self.loopback_latency_path, noise_threshold)
393
Hsin-Yu Chaod73dfc12013-04-15 18:26:27 +0800394 output = utils.system_output(cmd, retain_output=True)
Hsin-Yu Chaof272d8e2013-04-05 03:28:50 +0800395
396 # Sleep for a short while to make sure device is not busy anymore
397 # after called loopback_latency.
398 time.sleep(.1)
399
Hsin-Yu Chao95ee3512012-11-05 20:43:10 +0800400 measured_latency = None
401 reported_latency = None
402 for line in output.split('\n'):
403 match = re.search(_MEASURED_LATENCY_RE, line, re.I)
404 if match:
405 measured_latency = int(match.group(1))
406 continue
407 match = re.search(_REPORTED_LATENCY_RE, line, re.I)
408 if match:
409 reported_latency = int(match.group(1))
410 continue
411 if re.search(_AUDIO_NOT_FOUND_RE, line, re.I):
412 return None
413 if measured_latency and reported_latency:
414 return (measured_latency, reported_latency)
415 else:
416 # Should not reach here, just in case.
417 return None
Simon Quea4be3442012-11-14 16:36:56 -0800418
419 def play_sound(self, duration_seconds=None, audio_file_path=None):
420 '''
421 Plays a sound file found at |audio_file_path| for |duration_seconds|.
422
423 If |audio_file_path|=None, plays a default audio file.
424 If |duration_seconds|=None, plays audio file in its entirety.
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800425
426 @param duration_seconds: Duration to play sound.
427 @param audio_file_path: Path to the audio file.
Simon Quea4be3442012-11-14 16:36:56 -0800428 '''
429 if not audio_file_path:
430 audio_file_path = '/usr/local/autotest/cros/audio/sine440.wav'
431 duration_arg = ('-d %d' % duration_seconds) if duration_seconds else ''
432 utils.system('aplay %s %s' % (duration_arg, audio_file_path))
Hsin-Yu Chaob443f5d2013-03-12 18:36:18 +0800433
Hsin-Yu Chaoe6bb7932013-03-22 14:08:54 +0800434 def get_play_sine_args(self, channel, odev='default', freq=1000, duration=10,
Hsin-Yu Chaob443f5d2013-03-12 18:36:18 +0800435 sample_size=16):
Hsin-Yu Chaoe6bb7932013-03-22 14:08:54 +0800436 '''Gets the command args to generate a sine wav to play to odev.
Hsin-Yu Chaob443f5d2013-03-12 18:36:18 +0800437
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800438 @param channel: 0 for left, 1 for right; otherwize, mono.
439 @param odev: alsa output device.
440 @param freq: frequency of the generated sine tone.
441 @param duration: duration of the generated sine tone.
442 @param sample_size: output audio sample size. Default to 16.
Hsin-Yu Chaob443f5d2013-03-12 18:36:18 +0800443 '''
Hsin-Yu Chaoe6bb7932013-03-22 14:08:54 +0800444 cmdargs = [self.sox_path, '-b', str(sample_size), '-n', '-t', 'alsa',
445 odev, 'synth', str(duration)]
Hsin-Yu Chaob443f5d2013-03-12 18:36:18 +0800446 if channel == 0:
Hsin-Yu Chaoe6bb7932013-03-22 14:08:54 +0800447 cmdargs += ['sine', str(freq), 'sine', '0']
Hsin-Yu Chaob443f5d2013-03-12 18:36:18 +0800448 elif channel == 1:
Hsin-Yu Chaoe6bb7932013-03-22 14:08:54 +0800449 cmdargs += ['sine', '0', 'sine', str(freq)]
Hsin-Yu Chaob443f5d2013-03-12 18:36:18 +0800450 else:
Hsin-Yu Chaoe6bb7932013-03-22 14:08:54 +0800451 cmdargs += ['sine', str(freq)]
452
453 return cmdargs
454
455 def play_sine(self, channel, odev='default', freq=1000, duration=10,
456 sample_size=16):
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800457 '''Generates a sine wave and plays to odev.
458
459 @param channel: 0 for left, 1 for right; otherwize, mono.
460 @param odev: alsa output device.
461 @param freq: frequency of the generated sine tone.
462 @param duration: duration of the generated sine tone.
463 @param sample_size: output audio sample size. Default to 16.
464 '''
Hsin-Yu Chao1b641072013-03-25 18:23:44 +0800465 cmdargs = self.get_play_sine_args(channel, odev, freq, duration, sample_size)
Hsin-Yu Chaoe6bb7932013-03-22 14:08:54 +0800466 utils.system(' '.join(cmdargs))
Hsin-Yu Chao78c44b22013-04-06 05:33:58 +0800467
468 def create_wav_file(self, prefix=""):
469 '''Creates a unique name for wav file.
470
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800471 The created file name will be preserved in autotest result directory
472 for future analysis.
Hsin-Yu Chao78c44b22013-04-06 05:33:58 +0800473
Hsin-Yu Chao2ecbfe62013-04-06 05:49:27 +0800474 @param prefix: specified file name prefix.
Hsin-Yu Chao78c44b22013-04-06 05:33:58 +0800475 '''
476 filename = "%s-%s.wav" % (prefix, time.time())
477 return os.path.join(self._test.resultsdir, filename)