blob: 175efd724a8e2a234fcc11c3ed0d117b4bdadc24 [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
91 def set_mixer_controls(self, mixer_settings={}, card='0'):
92 '''
93 Sets all mixer controls listed in the mixer settings on card.
94 '''
95 logging.info('Setting mixer control values on %s' % card)
96 for item in mixer_settings:
97 logging.info('Setting %s to %s on card %s' %
98 (item['name'], item['value'], card))
99 cmd = 'amixer -c %s cset name=%s %s'
100 cmd = cmd % (card, item['name'], item['value'])
101 try:
102 utils.system(cmd)
103 except error.CmdError:
104 # A card is allowed not to support all the controls, so don't
105 # fail the test here if we get an error.
106 logging.info('amixer command failed: %s' % cmd)
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800107
Hsinyu Chao2d64e1f2012-05-21 11:18:53 +0800108 def sox_stat_output(self, infile, channel):
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800109 sox_mixer_cmd = self.get_sox_mixer_cmd(infile, channel)
110 stat_cmd = '%s -c 1 %s - -n stat 2>&1' % (self.sox_path,
111 self._sox_format)
112 sox_cmd = '%s | %s' % (sox_mixer_cmd, stat_cmd)
Hsinyu Chao2d64e1f2012-05-21 11:18:53 +0800113 return utils.system_output(sox_cmd, retain_output=True)
114
115 def get_audio_rms(self, sox_output):
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800116 for rms_line in sox_output.split('\n'):
117 m = _SOX_RMS_AMPLITUDE_RE.match(rms_line)
118 if m is not None:
119 return float(m.group(1))
120
Hsinyu Chao2d64e1f2012-05-21 11:18:53 +0800121 def get_rough_freq(self, sox_output):
122 for rms_line in sox_output.split('\n'):
123 m = _SOX_ROUGH_FREQ_RE.match(rms_line)
124 if m is not None:
125 return int(m.group(1))
126
127
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800128 def get_sox_mixer_cmd(self, infile, channel):
129 # Build up a pan value string for the sox command.
130 if channel == 0:
131 pan_values = '1'
132 else:
133 pan_values = '0'
134 for pan_index in range(1, self._num_channels):
135 if channel == pan_index:
136 pan_values = '%s%s' % (pan_values, ',1')
137 else:
138 pan_values = '%s%s' % (pan_values, ',0')
139
140 return '%s -c 2 %s %s -c 1 %s - mixer %s' % (self.sox_path,
141 self._sox_format, infile, self._sox_format, pan_values)
142
143 def noise_reduce_file(self, in_file, noise_file, out_file):
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800144 '''Runs the sox command to noise-reduce in_file using
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800145 the noise profile from noise_file.
146
147 Args:
148 in_file: The file to noise reduce.
149 noise_file: The file containing the noise profile.
150 This can be created by recording silence.
151 out_file: The file contains the noise reduced sound.
152
153 Returns:
154 The name of the file containing the noise-reduced data.
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800155 '''
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800156 prof_cmd = '%s -c 2 %s %s -n noiseprof' % (self.sox_path,
157 _SOX_FORMAT, noise_file)
158 reduce_cmd = ('%s -c 2 %s %s -c 2 %s %s noisered' %
159 (self.sox_path, _SOX_FORMAT, in_file, _SOX_FORMAT, out_file))
160 utils.system('%s | %s' % (prof_cmd, reduce_cmd))
161
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800162 def record_sample(self, tmpfile):
163 '''Records a sample from the default input device.
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800164
165 Args:
166 duration: How long to record in seconds.
167 tmpfile: The file to record to.
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800168 '''
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800169 cmd_rec = 'arecord -D %s -d %f -f dat %s' % (self._input_device,
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800170 self._record_duration, tmpfile)
171 logging.info('Command %s recording now (%fs)' % (cmd_rec,
172 self._record_duration))
Hsinyu Chaof80337a2012-04-07 18:02:29 +0800173 utils.system(cmd_rec)
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800174
175 def loopback_test_channels(self, noise_file, loopback_callback,
Hsinyu Chao2d64e1f2012-05-21 11:18:53 +0800176 check_recorded_callback):
Hsinyu Chao2a7e2f22012-04-18 16:46:43 +0800177 '''Tests loopback on all channels.
178
179 Args:
180 noise_file: The file contains the pre-recorded noise.
181 loopback_callback: The callback to do the loopback for one channel.
182 check_recorded_callback: The callback function to check the
183 calculated RMS value.
184 '''
185 for channel in xrange(self._num_channels):
186 # Temp file for the final noise-reduced file.
187 with tempfile.NamedTemporaryFile(mode='w+t') as reduced_file:
188 # Temp file that records before noise reduction.
189 with tempfile.NamedTemporaryFile(mode='w+t') as tmpfile:
190 record_thread = RecordSampleThread(self, tmpfile.name)
191 record_thread.start()
192 loopback_callback(channel)
193 record_thread.join()
194
195 self.noise_reduce_file(tmpfile.name, noise_file.name,
196 reduced_file.name)
197
Hsinyu Chao2d64e1f2012-05-21 11:18:53 +0800198 sox_output = self.sox_stat_output(reduced_file.name, channel)
199 check_recorded_callback(sox_output)