blob: cc6a70eeaf6f11b8038e338d149a203d480b2d8a [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.')
Artem Titovcbc91efa2019-07-23 13:23:20 +020064 parser.add_argument('--extra-test-args', default=[], action='append',
65 help='Extra args to path to the test binary.')
Edward Lemur7e3b5692017-10-04 17:03:16 +020066
67 # Ignore Chromium-specific flags
Edward Lemurd8b041c2018-01-16 14:30:28 +010068 parser.add_argument('--test-launcher-summary-output',
69 type=str, default=None)
kjellander8f8d1a02017-03-06 04:01:16 -080070 args = parser.parse_args()
Edward Lemur7e3b5692017-10-04 17:03:16 +020071
kjellander8f8d1a02017-03-06 04:01:16 -080072 return args
73
74
oprypin92220ff2017-03-23 03:40:03 -070075def _GetPlatform():
76 if sys.platform == 'win32':
77 return 'win'
78 elif sys.platform == 'darwin':
79 return 'mac'
80 elif sys.platform.startswith('linux'):
81 return 'linux'
82
83
Edward Lemurb0250f02017-10-04 14:41:17 +020084def _GetExtension():
85 return '.exe' if sys.platform == 'win32' else ''
86
87
88def _GetPathToTools():
Henrik Kjellander90fd7d82017-05-09 08:30:10 +020089 tools_dir = os.path.join(SRC_DIR, 'tools_webrtc')
oprypin92220ff2017-03-23 03:40:03 -070090 toolchain_dir = os.path.join(tools_dir, 'audio_quality')
91
Edward Lemurb0250f02017-10-04 14:41:17 +020092 platform = _GetPlatform()
93 ext = _GetExtension()
Edward Lemurbb1222f2017-10-03 12:33:38 +000094
Edward Lemurb0250f02017-10-04 14:41:17 +020095 pesq_path = os.path.join(toolchain_dir, platform, 'pesq' + ext)
96 if not os.path.isfile(pesq_path):
97 pesq_path = None
98
99 polqa_path = os.path.join(toolchain_dir, platform, 'PolqaOem64' + ext)
100 if not os.path.isfile(polqa_path):
101 polqa_path = None
102
103 if (platform != 'mac' and not polqa_path) or not pesq_path:
104 logging.error(NO_TOOLS_ERROR_MESSAGE,
105 toolchain_dir,
106 os.path.join(tools_dir, 'download_tools.py'),
107 toolchain_dir)
108
oprypinf2501002017-04-12 05:00:56 -0700109 return pesq_path, polqa_path
oprypin92220ff2017-03-23 03:40:03 -0700110
111
oprypinabd101b2017-04-06 23:21:30 -0700112def ExtractTestRuns(lines, echo=False):
113 """Extracts information about tests from the output of a test runner.
114
Artem Titovb1f2d602019-07-10 14:40:58 +0200115 Produces tuples
116 (android_device, test_name, reference_file, degraded_file, cur_perf_results).
oprypinabd101b2017-04-06 23:21:30 -0700117 """
118 for line in lines:
119 if echo:
120 sys.stdout.write(line)
121
122 # Output from Android has a prefix with the device name.
123 android_prefix_re = r'(?:I\b.+\brun_tests_on_device\((.+?)\)\s*)?'
Artem Titovb1f2d602019-07-10 14:40:58 +0200124 test_re = r'^' + android_prefix_re + (r'TEST (\w+) ([^ ]+?) ([^\s]+)'
125 r' ?([^\s]+)?\s*$')
oprypinabd101b2017-04-06 23:21:30 -0700126
127 match = re.search(test_re, line)
128 if match:
129 yield match.groups()
130
131
132def _GetFile(file_path, out_dir, move=False,
133 android=False, adb_prefix=('adb',)):
oprypin6d305ba2017-03-30 04:01:30 -0700134 out_file_name = os.path.basename(file_path)
135 out_file_path = os.path.join(out_dir, out_file_name)
136
137 if android:
oprypinabd101b2017-04-06 23:21:30 -0700138 # Pull the file from the connected Android device.
139 adb_command = adb_prefix + ('pull', file_path, out_dir)
oprypin6d305ba2017-03-30 04:01:30 -0700140 subprocess.check_call(_LogCommand(adb_command))
oprypinabd101b2017-04-06 23:21:30 -0700141 if move:
142 # Remove that file.
143 adb_command = adb_prefix + ('shell', 'rm', file_path)
144 subprocess.check_call(_LogCommand(adb_command))
oprypin6d305ba2017-03-30 04:01:30 -0700145 elif os.path.abspath(file_path) != os.path.abspath(out_file_path):
oprypinabd101b2017-04-06 23:21:30 -0700146 if move:
147 shutil.move(file_path, out_file_path)
148 else:
149 shutil.copy(file_path, out_file_path)
oprypin6d305ba2017-03-30 04:01:30 -0700150
151 return out_file_path
152
153
oprypinf2501002017-04-12 05:00:56 -0700154def _RunPesq(executable_path, reference_file, degraded_file,
155 sample_rate_hz=16000):
156 directory = os.path.dirname(reference_file)
157 assert os.path.dirname(degraded_file) == directory
158
159 # Analyze audio.
160 command = [executable_path, '+%d' % sample_rate_hz,
161 os.path.basename(reference_file),
162 os.path.basename(degraded_file)]
163 # Need to provide paths in the current directory due to a bug in PESQ:
164 # On Mac, for some 'path/to/file.wav', if 'file.wav' is longer than
165 # 'path/to', PESQ crashes.
166 out = subprocess.check_output(_LogCommand(command),
167 cwd=directory, stderr=subprocess.STDOUT)
168
169 # Find the scores in stdout of PESQ.
170 match = re.search(
171 r'Prediction \(Raw MOS, MOS-LQO\):\s+=\s+([\d.]+)\s+([\d.]+)', out)
172 if match:
173 raw_mos, _ = match.groups()
174
175 return {'pesq_mos': (raw_mos, 'score')}
176 else:
177 logging.error('PESQ: %s', out.splitlines()[-1])
178 return {}
179
180
181def _RunPolqa(executable_path, reference_file, degraded_file):
182 # Analyze audio.
183 command = [executable_path, '-q', '-LC', 'NB',
184 '-Ref', reference_file, '-Test', degraded_file]
Edward Lemurb0250f02017-10-04 14:41:17 +0200185 process = subprocess.Popen(_LogCommand(command),
186 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
oprypinf2501002017-04-12 05:00:56 -0700187 out, err = process.communicate()
188
189 # Find the scores in stdout of POLQA.
190 match = re.search(r'\bMOS-LQO:\s+([\d.]+)', out)
191
192 if process.returncode != 0 or not match:
193 if process.returncode == 2:
194 logging.warning('%s (2)', err.strip())
195 logging.warning('POLQA license error, skipping test.')
196 else:
197 logging.error('%s (%d)', err.strip(), process.returncode)
198 return {}
199
200 mos_lqo, = match.groups()
201 return {'polqa_mos_lqo': (mos_lqo, 'score')}
202
203
Edward Lemurb4017712018-01-15 14:21:09 +0100204def _AddChart(charts, metric, test_name, value, units):
205 chart = charts.setdefault(metric, {})
206 chart[test_name] = {
207 "type": "scalar",
208 "value": value,
209 "units": units,
210 }
211
212
Artem Titovb1f2d602019-07-10 14:40:58 +0200213def _AddRunPerfResults(charts, run_perf_results_file):
214 with open(run_perf_results_file, 'rb') as f:
215 per_run_perf_results = json.load(f)
216 if 'charts' not in per_run_perf_results:
217 return
218 for metric, cases in per_run_perf_results['charts'].items():
219 chart = charts.setdefault(metric, {})
220 for case_name, case_value in cases.items():
221 if case_name in chart:
222 logging.error('Overriding results for %s/%s', metric, case_name)
223 chart[case_name] = case_value
224
225
226Analyzer = collections.namedtuple('Analyzer', ['name', 'func', 'executable',
oprypinf2501002017-04-12 05:00:56 -0700227 'sample_rate_hz'])
228
229
kjellander8f8d1a02017-03-06 04:01:16 -0800230def main():
231 # pylint: disable=W0101
232 logging.basicConfig(level=logging.INFO)
233
234 args = _ParseArgs()
235
Edward Lemurb0250f02017-10-04 14:41:17 +0200236 pesq_path, polqa_path = _GetPathToTools()
237 if pesq_path is None:
238 return 1
kjellander8f8d1a02017-03-06 04:01:16 -0800239
oprypin6d305ba2017-03-30 04:01:30 -0700240 out_dir = os.path.join(args.build_dir, '..')
241 if args.android:
242 test_command = [os.path.join(args.build_dir, 'bin',
Edward Lesmes5b9c6842018-03-09 13:07:22 -0500243 'run_low_bandwidth_audio_test'),
244 '-v', '--num-retries', args.num_retries]
oprypin6d305ba2017-03-30 04:01:30 -0700245 else:
246 test_command = [os.path.join(args.build_dir, 'low_bandwidth_audio_test')]
oprypin92220ff2017-03-23 03:40:03 -0700247
Artem Titovb1f2d602019-07-10 14:40:58 +0200248 analyzers = [Analyzer('pesq', _RunPesq, pesq_path, 16000)]
oprypinf2501002017-04-12 05:00:56 -0700249 # Check if POLQA can run at all, or skip the 48 kHz tests entirely.
250 example_path = os.path.join(SRC_DIR, 'resources',
251 'voice_engine', 'audio_tiny48.wav')
Edward Lemurb0250f02017-10-04 14:41:17 +0200252 if polqa_path and _RunPolqa(polqa_path, example_path, example_path):
Artem Titovb1f2d602019-07-10 14:40:58 +0200253 analyzers.append(Analyzer('polqa', _RunPolqa, polqa_path, 48000))
oprypin92220ff2017-03-23 03:40:03 -0700254
Edward Lemurb4017712018-01-15 14:21:09 +0100255 charts = {}
256
oprypinf2501002017-04-12 05:00:56 -0700257 for analyzer in analyzers:
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000258 # Start the test executable that produces audio files.
259 test_process = subprocess.Popen(
Artem Titovb1f2d602019-07-10 14:40:58 +0200260 _LogCommand(test_command + [
261 '--sample_rate_hz=%d' % analyzer.sample_rate_hz,
262 '--test_case_prefix=%s' % analyzer.name
Artem Titovcbc91efa2019-07-23 13:23:20 +0200263 ] + args.extra_test_args),
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000264 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
Artem Titovb1f2d602019-07-10 14:40:58 +0200265 perf_results_file = None
oprypinf2501002017-04-12 05:00:56 -0700266 try:
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000267 lines = iter(test_process.stdout.readline, '')
268 for result in ExtractTestRuns(lines, echo=True):
Artem Titovb1f2d602019-07-10 14:40:58 +0200269 (android_device, test_name, reference_file, degraded_file,
270 perf_results_file) = result
oprypin92220ff2017-03-23 03:40:03 -0700271
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000272 adb_prefix = (args.adb_path,)
273 if android_device:
274 adb_prefix += ('-s', android_device)
oprypin92220ff2017-03-23 03:40:03 -0700275
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000276 reference_file = _GetFile(reference_file, out_dir,
277 android=args.android, adb_prefix=adb_prefix)
278 degraded_file = _GetFile(degraded_file, out_dir, move=True,
279 android=args.android, adb_prefix=adb_prefix)
oprypin92220ff2017-03-23 03:40:03 -0700280
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000281 analyzer_results = analyzer.func(analyzer.executable,
282 reference_file, degraded_file)
283 for metric, (value, units) in analyzer_results.items():
284 # Output a result for the perf dashboard.
285 print 'RESULT %s: %s= %s %s' % (metric, test_name, value, units)
286 _AddChart(charts, metric, test_name, value, units)
oprypin92220ff2017-03-23 03:40:03 -0700287
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000288 if args.remove:
289 os.remove(reference_file)
290 os.remove(degraded_file)
oprypinf2501002017-04-12 05:00:56 -0700291 finally:
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000292 test_process.terminate()
Artem Titovb1f2d602019-07-10 14:40:58 +0200293 if perf_results_file:
294 perf_results_file = _GetFile(perf_results_file, out_dir, move=True,
295 android=args.android, adb_prefix=adb_prefix)
296 _AddRunPerfResults(charts, perf_results_file)
297 if args.remove:
298 os.remove(perf_results_file)
oprypin6d305ba2017-03-30 04:01:30 -0700299
Edward Lemured7b4ff2018-02-01 17:23:58 +0100300 if args.isolated_script_test_perf_output:
301 with open(args.isolated_script_test_perf_output, 'w') as f:
Edward Lemurb4017712018-01-15 14:21:09 +0100302 json.dump({"format_version": "1.0", "charts": charts}, f)
303
Oleh Prypin637b0b52018-09-21 17:16:06 +0200304 if args.isolated_script_test_output:
305 with open(args.isolated_script_test_output, 'w') as f:
306 json.dump({"version": 3}, f)
307
oprypin92220ff2017-03-23 03:40:03 -0700308 return test_process.wait()
kjellander8f8d1a02017-03-06 04:01:16 -0800309
310
311if __name__ == '__main__':
312 sys.exit(main())