blob: 4be538bb35abb633782543bedd6e69c59aafbc94 [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 tempfile
10import threading
Hsinyu Chao4b8300e2011-11-15 13:07:32 -080011
12from autotest_lib.client.bin import utils
13from autotest_lib.client.common_lib import error
14
15LD_LIBRARY_PATH = 'LD_LIBRARY_PATH'
16
Hsinyu Chaof80337a2012-04-07 18:02:29 +080017_DEFAULT_NUM_CHANNELS = 2
Hsinyu Chao10ef3b92012-07-02 22:42:30 +080018_DEFAULT_INPUT_DEVICE = 'hw:0,0'
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +080019_DEFAULT_RECORD_DURATION = 10
Hsinyu Chaof80337a2012-04-07 18:02:29 +080020_DEFAULT_SOX_FORMAT = '-t raw -b 16 -e signed -r 48000 -L'
21
22_SOX_RMS_AMPLITUDE_RE = re.compile('RMS\s+amplitude:\s+(.+)')
Hsinyu Chao2d64e1f2012-05-21 11:18:53 +080023_SOX_ROUGH_FREQ_RE = re.compile('Rough\s+frequency:\s+(.+)')
Hsinyu Chaof80337a2012-04-07 18:02:29 +080024_SOX_FORMAT = '-t raw -b 16 -e signed -r 48000 -L'
25
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +080026
27class RecordSampleThread(threading.Thread):
28 '''Wraps the execution of arecord in a thread.'''
29 def __init__(self, audio, recordfile):
30 threading.Thread.__init__(self)
31 self._audio = audio
32 self._recordfile = recordfile
33
34 def run(self):
35 self._audio.record_sample(self._recordfile)
36
37
Hsinyu Chao4b8300e2011-11-15 13:07:32 -080038class AudioHelper(object):
39 '''
40 A helper class contains audio related utility functions.
41 '''
Hsinyu Chaof80337a2012-04-07 18:02:29 +080042 def __init__(self, test, sox_format=_DEFAULT_SOX_FORMAT,
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +080043 input_device=_DEFAULT_INPUT_DEVICE,
44 record_duration=_DEFAULT_RECORD_DURATION,
45 num_channels = _DEFAULT_NUM_CHANNELS):
Hsinyu Chao4b8300e2011-11-15 13:07:32 -080046 self._test = test
Hsinyu Chaof80337a2012-04-07 18:02:29 +080047 self._sox_format = sox_format
48 self._input_device = input_device
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +080049 self._record_duration = record_duration
50 self._num_channels = num_channels
Hsinyu Chao4b8300e2011-11-15 13:07:32 -080051
52 def setup_deps(self, deps):
53 '''
54 Sets up audio related dependencies.
55 '''
56 for dep in deps:
57 if dep == 'test_tones':
58 dep_dir = os.path.join(self._test.autodir, 'deps', dep)
59 self._test.job.install_pkg(dep, 'dep', dep_dir)
60 self.test_tones_path = os.path.join(dep_dir, 'src', dep)
61 elif dep == 'audioloop':
62 dep_dir = os.path.join(self._test.autodir, 'deps', dep)
63 self._test.job.install_pkg(dep, 'dep', dep_dir)
64 self.audioloop_path = os.path.join(dep_dir, 'src',
65 'looptest')
66 elif dep == 'sox':
67 dep_dir = os.path.join(self._test.autodir, 'deps', dep)
68 self._test.job.install_pkg(dep, 'dep', dep_dir)
69 self.sox_path = os.path.join(dep_dir, 'bin', dep)
70 self.sox_lib_path = os.path.join(dep_dir, 'lib')
71 if os.environ.has_key(LD_LIBRARY_PATH):
72 paths = os.environ[LD_LIBRARY_PATH].split(':')
73 if not self.sox_lib_path in paths:
74 paths.append(self.sox_lib_path)
75 os.environ[LD_LIBRARY_PATH] = ':'.join(paths)
76 else:
77 os.environ[LD_LIBRARY_PATH] = self.sox_lib_path
78
79 def cleanup_deps(self, deps):
80 '''
81 Cleans up environments which has been setup for dependencies.
82 '''
83 for dep in deps:
84 if dep == 'sox':
85 if (os.environ.has_key(LD_LIBRARY_PATH)
86 and hasattr(self, 'sox_lib_path')):
87 paths = filter(lambda x: x != self.sox_lib_path,
88 os.environ[LD_LIBRARY_PATH].split(':'))
89 os.environ[LD_LIBRARY_PATH] = ':'.join(paths)
90
Derek Basehoree973ce42012-07-10 23:38:32 -070091 def set_volume_levels(self, volume, capture):
92 '''
93 Sets the volume and capture gain through cras_test_client
94 '''
95 logging.info('Setting volume level to %d' % volume)
96 utils.system('/usr/bin/cras_test_client --volume %d' % volume)
97 logging.info('Setting capture gain to %d' % capture)
98 utils.system('/usr/bin/cras_test_client --capture_gain %d' % capture)
99 utils.system('/usr/bin/cras_test_client --dump_server_info')
100 utils.system('amixer -c 0 contents')
101
Hsinyu Chao4b8300e2011-11-15 13:07:32 -0800102 def set_mixer_controls(self, mixer_settings={}, card='0'):
103 '''
104 Sets all mixer controls listed in the mixer settings on card.
105 '''
106 logging.info('Setting mixer control values on %s' % card)
107 for item in mixer_settings:
108 logging.info('Setting %s to %s on card %s' %
109 (item['name'], item['value'], card))
110 cmd = 'amixer -c %s cset name=%s %s'
111 cmd = cmd % (card, item['name'], item['value'])
112 try:
113 utils.system(cmd)
114 except error.CmdError:
115 # A card is allowed not to support all the controls, so don't
116 # fail the test here if we get an error.
117 logging.info('amixer command failed: %s' % cmd)
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800118
Hsinyu Chao2d64e1f2012-05-21 11:18:53 +0800119 def sox_stat_output(self, infile, channel):
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800120 sox_mixer_cmd = self.get_sox_mixer_cmd(infile, channel)
121 stat_cmd = '%s -c 1 %s - -n stat 2>&1' % (self.sox_path,
122 self._sox_format)
123 sox_cmd = '%s | %s' % (sox_mixer_cmd, stat_cmd)
Hsinyu Chao2d64e1f2012-05-21 11:18:53 +0800124 return utils.system_output(sox_cmd, retain_output=True)
125
126 def get_audio_rms(self, sox_output):
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800127 for rms_line in sox_output.split('\n'):
128 m = _SOX_RMS_AMPLITUDE_RE.match(rms_line)
129 if m is not None:
130 return float(m.group(1))
131
Hsinyu Chao2d64e1f2012-05-21 11:18:53 +0800132 def get_rough_freq(self, sox_output):
133 for rms_line in sox_output.split('\n'):
134 m = _SOX_ROUGH_FREQ_RE.match(rms_line)
135 if m is not None:
136 return int(m.group(1))
137
138
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800139 def get_sox_mixer_cmd(self, infile, channel):
140 # Build up a pan value string for the sox command.
141 if channel == 0:
142 pan_values = '1'
143 else:
144 pan_values = '0'
145 for pan_index in range(1, self._num_channels):
146 if channel == pan_index:
147 pan_values = '%s%s' % (pan_values, ',1')
148 else:
149 pan_values = '%s%s' % (pan_values, ',0')
150
151 return '%s -c 2 %s %s -c 1 %s - mixer %s' % (self.sox_path,
152 self._sox_format, infile, self._sox_format, pan_values)
153
154 def noise_reduce_file(self, in_file, noise_file, out_file):
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800155 '''Runs the sox command to noise-reduce in_file using
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800156 the noise profile from noise_file.
157
158 Args:
159 in_file: The file to noise reduce.
160 noise_file: The file containing the noise profile.
161 This can be created by recording silence.
162 out_file: The file contains the noise reduced sound.
163
164 Returns:
165 The name of the file containing the noise-reduced data.
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800166 '''
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800167 prof_cmd = '%s -c 2 %s %s -n noiseprof' % (self.sox_path,
168 _SOX_FORMAT, noise_file)
169 reduce_cmd = ('%s -c 2 %s %s -c 2 %s %s noisered' %
170 (self.sox_path, _SOX_FORMAT, in_file, _SOX_FORMAT, out_file))
171 utils.system('%s | %s' % (prof_cmd, reduce_cmd))
172
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800173 def record_sample(self, tmpfile):
174 '''Records a sample from the default input device.
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800175
176 Args:
177 duration: How long to record in seconds.
178 tmpfile: The file to record to.
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800179 '''
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800180 cmd_rec = 'arecord -D %s -d %f -f dat %s' % (self._input_device,
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800181 self._record_duration, tmpfile)
182 logging.info('Command %s recording now (%fs)' % (cmd_rec,
183 self._record_duration))
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800184 utils.system(cmd_rec)
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800185
186 def loopback_test_channels(self, noise_file, loopback_callback,
Hsinyu Chao2d64e1f2012-05-21 11:18:53 +0800187 check_recorded_callback):
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800188 '''Tests loopback on all channels.
189
190 Args:
191 noise_file: The file contains the pre-recorded noise.
192 loopback_callback: The callback to do the loopback for one channel.
193 check_recorded_callback: The callback function to check the
194 calculated RMS value.
195 '''
196 for channel in xrange(self._num_channels):
197 # Temp file for the final noise-reduced file.
198 with tempfile.NamedTemporaryFile(mode='w+t') as reduced_file:
199 # Temp file that records before noise reduction.
200 with tempfile.NamedTemporaryFile(mode='w+t') as tmpfile:
201 record_thread = RecordSampleThread(self, tmpfile.name)
202 record_thread.start()
203 loopback_callback(channel)
204 record_thread.join()
205
206 self.noise_reduce_file(tmpfile.name, noise_file.name,
207 reduced_file.name)
208
Hsinyu Chao2d64e1f2012-05-21 11:18:53 +0800209 sox_output = self.sox_stat_output(reduced_file.name, channel)
210 check_recorded_callback(sox_output)