blob: 0a0a597de4dc1907fbb1fd6e81b279fc3ae6942e [file] [log] [blame]
Jeremy Leconte1d4e9822022-01-28 16:19:39 +01001#!/usr/bin/env vpython3
kjellander8f8d1a02017-03-06 04:01:16 -08002# 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.
kjellander8f8d1a02017-03-06 04:01:16 -08009"""
10This script is the wrapper that runs the low-bandwidth audio test.
11
12After running the test, post-process steps for calculating audio quality of the
13output files will be performed.
14"""
15
16import argparse
oprypinf2501002017-04-12 05:00:56 -070017import collections
Jeremy Leconte994bf452022-01-12 10:51:16 +010018import json
kjellander8f8d1a02017-03-06 04:01:16 -080019import logging
20import os
oprypin92220ff2017-03-23 03:40:03 -070021import re
oprypin6d305ba2017-03-30 04:01:30 -070022import shutil
kjellander8f8d1a02017-03-06 04:01:16 -080023import subprocess
24import sys
25
kjellander8f8d1a02017-03-06 04:01:16 -080026SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
Henrik Kjellander5a6aa4f2017-09-15 09:31:54 +020027SRC_DIR = os.path.normpath(os.path.join(SCRIPT_DIR, os.pardir, os.pardir))
kjellander8f8d1a02017-03-06 04:01:16 -080028
Edward Lemurb0250f02017-10-04 14:41:17 +020029NO_TOOLS_ERROR_MESSAGE = (
Mirko Bonadei8cc66952020-10-30 10:13:45 +010030 'Could not find PESQ or POLQA at %s.\n'
31 '\n'
32 'To fix this run:\n'
33 ' python %s %s\n'
34 '\n'
Jeremy Lecontef22c78b2021-12-07 19:49:48 +010035 'Note that these tools are Google-internal due to licensing, so in order '
36 'to use them you will have to get your own license and manually put them '
37 'in the right location.\n'
Mirko Bonadei8cc66952020-10-30 10:13:45 +010038 'See https://cs.chromium.org/chromium/src/third_party/webrtc/tools_webrtc/'
39 'download_tools.py?rcl=bbceb76f540159e2dba0701ac03c514f01624130&l=13')
Edward Lemurb0250f02017-10-04 14:41:17 +020040
kjellander8f8d1a02017-03-06 04:01:16 -080041
oprypin92220ff2017-03-23 03:40:03 -070042def _LogCommand(command):
Jeremy Lecontef22c78b2021-12-07 19:49:48 +010043 logging.info('Running %r', command)
44 return command
kjellander8f8d1a02017-03-06 04:01:16 -080045
46
47def _ParseArgs():
Jeremy Lecontef22c78b2021-12-07 19:49:48 +010048 parser = argparse.ArgumentParser(description='Run low-bandwidth audio tests.')
49 parser.add_argument('build_dir',
50 help='Path to the build directory (e.g. out/Release).')
51 parser.add_argument('--remove',
52 action='store_true',
53 help='Remove output audio files after testing.')
54 parser.add_argument(
55 '--android',
56 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')
59 parser.add_argument('--num-retries',
60 default='0',
61 help='Number of times to retry the test on Android.')
62 parser.add_argument(
63 '--isolated-script-test-perf-output',
64 default=None,
65 help='Path to store perf results in histogram proto format.')
Jeremy Leconte994bf452022-01-12 10:51:16 +010066 parser.add_argument(
67 '--isolated-script-test-output',
68 default=None,
69 help='Path to output an empty JSON file which Chromium infra requires.')
Jeremy Lecontef22c78b2021-12-07 19:49:48 +010070 parser.add_argument('--extra-test-args',
71 default=[],
72 action='append',
73 help='Extra args to path to the test binary.')
Edward Lemur7e3b5692017-10-04 17:03:16 +020074
Jeremy Lecontef22c78b2021-12-07 19:49:48 +010075 # Ignore Chromium-specific flags
76 parser.add_argument('--test-launcher-summary-output', type=str, default=None)
77 args = parser.parse_args()
Edward Lemur7e3b5692017-10-04 17:03:16 +020078
Jeremy Lecontef22c78b2021-12-07 19:49:48 +010079 return args
kjellander8f8d1a02017-03-06 04:01:16 -080080
81
oprypin92220ff2017-03-23 03:40:03 -070082def _GetPlatform():
Jeremy Lecontef22c78b2021-12-07 19:49:48 +010083 if sys.platform == 'win32':
84 return 'win'
85 elif sys.platform == 'darwin':
86 return 'mac'
87 elif sys.platform.startswith('linux'):
88 return 'linux'
89 raise AssertionError('Unknown platform %s' % sys.platform)
oprypin92220ff2017-03-23 03:40:03 -070090
91
Edward Lemurb0250f02017-10-04 14:41:17 +020092def _GetExtension():
Jeremy Lecontef22c78b2021-12-07 19:49:48 +010093 return '.exe' if sys.platform == 'win32' else ''
Edward Lemurb0250f02017-10-04 14:41:17 +020094
95
96def _GetPathToTools():
Jeremy Lecontef22c78b2021-12-07 19:49:48 +010097 tools_dir = os.path.join(SRC_DIR, 'tools_webrtc')
98 toolchain_dir = os.path.join(tools_dir, 'audio_quality')
oprypin92220ff2017-03-23 03:40:03 -070099
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100100 platform = _GetPlatform()
101 ext = _GetExtension()
Edward Lemurbb1222f2017-10-03 12:33:38 +0000102
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100103 pesq_path = os.path.join(toolchain_dir, platform, 'pesq' + ext)
104 if not os.path.isfile(pesq_path):
105 pesq_path = None
Edward Lemurb0250f02017-10-04 14:41:17 +0200106
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100107 polqa_path = os.path.join(toolchain_dir, platform, 'PolqaOem64' + ext)
108 if not os.path.isfile(polqa_path):
109 polqa_path = None
Edward Lemurb0250f02017-10-04 14:41:17 +0200110
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100111 if (platform != 'mac' and not polqa_path) or not pesq_path:
112 logging.error(NO_TOOLS_ERROR_MESSAGE, toolchain_dir,
113 os.path.join(tools_dir, 'download_tools.py'), toolchain_dir)
Edward Lemurb0250f02017-10-04 14:41:17 +0200114
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100115 return pesq_path, polqa_path
oprypin92220ff2017-03-23 03:40:03 -0700116
117
oprypinabd101b2017-04-06 23:21:30 -0700118def ExtractTestRuns(lines, echo=False):
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100119 """Extracts information about tests from the output of a test runner.
oprypinabd101b2017-04-06 23:21:30 -0700120
Artem Titovb1f2d602019-07-10 14:40:58 +0200121 Produces tuples
122 (android_device, test_name, reference_file, degraded_file, cur_perf_results).
oprypinabd101b2017-04-06 23:21:30 -0700123 """
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100124 for line in lines:
125 if echo:
Mirko Bonadei0bd99052022-01-31 13:16:29 +0100126 sys.stdout.write(line.decode('utf-8'))
oprypinabd101b2017-04-06 23:21:30 -0700127
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100128 # Output from Android has a prefix with the device name.
129 android_prefix_re = r'(?:I\b.+\brun_tests_on_device\((.+?)\)\s*)?'
130 test_re = r'^' + android_prefix_re + (r'TEST (\w+) ([^ ]+?) ([^\s]+)'
131 r' ?([^\s]+)?\s*$')
oprypinabd101b2017-04-06 23:21:30 -0700132
Mirko Bonadeib6653d92022-02-01 09:57:11 +0100133 match = re.search(test_re, line.decode('utf-8'))
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100134 if match:
135 yield match.groups()
oprypinabd101b2017-04-06 23:21:30 -0700136
137
Mirko Bonadei8cc66952020-10-30 10:13:45 +0100138def _GetFile(file_path,
139 out_dir,
140 move=False,
141 android=False,
142 adb_prefix=('adb', )):
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100143 out_file_name = os.path.basename(file_path)
144 out_file_path = os.path.join(out_dir, out_file_name)
oprypin6d305ba2017-03-30 04:01:30 -0700145
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100146 if android:
147 # Pull the file from the connected Android device.
148 adb_command = adb_prefix + ('pull', file_path, out_dir)
149 subprocess.check_call(_LogCommand(adb_command))
150 if move:
151 # Remove that file.
152 adb_command = adb_prefix + ('shell', 'rm', file_path)
153 subprocess.check_call(_LogCommand(adb_command))
154 elif os.path.abspath(file_path) != os.path.abspath(out_file_path):
155 if move:
156 shutil.move(file_path, out_file_path)
157 else:
158 shutil.copy(file_path, out_file_path)
oprypin6d305ba2017-03-30 04:01:30 -0700159
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100160 return out_file_path
oprypin6d305ba2017-03-30 04:01:30 -0700161
162
Mirko Bonadei8cc66952020-10-30 10:13:45 +0100163def _RunPesq(executable_path,
164 reference_file,
165 degraded_file,
oprypinf2501002017-04-12 05:00:56 -0700166 sample_rate_hz=16000):
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100167 directory = os.path.dirname(reference_file)
168 assert os.path.dirname(degraded_file) == directory
oprypinf2501002017-04-12 05:00:56 -0700169
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100170 # Analyze audio.
171 command = [
172 executable_path,
173 '+%d' % sample_rate_hz,
174 os.path.basename(reference_file),
175 os.path.basename(degraded_file)
176 ]
177 # Need to provide paths in the current directory due to a bug in PESQ:
178 # On Mac, for some 'path/to/file.wav', if 'file.wav' is longer than
179 # 'path/to', PESQ crashes.
180 out = subprocess.check_output(_LogCommand(command),
181 cwd=directory,
182 stderr=subprocess.STDOUT)
oprypinf2501002017-04-12 05:00:56 -0700183
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100184 # Find the scores in stdout of PESQ.
185 match = re.search(
Mirko Bonadeib6653d92022-02-01 09:57:11 +0100186 r'Prediction \(Raw MOS, MOS-LQO\):\s+=\s+([\d.]+)\s+([\d.]+)',
187 out.decode('utf-8'))
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100188 if match:
189 raw_mos, _ = match.groups()
190 return {'pesq_mos': (raw_mos, 'unitless')}
191 logging.error('PESQ: %s', out.splitlines()[-1])
192 return {}
oprypinf2501002017-04-12 05:00:56 -0700193
194
195def _RunPolqa(executable_path, reference_file, degraded_file):
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100196 # Analyze audio.
197 command = [
198 executable_path, '-q', '-LC', 'NB', '-Ref', reference_file, '-Test',
199 degraded_file
200 ]
201 process = subprocess.Popen(_LogCommand(command),
202 stdout=subprocess.PIPE,
203 stderr=subprocess.PIPE)
204 out, err = process.communicate()
oprypinf2501002017-04-12 05:00:56 -0700205
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100206 # Find the scores in stdout of POLQA.
Mirko Bonadeif3686712022-01-31 08:47:41 +0100207 match = re.search(r'\bMOS-LQO:\s+([\d.]+)', out.decode('utf-8'))
oprypinf2501002017-04-12 05:00:56 -0700208
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100209 if process.returncode != 0 or not match:
210 if process.returncode == 2:
211 logging.warning('%s (2)', err.strip())
212 logging.warning('POLQA license error, skipping test.')
213 else:
214 logging.error('%s (%d)', err.strip(), process.returncode)
215 return {}
oprypinf2501002017-04-12 05:00:56 -0700216
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100217 mos_lqo, = match.groups()
218 return {'polqa_mos_lqo': (mos_lqo, 'unitless')}
oprypinf2501002017-04-12 05:00:56 -0700219
220
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100221def _MergeInPerfResultsFromCcTests(histograms, run_perf_results_file):
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100222 from tracing.value import histogram_set
Edward Lemurb4017712018-01-15 14:21:09 +0100223
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100224 cc_histograms = histogram_set.HistogramSet()
225 with open(run_perf_results_file, 'rb') as f:
226 contents = f.read()
227 if not contents:
228 return
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100229
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100230 cc_histograms.ImportProto(contents)
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100231
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100232 histograms.Merge(cc_histograms)
Artem Titovb1f2d602019-07-10 14:40:58 +0200233
234
Mirko Bonadei8cc66952020-10-30 10:13:45 +0100235Analyzer = collections.namedtuple(
236 'Analyzer', ['name', 'func', 'executable', 'sample_rate_hz'])
oprypinf2501002017-04-12 05:00:56 -0700237
238
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100239def _ConfigurePythonPath(args):
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100240 script_dir = os.path.dirname(os.path.realpath(__file__))
241 checkout_root = os.path.abspath(os.path.join(script_dir, os.pardir,
242 os.pardir))
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100243
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100244 # TODO(https://crbug.com/1029452): Use a copy rule and add these from the
245 # out dir like for the third_party/protobuf code.
246 sys.path.insert(
247 0, os.path.join(checkout_root, 'third_party', 'catapult', 'tracing'))
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100248
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100249 # The low_bandwidth_audio_perf_test gn rule will build the protobuf stub
250 # for python, so put it in the path for this script before we attempt to
251 # import it.
252 histogram_proto_path = os.path.join(os.path.abspath(args.build_dir),
253 'pyproto', 'tracing', 'tracing', 'proto')
254 sys.path.insert(0, histogram_proto_path)
255 proto_stub_path = os.path.join(os.path.abspath(args.build_dir), 'pyproto')
256 sys.path.insert(0, proto_stub_path)
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100257
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100258 # Fail early in case the proto hasn't been built.
259 try:
260 #pylint: disable=unused-variable
261 import histogram_pb2
262 except ImportError as e:
263 logging.exception(e)
264 raise ImportError('Could not import histogram_pb2. You need to build the '
265 'low_bandwidth_audio_perf_test target before invoking '
266 'this script. Expected to find '
267 'histogram_pb2.py in %s.' % histogram_proto_path)
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100268
269
kjellander8f8d1a02017-03-06 04:01:16 -0800270def main():
Mirko Bonadeic6206652022-02-01 18:52:49 +0100271 logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s',
272 level=logging.INFO,
273 datefmt='%Y-%m-%d %H:%M:%S')
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100274 logging.info('Invoked with %s', str(sys.argv))
kjellander8f8d1a02017-03-06 04:01:16 -0800275
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100276 args = _ParseArgs()
kjellander8f8d1a02017-03-06 04:01:16 -0800277
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100278 _ConfigurePythonPath(args)
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100279
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100280 # Import catapult modules here after configuring the pythonpath.
281 from tracing.value import histogram_set
282 from tracing.value.diagnostics import reserved_infos
283 from tracing.value.diagnostics import generic_set
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100284
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100285 pesq_path, polqa_path = _GetPathToTools()
286 if pesq_path is None:
287 return 1
kjellander8f8d1a02017-03-06 04:01:16 -0800288
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100289 out_dir = os.path.join(args.build_dir, '..')
290 if args.android:
291 test_command = [
292 os.path.join(args.build_dir, 'bin', 'run_low_bandwidth_audio_test'),
293 '-v', '--num-retries', args.num_retries
294 ]
295 else:
296 test_command = [os.path.join(args.build_dir, 'low_bandwidth_audio_test')]
oprypin92220ff2017-03-23 03:40:03 -0700297
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100298 analyzers = [Analyzer('pesq', _RunPesq, pesq_path, 16000)]
299 # Check if POLQA can run at all, or skip the 48 kHz tests entirely.
300 example_path = os.path.join(SRC_DIR, 'resources', 'voice_engine',
301 'audio_tiny48.wav')
302 if polqa_path and _RunPolqa(polqa_path, example_path, example_path):
303 analyzers.append(Analyzer('polqa', _RunPolqa, polqa_path, 48000))
oprypin92220ff2017-03-23 03:40:03 -0700304
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100305 histograms = histogram_set.HistogramSet()
306 for analyzer in analyzers:
307 # Start the test executable that produces audio files.
308 test_process = subprocess.Popen(_LogCommand(test_command + [
309 '--sample_rate_hz=%d' % analyzer.sample_rate_hz,
310 '--test_case_prefix=%s' % analyzer.name,
311 ] + args.extra_test_args),
312 stdout=subprocess.PIPE,
313 stderr=subprocess.STDOUT)
314 perf_results_file = None
315 try:
316 lines = iter(test_process.stdout.readline, '')
317 for result in ExtractTestRuns(lines, echo=True):
318 (android_device, test_name, reference_file, degraded_file,
319 perf_results_file) = result
oprypin92220ff2017-03-23 03:40:03 -0700320
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100321 adb_prefix = (args.adb_path, )
322 if android_device:
323 adb_prefix += ('-s', android_device)
oprypin92220ff2017-03-23 03:40:03 -0700324
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100325 reference_file = _GetFile(reference_file,
326 out_dir,
327 android=args.android,
328 adb_prefix=adb_prefix)
329 degraded_file = _GetFile(degraded_file,
330 out_dir,
331 move=True,
332 android=args.android,
333 adb_prefix=adb_prefix)
oprypin92220ff2017-03-23 03:40:03 -0700334
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100335 analyzer_results = analyzer.func(analyzer.executable, reference_file,
336 degraded_file)
Jeremy Leconte1d4e9822022-01-28 16:19:39 +0100337 for metric, (value, units) in list(analyzer_results.items()):
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100338 hist = histograms.CreateHistogram(metric, units, [value])
339 user_story = generic_set.GenericSet([test_name])
340 hist.diagnostics[reserved_infos.STORIES.name] = user_story
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100341
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100342 # Output human readable results.
Jeremy Leconte1d4e9822022-01-28 16:19:39 +0100343 print('RESULT %s: %s= %s %s' % (metric, test_name, value, units))
oprypin92220ff2017-03-23 03:40:03 -0700344
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100345 if args.remove:
346 os.remove(reference_file)
347 os.remove(degraded_file)
348 finally:
349 test_process.terminate()
350 if perf_results_file:
351 perf_results_file = _GetFile(perf_results_file,
352 out_dir,
353 move=True,
354 android=args.android,
355 adb_prefix=adb_prefix)
356 _MergeInPerfResultsFromCcTests(histograms, perf_results_file)
357 if args.remove:
358 os.remove(perf_results_file)
oprypin6d305ba2017-03-30 04:01:30 -0700359
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100360 if args.isolated_script_test_perf_output:
361 with open(args.isolated_script_test_perf_output, 'wb') as f:
362 f.write(histograms.AsProto().SerializeToString())
Edward Lemurb4017712018-01-15 14:21:09 +0100363
Jeremy Leconte994bf452022-01-12 10:51:16 +0100364 if args.isolated_script_test_output:
365 with open(args.isolated_script_test_output, 'w') as f:
366 json.dump({"version": 3}, f)
367
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100368 return test_process.wait()
kjellander8f8d1a02017-03-06 04:01:16 -0800369
370
371if __name__ == '__main__':
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100372 sys.exit(main())