blob: 4b86292e840ccdc7453f1946e33a682fe1108d2c [file] [log] [blame]
Owen Linca365f82013-11-08 16:52:28 +08001# Copyright (c) 2013 The Chromium 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
Owen Lin7ab45a22013-11-19 17:26:33 +08005import logging
6import re
Owen Lin7ab45a22013-11-19 17:26:33 +08007
8from autotest_lib.client.cros.audio import cmd_utils
9
Cheng-Yi Chiang17a25272014-11-28 19:05:13 +080010SOX_PATH = 'sox'
Owen Linca365f82013-11-08 16:52:28 +080011
Owen Lin7ab45a22013-11-19 17:26:33 +080012def _raw_format_args(channels, bits, rate):
Cheng-Yi Chiang547d61e2016-09-07 00:45:03 +080013 """Gets raw format args used in sox.
14
15 @param channels: Number of channels.
16 @param bits: Bit length for a sample.
17 @param rate: Sampling rate.
18
19 @returns: A list of args.
20
21 """
Owen Lin7ab45a22013-11-19 17:26:33 +080022 args = ['-t', 'raw', '-e', 'signed']
Cheng-Yi Chiang547d61e2016-09-07 00:45:03 +080023 args += _format_args(channels, bits, rate)
Owen Lin7ab45a22013-11-19 17:26:33 +080024 return args
25
Cheng-Yi Chiang547d61e2016-09-07 00:45:03 +080026
27def _format_args(channels, bits, rate):
28 """Gets format args used in sox.
29
30 @param channels: Number of channels.
31 @param bits: Bit length for a sample.
32 @param rate: Sampling rate.
33
34 @returns: A list of args.
35
36 """
37 return ['-c', str(channels), '-b', str(bits), '-r', str(rate)]
38
39
Owen Linca365f82013-11-08 16:52:28 +080040def generate_sine_tone_cmd(
Owen Lin2013e462013-12-05 17:54:42 +080041 filename, channels=2, bits=16, rate=48000, duration=None, frequence=440,
Owen Linca365f82013-11-08 16:52:28 +080042 gain=None):
43 """Gets a command to generate sine tones at specified ferquencies.
44
Owen Lin7ab45a22013-11-19 17:26:33 +080045 @param filename: The name of the file to store the sine wave in.
46 @param channels: The number of channels.
47 @param bits: The number of bits of each sample.
48 @param rate: The sampling rate.
49 @param duration: The length of the generated sine tone (in seconds).
50 @param frequence: The frequence of the sine wave.
51 @param gain: The gain (in db).
Owen Linca365f82013-11-08 16:52:28 +080052 """
Owen Lin7ab45a22013-11-19 17:26:33 +080053 args = [SOX_PATH, '-n']
54 args += _raw_format_args(channels, bits, rate)
Owen Linca365f82013-11-08 16:52:28 +080055 args.append(filename)
56 args.append('synth')
57 if duration is not None:
58 args.append(str(duration))
59 args += ['sine', str(frequence)]
60 if gain is not None:
61 args += ['gain', str(gain)]
62 return args
Owen Lin7ab45a22013-11-19 17:26:33 +080063
64
65def noise_profile(*arg, **karg):
66 """A helper function to execute the noise_profile_cmd."""
67 return cmd_utils.execute(noise_profile_cmd(*arg, **karg))
68
69
Owen Lin2013e462013-12-05 17:54:42 +080070def noise_profile_cmd(input, output, channels=1, bits=16, rate=48000):
Owen Lin7ab45a22013-11-19 17:26:33 +080071 """Gets the noise profile of the input audio.
72
73 @param input: The input audio.
74 @param output: The file where the output profile will be stored in.
75 @param channels: The number of channels.
76 @param bits: The number of bits of each sample.
77 @param rate: The sampling rate.
78 """
79 args = [SOX_PATH]
80 args += _raw_format_args(channels, bits, rate)
81 args += [input, '-n', 'noiseprof', output]
82 return args
83
84
85def noise_reduce(*args, **kargs):
86 """A helper function to execute the noise_reduce_cmd."""
87 return cmd_utils.execute(noise_reduce_cmd(*args, **kargs))
88
89
90def noise_reduce_cmd(
Owen Lin2013e462013-12-05 17:54:42 +080091 input, output, noise_profile, channels=1, bits=16, rate=48000):
Owen Lin7ab45a22013-11-19 17:26:33 +080092 """Reduce noise in the input audio by the given noise profile.
93
94 @param input: The input audio file.
95 @param ouput: The output file in which the noise reduced audio is stored.
96 @param noise_profile: The noise profile.
97 @param channels: The number of channels.
98 @param bits: The number of bits of each sample.
99 @param rate: The sampling rate.
100 """
101 args = [SOX_PATH]
102 format_args = _raw_format_args(channels, bits, rate)
103 args += format_args
104 args.append(input)
105 # Uses the same format for output.
106 args += format_args
107 args.append(output)
108 args.append('noisered')
109 args.append(noise_profile)
110 return args
111
112
113def extract_channel_cmd(
Owen Lin2013e462013-12-05 17:54:42 +0800114 input, output, channel_index, channels=2, bits=16, rate=48000):
Owen Lin7ab45a22013-11-19 17:26:33 +0800115 """Extract the specified channel data from the given input audio file.
116
117 @param input: The input audio file.
118 @param output: The output file to which the extracted channel is stored
119 @param channel_index: The index of the channel to be extracted.
120 Note: 1 for the first channel.
121 @param channels: The number of channels.
122 @param bits: The number of bits of each sample.
123 @param rate: The sampling rate.
124 """
125 args = [SOX_PATH]
126 args += _raw_format_args(channels, bits, rate)
127 args.append(input)
128 args += ['-t', 'raw', output]
129 args += ['remix', str(channel_index)]
130 return args
131
132
Owen Lin2013e462013-12-05 17:54:42 +0800133def stat_cmd(input, channels=1, bits=16, rate=44100):
Owen Lin7ab45a22013-11-19 17:26:33 +0800134 """Get statistical information about the input audio data.
135
136 The statistics will be output to standard error.
137
138 @param input: The input audio file.
139 @param channels: The number of channels.
140 @param bits: The number of bits of each sample.
141 @param rate: The sampling rate.
142 """
143 args = [SOX_PATH]
144 args += _raw_format_args(channels, bits, rate)
145 args += [input, '-n', 'stat']
146 return args
147
148
149def get_stat(*args, **kargs):
150 """A helper function to execute the stat_cmd.
151
152 It returns the statistical information (in text) read from the standard
153 error.
154 """
Owen Linad6610a2013-12-13 11:20:48 +0800155 p = cmd_utils.popen(stat_cmd(*args, **kargs), stderr=cmd_utils.PIPE)
Owen Lin7ab45a22013-11-19 17:26:33 +0800156
157 #The output is read from the stderr instead of stdout
158 stat_output = p.stderr.read()
159 cmd_utils.wait_and_check_returncode(p)
160 return parse_stat_output(stat_output)
161
162
163_SOX_STAT_ATTR_MAP = {
164 'Samples read': ('sameple_count', int),
165 'Length (seconds)': ('length', float),
166 'RMS amplitude': ('rms', float),
167 'Rough frequency': ('rough_frequency', float)}
168
169_RE_STAT_LINE = re.compile('(.*):(.*)')
170
171class _SOX_STAT:
172 def __str__(self):
173 return str(vars(self))
174
175
176def _remove_redundant_spaces(value):
177 return ' '.join(value.split()).strip()
178
179
180def parse_stat_output(stat_output):
181 """A helper function to parses the stat_cmd's output to get a python object
182 for easy access to the statistics.
183
184 It returns a python object with the following attributes:
185 .sample_count: The number of the audio samples.
186 .length: The length of the audio (in seconds).
187 .rms: The RMS value of the audio.
188 .rough_frequency: The rough frequency of the audio (in Hz).
189
190 @param stat_output: The statistics ouput to be parsed.
191 """
192 stat = _SOX_STAT()
193
194 for line in stat_output.splitlines():
195 match = _RE_STAT_LINE.match(line)
196 if not match:
197 continue
198 key, value = (_remove_redundant_spaces(x) for x in match.groups())
199 attr, convfun = _SOX_STAT_ATTR_MAP.get(key, (None, None))
200 if attr:
201 setattr(stat, attr, convfun(value))
202
203 if not all(hasattr(stat, x[0]) for x in _SOX_STAT_ATTR_MAP.values()):
204 logging.error('stat_output: %s', stat_output)
205 raise RuntimeError('missing entries: ' + str(stat))
206
207 return stat
Cheng-Yi Chiangbeafe572015-01-12 17:23:24 +0800208
209
Cheng-Yi Chiang13ac4682015-11-24 15:22:36 +0800210def convert_raw_file(path_src, channels_src, bits_src, rate_src,
211 path_dst):
212 """Converts a raw file to a new format.
213
214 @param path_src: The path to the source file.
215 @param channels_src: The channel number of the source file.
216 @param bits_src: The size of sample in bits of the source file.
217 @param rate_src: The sampling rate of the source file.
218 @param path_dst: The path to the destination file. The file name determines
219 the new file format.
220
221 """
222 sox_cmd = [SOX_PATH]
223 sox_cmd += _raw_format_args(channels_src, bits_src, rate_src)
224 sox_cmd += [path_src]
225 sox_cmd += [path_dst]
226 cmd_utils.execute(sox_cmd)
227
228
Cheng-Yi Chiangbeafe572015-01-12 17:23:24 +0800229def convert_format(path_src, channels_src, bits_src, rate_src,
230 path_dst, channels_dst, bits_dst, rate_dst,
Cheng-Yi Chiang547d61e2016-09-07 00:45:03 +0800231 volume_scale, use_src_header=False, use_dst_header=False):
Cheng-Yi Chiangbeafe572015-01-12 17:23:24 +0800232 """Converts a raw file to a new format.
233
234 @param path_src: The path to the source file.
235 @param channels_src: The channel number of the source file.
236 @param bits_src: The size of sample in bits of the source file.
237 @param rate_src: The sampling rate of the source file.
238 @param path_dst: The path to the destination file.
239 @param channels_dst: The channel number of the destination file.
240 @param bits_dst: The size of sample in bits of the destination file.
241 @param rate_dst: The sampling rate of the destination file.
242 @param volume_scale: A float for volume scale used in sox command.
243 E.g. 1.0 is the same. 0.5 to scale volume by
244 half. -1.0 to invert the data.
Cheng-Yi Chiangcad095c2016-08-11 17:43:02 +0800245 @param use_src_header: True to use header from source file and skip
246 specifying channel, sample format, and rate for
247 source. False otherwise.
Cheng-Yi Chiang547d61e2016-09-07 00:45:03 +0800248 @param use_dst_header: True to use header for dst file. False to treat
249 dst file as a raw file.
Cheng-Yi Chiangbeafe572015-01-12 17:23:24 +0800250
251 """
252 sox_cmd = [SOX_PATH]
Cheng-Yi Chiang547d61e2016-09-07 00:45:03 +0800253
Cheng-Yi Chiangcad095c2016-08-11 17:43:02 +0800254 if not use_src_header:
255 sox_cmd += _raw_format_args(channels_src, bits_src, rate_src)
Cheng-Yi Chiangbeafe572015-01-12 17:23:24 +0800256 sox_cmd += ['-v', '%f' % volume_scale]
257 sox_cmd += [path_src]
Cheng-Yi Chiang547d61e2016-09-07 00:45:03 +0800258
259 if not use_dst_header:
260 sox_cmd += _raw_format_args(channels_dst, bits_dst, rate_dst)
261 else:
262 sox_cmd += _format_args(channels_dst, bits_dst, rate_dst)
Cheng-Yi Chiangbeafe572015-01-12 17:23:24 +0800263 sox_cmd += [path_dst]
Cheng-Yi Chiang547d61e2016-09-07 00:45:03 +0800264
Cheng-Yi Chiangbeafe572015-01-12 17:23:24 +0800265 cmd_utils.execute(sox_cmd)
Cheng-Yi Chiang2ac8d9a2015-01-12 17:32:02 +0800266
267
268def lowpass_filter(path_src, channels_src, bits_src, rate_src,
269 path_dst, frequency):
270 """Passes a raw file to a lowpass filter.
271
272 @param path_src: The path to the source file.
273 @param channels_src: The channel number of the source file.
274 @param bits_src: The size of sample in bits of the source file.
275 @param rate_src: The sampling rate of the source file.
276 @param path_dst: The path to the destination file.
277 @param frequency: A float for frequency used in sox command. The 3dB
278 frequency of the lowpass filter. Checks manual of sox
279 command for detail.
280
281 """
282 sox_cmd = [SOX_PATH]
283 sox_cmd += _raw_format_args(channels_src, bits_src, rate_src)
284 sox_cmd += [path_src]
285 sox_cmd += _raw_format_args(channels_src, bits_src, rate_src)
286 sox_cmd += [path_dst]
287 sox_cmd += ['lowpass', '-2', str(frequency)]
288 cmd_utils.execute(sox_cmd)