blob: 8ad820e932c34a94bcdc6f5c6da2e25a35c94109 [file] [log] [blame]
kjellander8f8d1a02017-03-06 04:01:16 -08001#!/usr/bin/env python
2# Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
3#
4# Use of this source code is governed by a BSD-style license
5# that can be found in the LICENSE file in the root of the source
6# tree. An additional intellectual property rights grant can be found
7# in the file PATENTS. All contributing project authors may
8# be found in the AUTHORS file in the root of the source tree.
9
10"""
11This script is the wrapper that runs the low-bandwidth audio test.
12
13After running the test, post-process steps for calculating audio quality of the
14output files will be performed.
15"""
16
17import argparse
oprypinf2501002017-04-12 05:00:56 -070018import collections
Edward Lemurb4017712018-01-15 14:21:09 +010019import json
kjellander8f8d1a02017-03-06 04:01:16 -080020import logging
21import os
oprypin92220ff2017-03-23 03:40:03 -070022import re
oprypin6d305ba2017-03-30 04:01:30 -070023import shutil
kjellander8f8d1a02017-03-06 04:01:16 -080024import subprocess
25import sys
26
27
28SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
Henrik Kjellander5a6aa4f2017-09-15 09:31:54 +020029SRC_DIR = os.path.normpath(os.path.join(SCRIPT_DIR, os.pardir, os.pardir))
kjellander8f8d1a02017-03-06 04:01:16 -080030
Edward Lemurb0250f02017-10-04 14:41:17 +020031NO_TOOLS_ERROR_MESSAGE = (
32 'Could not find PESQ or POLQA at %s.\n'
33 '\n'
34 'To fix this run:\n'
35 ' python %s %s\n'
36 '\n'
37 'Note that these tools are Google-internal due to licensing, so in order to '
38 'use them you will have to get your own license and manually put them in the '
39 'right location.\n'
40 'See https://cs.chromium.org/chromium/src/third_party/webrtc/tools_webrtc/'
41 'download_tools.py?rcl=bbceb76f540159e2dba0701ac03c514f01624130&l=13')
42
kjellander8f8d1a02017-03-06 04:01:16 -080043
oprypin92220ff2017-03-23 03:40:03 -070044def _LogCommand(command):
45 logging.info('Running %r', command)
46 return command
kjellander8f8d1a02017-03-06 04:01:16 -080047
48
49def _ParseArgs():
50 parser = argparse.ArgumentParser(description='Run low-bandwidth audio tests.')
51 parser.add_argument('build_dir',
52 help='Path to the build directory (e.g. out/Release).')
oprypin92220ff2017-03-23 03:40:03 -070053 parser.add_argument('--remove', action='store_true',
54 help='Remove output audio files after testing.')
oprypin6d305ba2017-03-30 04:01:30 -070055 parser.add_argument('--android', action='store_true',
56 help='Perform the test on a connected Android device instead.')
57 parser.add_argument('--adb-path', help='Path to adb binary.', default='adb')
Edward Lesmes9599fd42018-03-12 16:43:05 -040058 parser.add_argument('--num-retries', default='0',
Edward Lesmes5b9c6842018-03-09 13:07:22 -050059 help='Number of times to retry the test on Android.')
Oleh Prypin637b0b52018-09-21 17:16:06 +020060 parser.add_argument('--isolated-script-test-perf-output', default=None,
61 help='Path to store perf results in chartjson format.')
62 parser.add_argument('--isolated-script-test-output', default=None,
63 help='Path to output an empty JSON file which Chromium infra requires.')
Edward Lemur7e3b5692017-10-04 17:03:16 +020064
65 # Ignore Chromium-specific flags
Edward Lemurd8b041c2018-01-16 14:30:28 +010066 parser.add_argument('--test-launcher-summary-output',
67 type=str, default=None)
kjellander8f8d1a02017-03-06 04:01:16 -080068 args = parser.parse_args()
Edward Lemur7e3b5692017-10-04 17:03:16 +020069
kjellander8f8d1a02017-03-06 04:01:16 -080070 return args
71
72
oprypin92220ff2017-03-23 03:40:03 -070073def _GetPlatform():
74 if sys.platform == 'win32':
75 return 'win'
76 elif sys.platform == 'darwin':
77 return 'mac'
78 elif sys.platform.startswith('linux'):
79 return 'linux'
80
81
Edward Lemurb0250f02017-10-04 14:41:17 +020082def _GetExtension():
83 return '.exe' if sys.platform == 'win32' else ''
84
85
86def _GetPathToTools():
Henrik Kjellander90fd7d82017-05-09 08:30:10 +020087 tools_dir = os.path.join(SRC_DIR, 'tools_webrtc')
oprypin92220ff2017-03-23 03:40:03 -070088 toolchain_dir = os.path.join(tools_dir, 'audio_quality')
89
Edward Lemurb0250f02017-10-04 14:41:17 +020090 platform = _GetPlatform()
91 ext = _GetExtension()
Edward Lemurbb1222f2017-10-03 12:33:38 +000092
Edward Lemurb0250f02017-10-04 14:41:17 +020093 pesq_path = os.path.join(toolchain_dir, platform, 'pesq' + ext)
94 if not os.path.isfile(pesq_path):
95 pesq_path = None
96
97 polqa_path = os.path.join(toolchain_dir, platform, 'PolqaOem64' + ext)
98 if not os.path.isfile(polqa_path):
99 polqa_path = None
100
101 if (platform != 'mac' and not polqa_path) or not pesq_path:
102 logging.error(NO_TOOLS_ERROR_MESSAGE,
103 toolchain_dir,
104 os.path.join(tools_dir, 'download_tools.py'),
105 toolchain_dir)
106
oprypinf2501002017-04-12 05:00:56 -0700107 return pesq_path, polqa_path
oprypin92220ff2017-03-23 03:40:03 -0700108
109
oprypinabd101b2017-04-06 23:21:30 -0700110def ExtractTestRuns(lines, echo=False):
111 """Extracts information about tests from the output of a test runner.
112
Artem Titovb1f2d602019-07-10 14:40:58 +0200113 Produces tuples
114 (android_device, test_name, reference_file, degraded_file, cur_perf_results).
oprypinabd101b2017-04-06 23:21:30 -0700115 """
116 for line in lines:
117 if echo:
118 sys.stdout.write(line)
119
120 # Output from Android has a prefix with the device name.
121 android_prefix_re = r'(?:I\b.+\brun_tests_on_device\((.+?)\)\s*)?'
Artem Titovb1f2d602019-07-10 14:40:58 +0200122 test_re = r'^' + android_prefix_re + (r'TEST (\w+) ([^ ]+?) ([^\s]+)'
123 r' ?([^\s]+)?\s*$')
oprypinabd101b2017-04-06 23:21:30 -0700124
125 match = re.search(test_re, line)
126 if match:
127 yield match.groups()
128
129
130def _GetFile(file_path, out_dir, move=False,
131 android=False, adb_prefix=('adb',)):
oprypin6d305ba2017-03-30 04:01:30 -0700132 out_file_name = os.path.basename(file_path)
133 out_file_path = os.path.join(out_dir, out_file_name)
134
135 if android:
oprypinabd101b2017-04-06 23:21:30 -0700136 # Pull the file from the connected Android device.
137 adb_command = adb_prefix + ('pull', file_path, out_dir)
oprypin6d305ba2017-03-30 04:01:30 -0700138 subprocess.check_call(_LogCommand(adb_command))
oprypinabd101b2017-04-06 23:21:30 -0700139 if move:
140 # Remove that file.
141 adb_command = adb_prefix + ('shell', 'rm', file_path)
142 subprocess.check_call(_LogCommand(adb_command))
oprypin6d305ba2017-03-30 04:01:30 -0700143 elif os.path.abspath(file_path) != os.path.abspath(out_file_path):
oprypinabd101b2017-04-06 23:21:30 -0700144 if move:
145 shutil.move(file_path, out_file_path)
146 else:
147 shutil.copy(file_path, out_file_path)
oprypin6d305ba2017-03-30 04:01:30 -0700148
149 return out_file_path
150
151
oprypinf2501002017-04-12 05:00:56 -0700152def _RunPesq(executable_path, reference_file, degraded_file,
153 sample_rate_hz=16000):
154 directory = os.path.dirname(reference_file)
155 assert os.path.dirname(degraded_file) == directory
156
157 # Analyze audio.
158 command = [executable_path, '+%d' % sample_rate_hz,
159 os.path.basename(reference_file),
160 os.path.basename(degraded_file)]
161 # Need to provide paths in the current directory due to a bug in PESQ:
162 # On Mac, for some 'path/to/file.wav', if 'file.wav' is longer than
163 # 'path/to', PESQ crashes.
164 out = subprocess.check_output(_LogCommand(command),
165 cwd=directory, stderr=subprocess.STDOUT)
166
167 # Find the scores in stdout of PESQ.
168 match = re.search(
169 r'Prediction \(Raw MOS, MOS-LQO\):\s+=\s+([\d.]+)\s+([\d.]+)', out)
170 if match:
171 raw_mos, _ = match.groups()
172
173 return {'pesq_mos': (raw_mos, 'score')}
174 else:
175 logging.error('PESQ: %s', out.splitlines()[-1])
176 return {}
177
178
179def _RunPolqa(executable_path, reference_file, degraded_file):
180 # Analyze audio.
181 command = [executable_path, '-q', '-LC', 'NB',
182 '-Ref', reference_file, '-Test', degraded_file]
Edward Lemurb0250f02017-10-04 14:41:17 +0200183 process = subprocess.Popen(_LogCommand(command),
184 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
oprypinf2501002017-04-12 05:00:56 -0700185 out, err = process.communicate()
186
187 # Find the scores in stdout of POLQA.
188 match = re.search(r'\bMOS-LQO:\s+([\d.]+)', out)
189
190 if process.returncode != 0 or not match:
191 if process.returncode == 2:
192 logging.warning('%s (2)', err.strip())
193 logging.warning('POLQA license error, skipping test.')
194 else:
195 logging.error('%s (%d)', err.strip(), process.returncode)
196 return {}
197
198 mos_lqo, = match.groups()
199 return {'polqa_mos_lqo': (mos_lqo, 'score')}
200
201
Edward Lemurb4017712018-01-15 14:21:09 +0100202def _AddChart(charts, metric, test_name, value, units):
203 chart = charts.setdefault(metric, {})
204 chart[test_name] = {
205 "type": "scalar",
206 "value": value,
207 "units": units,
208 }
209
210
Artem Titovb1f2d602019-07-10 14:40:58 +0200211def _AddRunPerfResults(charts, run_perf_results_file):
212 with open(run_perf_results_file, 'rb') as f:
213 per_run_perf_results = json.load(f)
214 if 'charts' not in per_run_perf_results:
215 return
216 for metric, cases in per_run_perf_results['charts'].items():
217 chart = charts.setdefault(metric, {})
218 for case_name, case_value in cases.items():
219 if case_name in chart:
220 logging.error('Overriding results for %s/%s', metric, case_name)
221 chart[case_name] = case_value
222
223
224Analyzer = collections.namedtuple('Analyzer', ['name', 'func', 'executable',
oprypinf2501002017-04-12 05:00:56 -0700225 'sample_rate_hz'])
226
227
kjellander8f8d1a02017-03-06 04:01:16 -0800228def main():
229 # pylint: disable=W0101
230 logging.basicConfig(level=logging.INFO)
231
232 args = _ParseArgs()
233
Edward Lemurb0250f02017-10-04 14:41:17 +0200234 pesq_path, polqa_path = _GetPathToTools()
235 if pesq_path is None:
236 return 1
kjellander8f8d1a02017-03-06 04:01:16 -0800237
oprypin6d305ba2017-03-30 04:01:30 -0700238 out_dir = os.path.join(args.build_dir, '..')
239 if args.android:
240 test_command = [os.path.join(args.build_dir, 'bin',
Edward Lesmes5b9c6842018-03-09 13:07:22 -0500241 'run_low_bandwidth_audio_test'),
242 '-v', '--num-retries', args.num_retries]
oprypin6d305ba2017-03-30 04:01:30 -0700243 else:
244 test_command = [os.path.join(args.build_dir, 'low_bandwidth_audio_test')]
oprypin92220ff2017-03-23 03:40:03 -0700245
Artem Titovb1f2d602019-07-10 14:40:58 +0200246 analyzers = [Analyzer('pesq', _RunPesq, pesq_path, 16000)]
oprypinf2501002017-04-12 05:00:56 -0700247 # Check if POLQA can run at all, or skip the 48 kHz tests entirely.
248 example_path = os.path.join(SRC_DIR, 'resources',
249 'voice_engine', 'audio_tiny48.wav')
Edward Lemurb0250f02017-10-04 14:41:17 +0200250 if polqa_path and _RunPolqa(polqa_path, example_path, example_path):
Artem Titovb1f2d602019-07-10 14:40:58 +0200251 analyzers.append(Analyzer('polqa', _RunPolqa, polqa_path, 48000))
oprypin92220ff2017-03-23 03:40:03 -0700252
Edward Lemurb4017712018-01-15 14:21:09 +0100253 charts = {}
254
oprypinf2501002017-04-12 05:00:56 -0700255 for analyzer in analyzers:
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000256 # Start the test executable that produces audio files.
257 test_process = subprocess.Popen(
Artem Titovb1f2d602019-07-10 14:40:58 +0200258 _LogCommand(test_command + [
259 '--sample_rate_hz=%d' % analyzer.sample_rate_hz,
260 '--test_case_prefix=%s' % analyzer.name
261 ]),
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000262 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
Artem Titovb1f2d602019-07-10 14:40:58 +0200263 perf_results_file = None
oprypinf2501002017-04-12 05:00:56 -0700264 try:
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000265 lines = iter(test_process.stdout.readline, '')
266 for result in ExtractTestRuns(lines, echo=True):
Artem Titovb1f2d602019-07-10 14:40:58 +0200267 (android_device, test_name, reference_file, degraded_file,
268 perf_results_file) = result
oprypin92220ff2017-03-23 03:40:03 -0700269
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000270 adb_prefix = (args.adb_path,)
271 if android_device:
272 adb_prefix += ('-s', android_device)
oprypin92220ff2017-03-23 03:40:03 -0700273
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000274 reference_file = _GetFile(reference_file, out_dir,
275 android=args.android, adb_prefix=adb_prefix)
276 degraded_file = _GetFile(degraded_file, out_dir, move=True,
277 android=args.android, adb_prefix=adb_prefix)
oprypin92220ff2017-03-23 03:40:03 -0700278
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000279 analyzer_results = analyzer.func(analyzer.executable,
280 reference_file, degraded_file)
281 for metric, (value, units) in analyzer_results.items():
282 # Output a result for the perf dashboard.
283 print 'RESULT %s: %s= %s %s' % (metric, test_name, value, units)
284 _AddChart(charts, metric, test_name, value, units)
oprypin92220ff2017-03-23 03:40:03 -0700285
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000286 if args.remove:
287 os.remove(reference_file)
288 os.remove(degraded_file)
oprypinf2501002017-04-12 05:00:56 -0700289 finally:
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000290 test_process.terminate()
Artem Titovb1f2d602019-07-10 14:40:58 +0200291 if perf_results_file:
292 perf_results_file = _GetFile(perf_results_file, out_dir, move=True,
293 android=args.android, adb_prefix=adb_prefix)
294 _AddRunPerfResults(charts, perf_results_file)
295 if args.remove:
296 os.remove(perf_results_file)
oprypin6d305ba2017-03-30 04:01:30 -0700297
Edward Lemured7b4ff2018-02-01 17:23:58 +0100298 if args.isolated_script_test_perf_output:
299 with open(args.isolated_script_test_perf_output, 'w') as f:
Edward Lemurb4017712018-01-15 14:21:09 +0100300 json.dump({"format_version": "1.0", "charts": charts}, f)
301
Oleh Prypin637b0b52018-09-21 17:16:06 +0200302 if args.isolated_script_test_output:
303 with open(args.isolated_script_test_output, 'w') as f:
304 json.dump({"version": 3}, f)
305
oprypin92220ff2017-03-23 03:40:03 -0700306 return test_process.wait()
kjellander8f8d1a02017-03-06 04:01:16 -0800307
308
309if __name__ == '__main__':
310 sys.exit(main())