blob: 22a5fd7d8248ec8856811d8ab8af08f19a474cfc [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
7import subprocess
8
9from autotest_lib.client.cros.audio import cmd_utils
10
Owen Linca365f82013-11-08 16:52:28 +080011SOX_PATH = '/usr/local/bin/sox'
12
Owen Lin7ab45a22013-11-19 17:26:33 +080013def _raw_format_args(channels, bits, rate):
14 args = ['-t', 'raw', '-e', 'signed']
15 args += ['-c', str(channels)]
16 args += ['-b', str(bits)]
17 args += ['-r', str(rate)]
18 return args
19
Owen Linca365f82013-11-08 16:52:28 +080020def generate_sine_tone_cmd(
Owen Lin2013e462013-12-05 17:54:42 +080021 filename, channels=2, bits=16, rate=48000, duration=None, frequence=440,
Owen Linca365f82013-11-08 16:52:28 +080022 gain=None):
23 """Gets a command to generate sine tones at specified ferquencies.
24
Owen Lin7ab45a22013-11-19 17:26:33 +080025 @param filename: The name of the file to store the sine wave in.
26 @param channels: The number of channels.
27 @param bits: The number of bits of each sample.
28 @param rate: The sampling rate.
29 @param duration: The length of the generated sine tone (in seconds).
30 @param frequence: The frequence of the sine wave.
31 @param gain: The gain (in db).
Owen Linca365f82013-11-08 16:52:28 +080032 """
Owen Lin7ab45a22013-11-19 17:26:33 +080033 args = [SOX_PATH, '-n']
34 args += _raw_format_args(channels, bits, rate)
Owen Linca365f82013-11-08 16:52:28 +080035 args.append(filename)
36 args.append('synth')
37 if duration is not None:
38 args.append(str(duration))
39 args += ['sine', str(frequence)]
40 if gain is not None:
41 args += ['gain', str(gain)]
42 return args
Owen Lin7ab45a22013-11-19 17:26:33 +080043
44
45def noise_profile(*arg, **karg):
46 """A helper function to execute the noise_profile_cmd."""
47 return cmd_utils.execute(noise_profile_cmd(*arg, **karg))
48
49
Owen Lin2013e462013-12-05 17:54:42 +080050def noise_profile_cmd(input, output, channels=1, bits=16, rate=48000):
Owen Lin7ab45a22013-11-19 17:26:33 +080051 """Gets the noise profile of the input audio.
52
53 @param input: The input audio.
54 @param output: The file where the output profile will be stored in.
55 @param channels: The number of channels.
56 @param bits: The number of bits of each sample.
57 @param rate: The sampling rate.
58 """
59 args = [SOX_PATH]
60 args += _raw_format_args(channels, bits, rate)
61 args += [input, '-n', 'noiseprof', output]
62 return args
63
64
65def noise_reduce(*args, **kargs):
66 """A helper function to execute the noise_reduce_cmd."""
67 return cmd_utils.execute(noise_reduce_cmd(*args, **kargs))
68
69
70def noise_reduce_cmd(
Owen Lin2013e462013-12-05 17:54:42 +080071 input, output, noise_profile, channels=1, bits=16, rate=48000):
Owen Lin7ab45a22013-11-19 17:26:33 +080072 """Reduce noise in the input audio by the given noise profile.
73
74 @param input: The input audio file.
75 @param ouput: The output file in which the noise reduced audio is stored.
76 @param noise_profile: The noise profile.
77 @param channels: The number of channels.
78 @param bits: The number of bits of each sample.
79 @param rate: The sampling rate.
80 """
81 args = [SOX_PATH]
82 format_args = _raw_format_args(channels, bits, rate)
83 args += format_args
84 args.append(input)
85 # Uses the same format for output.
86 args += format_args
87 args.append(output)
88 args.append('noisered')
89 args.append(noise_profile)
90 return args
91
92
93def extract_channel_cmd(
Owen Lin2013e462013-12-05 17:54:42 +080094 input, output, channel_index, channels=2, bits=16, rate=48000):
Owen Lin7ab45a22013-11-19 17:26:33 +080095 """Extract the specified channel data from the given input audio file.
96
97 @param input: The input audio file.
98 @param output: The output file to which the extracted channel is stored
99 @param channel_index: The index of the channel to be extracted.
100 Note: 1 for the first channel.
101 @param channels: The number of channels.
102 @param bits: The number of bits of each sample.
103 @param rate: The sampling rate.
104 """
105 args = [SOX_PATH]
106 args += _raw_format_args(channels, bits, rate)
107 args.append(input)
108 args += ['-t', 'raw', output]
109 args += ['remix', str(channel_index)]
110 return args
111
112
Owen Lin2013e462013-12-05 17:54:42 +0800113def stat_cmd(input, channels=1, bits=16, rate=44100):
Owen Lin7ab45a22013-11-19 17:26:33 +0800114 """Get statistical information about the input audio data.
115
116 The statistics will be output to standard error.
117
118 @param input: The input audio file.
119 @param channels: The number of channels.
120 @param bits: The number of bits of each sample.
121 @param rate: The sampling rate.
122 """
123 args = [SOX_PATH]
124 args += _raw_format_args(channels, bits, rate)
125 args += [input, '-n', 'stat']
126 return args
127
128
129def get_stat(*args, **kargs):
130 """A helper function to execute the stat_cmd.
131
132 It returns the statistical information (in text) read from the standard
133 error.
134 """
135 p = cmd_utils.popen(stat_cmd(*args, **kargs), stderr=subprocess.PIPE)
136
137 #The output is read from the stderr instead of stdout
138 stat_output = p.stderr.read()
139 cmd_utils.wait_and_check_returncode(p)
140 return parse_stat_output(stat_output)
141
142
143_SOX_STAT_ATTR_MAP = {
144 'Samples read': ('sameple_count', int),
145 'Length (seconds)': ('length', float),
146 'RMS amplitude': ('rms', float),
147 'Rough frequency': ('rough_frequency', float)}
148
149_RE_STAT_LINE = re.compile('(.*):(.*)')
150
151class _SOX_STAT:
152 def __str__(self):
153 return str(vars(self))
154
155
156def _remove_redundant_spaces(value):
157 return ' '.join(value.split()).strip()
158
159
160def parse_stat_output(stat_output):
161 """A helper function to parses the stat_cmd's output to get a python object
162 for easy access to the statistics.
163
164 It returns a python object with the following attributes:
165 .sample_count: The number of the audio samples.
166 .length: The length of the audio (in seconds).
167 .rms: The RMS value of the audio.
168 .rough_frequency: The rough frequency of the audio (in Hz).
169
170 @param stat_output: The statistics ouput to be parsed.
171 """
172 stat = _SOX_STAT()
173
174 for line in stat_output.splitlines():
175 match = _RE_STAT_LINE.match(line)
176 if not match:
177 continue
178 key, value = (_remove_redundant_spaces(x) for x in match.groups())
179 attr, convfun = _SOX_STAT_ATTR_MAP.get(key, (None, None))
180 if attr:
181 setattr(stat, attr, convfun(value))
182
183 if not all(hasattr(stat, x[0]) for x in _SOX_STAT_ATTR_MAP.values()):
184 logging.error('stat_output: %s', stat_output)
185 raise RuntimeError('missing entries: ' + str(stat))
186
187 return stat