blob: 0744889c64b9c41a4fe8b40924d7e0a9a9263ddf [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
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
26
27SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
Henrik Kjellander5a6aa4f2017-09-15 09:31:54 +020028SRC_DIR = os.path.normpath(os.path.join(SCRIPT_DIR, os.pardir, os.pardir))
kjellander8f8d1a02017-03-06 04:01:16 -080029
Edward Lemurb0250f02017-10-04 14:41:17 +020030NO_TOOLS_ERROR_MESSAGE = (
31 'Could not find PESQ or POLQA at %s.\n'
32 '\n'
33 'To fix this run:\n'
34 ' python %s %s\n'
35 '\n'
36 'Note that these tools are Google-internal due to licensing, so in order to '
37 'use them you will have to get your own license and manually put them in the '
38 'right location.\n'
39 'See https://cs.chromium.org/chromium/src/third_party/webrtc/tools_webrtc/'
40 'download_tools.py?rcl=bbceb76f540159e2dba0701ac03c514f01624130&l=13')
41
kjellander8f8d1a02017-03-06 04:01:16 -080042
oprypin92220ff2017-03-23 03:40:03 -070043def _LogCommand(command):
44 logging.info('Running %r', command)
45 return command
kjellander8f8d1a02017-03-06 04:01:16 -080046
47
48def _ParseArgs():
49 parser = argparse.ArgumentParser(description='Run low-bandwidth audio tests.')
50 parser.add_argument('build_dir',
51 help='Path to the build directory (e.g. out/Release).')
oprypin92220ff2017-03-23 03:40:03 -070052 parser.add_argument('--remove', action='store_true',
53 help='Remove output audio files after testing.')
oprypin6d305ba2017-03-30 04:01:30 -070054 parser.add_argument('--android', action='store_true',
55 help='Perform the test on a connected Android device instead.')
56 parser.add_argument('--adb-path', help='Path to adb binary.', default='adb')
Edward Lesmes9599fd42018-03-12 16:43:05 -040057 parser.add_argument('--num-retries', default='0',
Edward Lesmes5b9c6842018-03-09 13:07:22 -050058 help='Number of times to retry the test on Android.')
Patrik Höglund1b20c412020-03-25 08:58:51 +010059 parser.add_argument('--isolated_script_test_perf_output', default=None,
Patrik Höglund3b4bbf52020-03-26 08:41:09 +010060 help='Path to store perf results in histogram proto format.')
Artem Titovcbc91efa2019-07-23 13:23:20 +020061 parser.add_argument('--extra-test-args', default=[], action='append',
62 help='Extra args to path to the test binary.')
Edward Lemur7e3b5692017-10-04 17:03:16 +020063
64 # Ignore Chromium-specific flags
Edward Lemurd8b041c2018-01-16 14:30:28 +010065 parser.add_argument('--test-launcher-summary-output',
66 type=str, default=None)
kjellander8f8d1a02017-03-06 04:01:16 -080067 args = parser.parse_args()
Edward Lemur7e3b5692017-10-04 17:03:16 +020068
kjellander8f8d1a02017-03-06 04:01:16 -080069 return args
70
71
oprypin92220ff2017-03-23 03:40:03 -070072def _GetPlatform():
73 if sys.platform == 'win32':
74 return 'win'
75 elif sys.platform == 'darwin':
76 return 'mac'
77 elif sys.platform.startswith('linux'):
78 return 'linux'
79
80
Edward Lemurb0250f02017-10-04 14:41:17 +020081def _GetExtension():
82 return '.exe' if sys.platform == 'win32' else ''
83
84
85def _GetPathToTools():
Henrik Kjellander90fd7d82017-05-09 08:30:10 +020086 tools_dir = os.path.join(SRC_DIR, 'tools_webrtc')
oprypin92220ff2017-03-23 03:40:03 -070087 toolchain_dir = os.path.join(tools_dir, 'audio_quality')
88
Edward Lemurb0250f02017-10-04 14:41:17 +020089 platform = _GetPlatform()
90 ext = _GetExtension()
Edward Lemurbb1222f2017-10-03 12:33:38 +000091
Edward Lemurb0250f02017-10-04 14:41:17 +020092 pesq_path = os.path.join(toolchain_dir, platform, 'pesq' + ext)
93 if not os.path.isfile(pesq_path):
94 pesq_path = None
95
96 polqa_path = os.path.join(toolchain_dir, platform, 'PolqaOem64' + ext)
97 if not os.path.isfile(polqa_path):
98 polqa_path = None
99
100 if (platform != 'mac' and not polqa_path) or not pesq_path:
101 logging.error(NO_TOOLS_ERROR_MESSAGE,
102 toolchain_dir,
103 os.path.join(tools_dir, 'download_tools.py'),
104 toolchain_dir)
105
oprypinf2501002017-04-12 05:00:56 -0700106 return pesq_path, polqa_path
oprypin92220ff2017-03-23 03:40:03 -0700107
108
oprypinabd101b2017-04-06 23:21:30 -0700109def ExtractTestRuns(lines, echo=False):
110 """Extracts information about tests from the output of a test runner.
111
Artem Titovb1f2d602019-07-10 14:40:58 +0200112 Produces tuples
113 (android_device, test_name, reference_file, degraded_file, cur_perf_results).
oprypinabd101b2017-04-06 23:21:30 -0700114 """
115 for line in lines:
116 if echo:
117 sys.stdout.write(line)
118
119 # Output from Android has a prefix with the device name.
120 android_prefix_re = r'(?:I\b.+\brun_tests_on_device\((.+?)\)\s*)?'
Artem Titovb1f2d602019-07-10 14:40:58 +0200121 test_re = r'^' + android_prefix_re + (r'TEST (\w+) ([^ ]+?) ([^\s]+)'
122 r' ?([^\s]+)?\s*$')
oprypinabd101b2017-04-06 23:21:30 -0700123
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
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100172 return {'pesq_mos': (raw_mos, 'unitless')}
oprypinf2501002017-04-12 05:00:56 -0700173 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()
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100198 return {'polqa_mos_lqo': (mos_lqo, 'unitless')}
oprypinf2501002017-04-12 05:00:56 -0700199
200
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100201def _MergeInPerfResultsFromCcTests(histograms, run_perf_results_file):
202 from tracing.value import histogram_set
Edward Lemurb4017712018-01-15 14:21:09 +0100203
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100204 cc_histograms = histogram_set.HistogramSet()
Artem Titovb1f2d602019-07-10 14:40:58 +0200205 with open(run_perf_results_file, 'rb') as f:
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100206 contents = f.read()
207 if not contents:
208 return
209
210 cc_histograms.ImportProto(contents)
211
212 histograms.Merge(cc_histograms)
Artem Titovb1f2d602019-07-10 14:40:58 +0200213
214
215Analyzer = collections.namedtuple('Analyzer', ['name', 'func', 'executable',
oprypinf2501002017-04-12 05:00:56 -0700216 'sample_rate_hz'])
217
218
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100219def _ConfigurePythonPath(args):
220 script_dir = os.path.dirname(os.path.realpath(__file__))
221 checkout_root = os.path.abspath(
222 os.path.join(script_dir, os.pardir, os.pardir))
223
224 sys.path.insert(0, os.path.join(checkout_root, 'third_party', 'catapult',
225 'tracing'))
226 sys.path.insert(0, os.path.join(checkout_root, 'third_party', 'protobuf',
227 'python'))
228
229 # The low_bandwidth_audio_perf_test gn rule will build the protobuf stub for
230 # python, so put it in the path for this script before we attempt to import
231 # it.
232 histogram_proto_path = os.path.join(
233 args.build_dir, 'pyproto', 'tracing', 'tracing', 'proto')
234 sys.path.insert(0, histogram_proto_path)
235
236 # Fail early in case the proto hasn't been built.
237 from tracing.proto import histogram_proto
238 if not histogram_proto.HAS_PROTO:
239 raise ImportError('Could not find histogram_pb2. You need to build the '
240 'low_bandwidth_audio_perf_test target before invoking '
241 'this script. Expected to find '
242 'histogram_pb2.py in %s.' % histogram_proto_path)
243
244
kjellander8f8d1a02017-03-06 04:01:16 -0800245def main():
246 # pylint: disable=W0101
247 logging.basicConfig(level=logging.INFO)
248
249 args = _ParseArgs()
250
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100251 _ConfigurePythonPath(args)
252
253 # Import catapult modules here after configuring the pythonpath.
254 from tracing.value import histogram_set
255 from tracing.value.diagnostics import reserved_infos
256 from tracing.value.diagnostics import generic_set
257
Edward Lemurb0250f02017-10-04 14:41:17 +0200258 pesq_path, polqa_path = _GetPathToTools()
259 if pesq_path is None:
260 return 1
kjellander8f8d1a02017-03-06 04:01:16 -0800261
oprypin6d305ba2017-03-30 04:01:30 -0700262 out_dir = os.path.join(args.build_dir, '..')
263 if args.android:
264 test_command = [os.path.join(args.build_dir, 'bin',
Edward Lesmes5b9c6842018-03-09 13:07:22 -0500265 'run_low_bandwidth_audio_test'),
266 '-v', '--num-retries', args.num_retries]
oprypin6d305ba2017-03-30 04:01:30 -0700267 else:
268 test_command = [os.path.join(args.build_dir, 'low_bandwidth_audio_test')]
oprypin92220ff2017-03-23 03:40:03 -0700269
Artem Titovb1f2d602019-07-10 14:40:58 +0200270 analyzers = [Analyzer('pesq', _RunPesq, pesq_path, 16000)]
oprypinf2501002017-04-12 05:00:56 -0700271 # Check if POLQA can run at all, or skip the 48 kHz tests entirely.
272 example_path = os.path.join(SRC_DIR, 'resources',
273 'voice_engine', 'audio_tiny48.wav')
Edward Lemurb0250f02017-10-04 14:41:17 +0200274 if polqa_path and _RunPolqa(polqa_path, example_path, example_path):
Artem Titovb1f2d602019-07-10 14:40:58 +0200275 analyzers.append(Analyzer('polqa', _RunPolqa, polqa_path, 48000))
oprypin92220ff2017-03-23 03:40:03 -0700276
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100277 histograms = histogram_set.HistogramSet()
oprypinf2501002017-04-12 05:00:56 -0700278 for analyzer in analyzers:
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000279 # Start the test executable that produces audio files.
280 test_process = subprocess.Popen(
Artem Titovb1f2d602019-07-10 14:40:58 +0200281 _LogCommand(test_command + [
282 '--sample_rate_hz=%d' % analyzer.sample_rate_hz,
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100283 '--test_case_prefix=%s' % analyzer.name,
284 '--write_histogram_proto_json'
Artem Titovcbc91efa2019-07-23 13:23:20 +0200285 ] + args.extra_test_args),
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000286 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
Artem Titovb1f2d602019-07-10 14:40:58 +0200287 perf_results_file = None
oprypinf2501002017-04-12 05:00:56 -0700288 try:
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000289 lines = iter(test_process.stdout.readline, '')
290 for result in ExtractTestRuns(lines, echo=True):
Artem Titovb1f2d602019-07-10 14:40:58 +0200291 (android_device, test_name, reference_file, degraded_file,
292 perf_results_file) = result
oprypin92220ff2017-03-23 03:40:03 -0700293
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000294 adb_prefix = (args.adb_path,)
295 if android_device:
296 adb_prefix += ('-s', android_device)
oprypin92220ff2017-03-23 03:40:03 -0700297
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000298 reference_file = _GetFile(reference_file, out_dir,
299 android=args.android, adb_prefix=adb_prefix)
300 degraded_file = _GetFile(degraded_file, out_dir, move=True,
301 android=args.android, adb_prefix=adb_prefix)
oprypin92220ff2017-03-23 03:40:03 -0700302
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000303 analyzer_results = analyzer.func(analyzer.executable,
304 reference_file, degraded_file)
305 for metric, (value, units) in analyzer_results.items():
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100306 hist = histograms.CreateHistogram(metric, units, [value])
307 user_story = generic_set.GenericSet([test_name])
308 hist.diagnostics[reserved_infos.STORIES.name] = user_story
309
310 # Output human readable results.
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000311 print 'RESULT %s: %s= %s %s' % (metric, test_name, value, units)
oprypin92220ff2017-03-23 03:40:03 -0700312
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000313 if args.remove:
314 os.remove(reference_file)
315 os.remove(degraded_file)
oprypinf2501002017-04-12 05:00:56 -0700316 finally:
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000317 test_process.terminate()
Artem Titovb1f2d602019-07-10 14:40:58 +0200318 if perf_results_file:
319 perf_results_file = _GetFile(perf_results_file, out_dir, move=True,
320 android=args.android, adb_prefix=adb_prefix)
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100321 _MergeInPerfResultsFromCcTests(histograms, perf_results_file)
Artem Titovb1f2d602019-07-10 14:40:58 +0200322 if args.remove:
323 os.remove(perf_results_file)
oprypin6d305ba2017-03-30 04:01:30 -0700324
Edward Lemured7b4ff2018-02-01 17:23:58 +0100325 if args.isolated_script_test_perf_output:
Patrik Höglund3b4bbf52020-03-26 08:41:09 +0100326 with open(args.isolated_script_test_perf_output, 'wb') as f:
327 f.write(histograms.AsProto().SerializeToString())
Edward Lemurb4017712018-01-15 14:21:09 +0100328
oprypin92220ff2017-03-23 03:40:03 -0700329 return test_process.wait()
kjellander8f8d1a02017-03-06 04:01:16 -0800330
331
332if __name__ == '__main__':
333 sys.exit(main())