blob: 8c3554b1d4e53f592179b648351942435a6e3d44 [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
Artem Titov2d0880b2019-07-09 13:50:18 +020026import tempfile
kjellander8f8d1a02017-03-06 04:01:16 -080027
28
29SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
Henrik Kjellander5a6aa4f2017-09-15 09:31:54 +020030SRC_DIR = os.path.normpath(os.path.join(SCRIPT_DIR, os.pardir, os.pardir))
kjellander8f8d1a02017-03-06 04:01:16 -080031
Edward Lemurb0250f02017-10-04 14:41:17 +020032NO_TOOLS_ERROR_MESSAGE = (
33 'Could not find PESQ or POLQA at %s.\n'
34 '\n'
35 'To fix this run:\n'
36 ' python %s %s\n'
37 '\n'
38 'Note that these tools are Google-internal due to licensing, so in order to '
39 'use them you will have to get your own license and manually put them in the '
40 'right location.\n'
41 'See https://cs.chromium.org/chromium/src/third_party/webrtc/tools_webrtc/'
42 'download_tools.py?rcl=bbceb76f540159e2dba0701ac03c514f01624130&l=13')
43
kjellander8f8d1a02017-03-06 04:01:16 -080044
oprypin92220ff2017-03-23 03:40:03 -070045def _LogCommand(command):
46 logging.info('Running %r', command)
47 return command
kjellander8f8d1a02017-03-06 04:01:16 -080048
49
50def _ParseArgs():
51 parser = argparse.ArgumentParser(description='Run low-bandwidth audio tests.')
52 parser.add_argument('build_dir',
53 help='Path to the build directory (e.g. out/Release).')
oprypin92220ff2017-03-23 03:40:03 -070054 parser.add_argument('--remove', action='store_true',
55 help='Remove output audio files after testing.')
oprypin6d305ba2017-03-30 04:01:30 -070056 parser.add_argument('--android', action='store_true',
57 help='Perform the test on a connected Android device instead.')
58 parser.add_argument('--adb-path', help='Path to adb binary.', default='adb')
Edward Lesmes9599fd42018-03-12 16:43:05 -040059 parser.add_argument('--num-retries', default='0',
Edward Lesmes5b9c6842018-03-09 13:07:22 -050060 help='Number of times to retry the test on Android.')
Oleh Prypin637b0b52018-09-21 17:16:06 +020061 parser.add_argument('--isolated-script-test-perf-output', default=None,
62 help='Path to store perf results in chartjson format.')
63 parser.add_argument('--isolated-script-test-output', default=None,
64 help='Path to output an empty JSON file which Chromium infra requires.')
Edward Lemur7e3b5692017-10-04 17:03:16 +020065
66 # Ignore Chromium-specific flags
Edward Lemurd8b041c2018-01-16 14:30:28 +010067 parser.add_argument('--test-launcher-summary-output',
68 type=str, default=None)
kjellander8f8d1a02017-03-06 04:01:16 -080069 args = parser.parse_args()
Edward Lemur7e3b5692017-10-04 17:03:16 +020070
kjellander8f8d1a02017-03-06 04:01:16 -080071 return args
72
73
oprypin92220ff2017-03-23 03:40:03 -070074def _GetPlatform():
75 if sys.platform == 'win32':
76 return 'win'
77 elif sys.platform == 'darwin':
78 return 'mac'
79 elif sys.platform.startswith('linux'):
80 return 'linux'
81
82
Edward Lemurb0250f02017-10-04 14:41:17 +020083def _GetExtension():
84 return '.exe' if sys.platform == 'win32' else ''
85
86
87def _GetPathToTools():
Henrik Kjellander90fd7d82017-05-09 08:30:10 +020088 tools_dir = os.path.join(SRC_DIR, 'tools_webrtc')
oprypin92220ff2017-03-23 03:40:03 -070089 toolchain_dir = os.path.join(tools_dir, 'audio_quality')
90
Edward Lemurb0250f02017-10-04 14:41:17 +020091 platform = _GetPlatform()
92 ext = _GetExtension()
Edward Lemurbb1222f2017-10-03 12:33:38 +000093
Edward Lemurb0250f02017-10-04 14:41:17 +020094 pesq_path = os.path.join(toolchain_dir, platform, 'pesq' + ext)
95 if not os.path.isfile(pesq_path):
96 pesq_path = None
97
98 polqa_path = os.path.join(toolchain_dir, platform, 'PolqaOem64' + ext)
99 if not os.path.isfile(polqa_path):
100 polqa_path = None
101
102 if (platform != 'mac' and not polqa_path) or not pesq_path:
103 logging.error(NO_TOOLS_ERROR_MESSAGE,
104 toolchain_dir,
105 os.path.join(tools_dir, 'download_tools.py'),
106 toolchain_dir)
107
oprypinf2501002017-04-12 05:00:56 -0700108 return pesq_path, polqa_path
oprypin92220ff2017-03-23 03:40:03 -0700109
110
oprypinabd101b2017-04-06 23:21:30 -0700111def ExtractTestRuns(lines, echo=False):
112 """Extracts information about tests from the output of a test runner.
113
114 Produces tuples (android_device, test_name, reference_file, degraded_file).
115 """
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*)?'
122 test_re = r'^' + android_prefix_re + r'TEST (\w+) ([^ ]+?) ([^ ]+?)\s*$'
123
124 match = re.search(test_re, line)
125 if match:
126 yield match.groups()
127
128
129def _GetFile(file_path, out_dir, move=False,
130 android=False, adb_prefix=('adb',)):
oprypin6d305ba2017-03-30 04:01:30 -0700131 out_file_name = os.path.basename(file_path)
132 out_file_path = os.path.join(out_dir, out_file_name)
133
134 if android:
oprypinabd101b2017-04-06 23:21:30 -0700135 # Pull the file from the connected Android device.
136 adb_command = adb_prefix + ('pull', file_path, out_dir)
oprypin6d305ba2017-03-30 04:01:30 -0700137 subprocess.check_call(_LogCommand(adb_command))
oprypinabd101b2017-04-06 23:21:30 -0700138 if move:
139 # Remove that file.
140 adb_command = adb_prefix + ('shell', 'rm', file_path)
141 subprocess.check_call(_LogCommand(adb_command))
oprypin6d305ba2017-03-30 04:01:30 -0700142 elif os.path.abspath(file_path) != os.path.abspath(out_file_path):
oprypinabd101b2017-04-06 23:21:30 -0700143 if move:
144 shutil.move(file_path, out_file_path)
145 else:
146 shutil.copy(file_path, out_file_path)
oprypin6d305ba2017-03-30 04:01:30 -0700147
148 return out_file_path
149
150
oprypinf2501002017-04-12 05:00:56 -0700151def _RunPesq(executable_path, reference_file, degraded_file,
152 sample_rate_hz=16000):
153 directory = os.path.dirname(reference_file)
154 assert os.path.dirname(degraded_file) == directory
155
156 # Analyze audio.
157 command = [executable_path, '+%d' % sample_rate_hz,
158 os.path.basename(reference_file),
159 os.path.basename(degraded_file)]
160 # Need to provide paths in the current directory due to a bug in PESQ:
161 # On Mac, for some 'path/to/file.wav', if 'file.wav' is longer than
162 # 'path/to', PESQ crashes.
163 out = subprocess.check_output(_LogCommand(command),
164 cwd=directory, stderr=subprocess.STDOUT)
165
166 # Find the scores in stdout of PESQ.
167 match = re.search(
168 r'Prediction \(Raw MOS, MOS-LQO\):\s+=\s+([\d.]+)\s+([\d.]+)', out)
169 if match:
170 raw_mos, _ = match.groups()
171
172 return {'pesq_mos': (raw_mos, 'score')}
173 else:
174 logging.error('PESQ: %s', out.splitlines()[-1])
175 return {}
176
177
178def _RunPolqa(executable_path, reference_file, degraded_file):
179 # Analyze audio.
180 command = [executable_path, '-q', '-LC', 'NB',
181 '-Ref', reference_file, '-Test', degraded_file]
Edward Lemurb0250f02017-10-04 14:41:17 +0200182 process = subprocess.Popen(_LogCommand(command),
183 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
oprypinf2501002017-04-12 05:00:56 -0700184 out, err = process.communicate()
185
186 # Find the scores in stdout of POLQA.
187 match = re.search(r'\bMOS-LQO:\s+([\d.]+)', out)
188
189 if process.returncode != 0 or not match:
190 if process.returncode == 2:
191 logging.warning('%s (2)', err.strip())
192 logging.warning('POLQA license error, skipping test.')
193 else:
194 logging.error('%s (%d)', err.strip(), process.returncode)
195 return {}
196
197 mos_lqo, = match.groups()
198 return {'polqa_mos_lqo': (mos_lqo, 'score')}
199
200
Edward Lemurb4017712018-01-15 14:21:09 +0100201def _AddChart(charts, metric, test_name, value, units):
202 chart = charts.setdefault(metric, {})
203 chart[test_name] = {
204 "type": "scalar",
205 "value": value,
206 "units": units,
207 }
208
209
Artem Titov2d0880b2019-07-09 13:50:18 +0200210def _AddRunPerfResults(charts, run_perf_results_file):
211 with open(run_perf_results_file, 'rb') as f:
212 per_run_perf_results = json.load(f)
213 if 'charts' not in per_run_perf_results:
214 return
215 for metric, cases in per_run_perf_results['charts'].items():
216 chart = charts.setdefault(metric, {})
217 for case_name, case_value in cases.items():
218 if case_name in chart:
219 logging.error('Overriding results for %s/%s', metric, case_name)
220 chart[case_name] = case_value
221
222
223Analyzer = collections.namedtuple('Analyzer', ['name', 'func', 'executable',
oprypinf2501002017-04-12 05:00:56 -0700224 'sample_rate_hz'])
225
226
kjellander8f8d1a02017-03-06 04:01:16 -0800227def main():
228 # pylint: disable=W0101
229 logging.basicConfig(level=logging.INFO)
230
231 args = _ParseArgs()
232
Edward Lemurb0250f02017-10-04 14:41:17 +0200233 pesq_path, polqa_path = _GetPathToTools()
234 if pesq_path is None:
235 return 1
kjellander8f8d1a02017-03-06 04:01:16 -0800236
oprypin6d305ba2017-03-30 04:01:30 -0700237 out_dir = os.path.join(args.build_dir, '..')
238 if args.android:
239 test_command = [os.path.join(args.build_dir, 'bin',
Edward Lesmes5b9c6842018-03-09 13:07:22 -0500240 'run_low_bandwidth_audio_test'),
241 '-v', '--num-retries', args.num_retries]
oprypin6d305ba2017-03-30 04:01:30 -0700242 else:
243 test_command = [os.path.join(args.build_dir, 'low_bandwidth_audio_test')]
oprypin92220ff2017-03-23 03:40:03 -0700244
Artem Titov2d0880b2019-07-09 13:50:18 +0200245 analyzers = [Analyzer('pesq', _RunPesq, pesq_path, 16000)]
oprypinf2501002017-04-12 05:00:56 -0700246 # Check if POLQA can run at all, or skip the 48 kHz tests entirely.
247 example_path = os.path.join(SRC_DIR, 'resources',
248 'voice_engine', 'audio_tiny48.wav')
Edward Lemurb0250f02017-10-04 14:41:17 +0200249 if polqa_path and _RunPolqa(polqa_path, example_path, example_path):
Artem Titov2d0880b2019-07-09 13:50:18 +0200250 analyzers.append(Analyzer('polqa', _RunPolqa, polqa_path, 48000))
oprypin92220ff2017-03-23 03:40:03 -0700251
Edward Lemurb4017712018-01-15 14:21:09 +0100252 charts = {}
253
oprypinf2501002017-04-12 05:00:56 -0700254 for analyzer in analyzers:
Artem Titov2d0880b2019-07-09 13:50:18 +0200255 f, cur_perf_results = tempfile.mkstemp(prefix='audio_perf', suffix=".json")
oprypinf2501002017-04-12 05:00:56 -0700256 try:
Artem Titov2d0880b2019-07-09 13:50:18 +0200257 # Start the test executable that produces audio files.
258 test_process = subprocess.Popen(
259 _LogCommand(test_command + [
260 '--sample_rate_hz=%d' % analyzer.sample_rate_hz,
261 '--test_case_prefix=%s' % analyzer.name,
262 '--isolated_script_test_perf_output=%s' % cur_perf_results,
263 ]),
264 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
265 try:
266 lines = iter(test_process.stdout.readline, '')
267 for result in ExtractTestRuns(lines, echo=True):
268 (android_device, test_name, reference_file, degraded_file) = result
oprypin92220ff2017-03-23 03:40:03 -0700269
Artem Titov2d0880b2019-07-09 13:50:18 +0200270 adb_prefix = (args.adb_path,)
271 if android_device:
272 adb_prefix += ('-s', android_device)
oprypin92220ff2017-03-23 03:40:03 -0700273
Artem Titov2d0880b2019-07-09 13:50:18 +0200274 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
Artem Titov2d0880b2019-07-09 13:50:18 +0200279 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
Artem Titov2d0880b2019-07-09 13:50:18 +0200286 if args.remove:
287 os.remove(reference_file)
288 os.remove(degraded_file)
289 finally:
290 test_process.terminate()
291 _AddRunPerfResults(charts, cur_perf_results)
oprypinf2501002017-04-12 05:00:56 -0700292 finally:
Artem Titov2d0880b2019-07-09 13:50:18 +0200293 os.remove(cur_perf_results)
oprypin6d305ba2017-03-30 04:01:30 -0700294
Edward Lemured7b4ff2018-02-01 17:23:58 +0100295 if args.isolated_script_test_perf_output:
296 with open(args.isolated_script_test_perf_output, 'w') as f:
Edward Lemurb4017712018-01-15 14:21:09 +0100297 json.dump({"format_version": "1.0", "charts": charts}, f)
298
Oleh Prypin637b0b52018-09-21 17:16:06 +0200299 if args.isolated_script_test_output:
300 with open(args.isolated_script_test_output, 'w') as f:
301 json.dump({"version": 3}, f)
302
oprypin92220ff2017-03-23 03:40:03 -0700303 return test_process.wait()
kjellander8f8d1a02017-03-06 04:01:16 -0800304
305
306if __name__ == '__main__':
307 sys.exit(main())