blob: 07ddc7b90690b1fc8563371bb833343031710bcf [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')
kjellander8f8d1a02017-03-06 04:01:16 -080057 args = parser.parse_args()
58 return args
59
60
oprypin92220ff2017-03-23 03:40:03 -070061def _GetPlatform():
62 if sys.platform == 'win32':
63 return 'win'
64 elif sys.platform == 'darwin':
65 return 'mac'
66 elif sys.platform.startswith('linux'):
67 return 'linux'
68
69
Edward Lemurb0250f02017-10-04 14:41:17 +020070def _GetExtension():
71 return '.exe' if sys.platform == 'win32' else ''
72
73
74def _GetPathToTools():
Henrik Kjellander90fd7d82017-05-09 08:30:10 +020075 tools_dir = os.path.join(SRC_DIR, 'tools_webrtc')
oprypin92220ff2017-03-23 03:40:03 -070076 toolchain_dir = os.path.join(tools_dir, 'audio_quality')
77
Edward Lemurb0250f02017-10-04 14:41:17 +020078 platform = _GetPlatform()
79 ext = _GetExtension()
Edward Lemurbb1222f2017-10-03 12:33:38 +000080
Edward Lemurb0250f02017-10-04 14:41:17 +020081 pesq_path = os.path.join(toolchain_dir, platform, 'pesq' + ext)
82 if not os.path.isfile(pesq_path):
83 pesq_path = None
84
85 polqa_path = os.path.join(toolchain_dir, platform, 'PolqaOem64' + ext)
86 if not os.path.isfile(polqa_path):
87 polqa_path = None
88
89 if (platform != 'mac' and not polqa_path) or not pesq_path:
90 logging.error(NO_TOOLS_ERROR_MESSAGE,
91 toolchain_dir,
92 os.path.join(tools_dir, 'download_tools.py'),
93 toolchain_dir)
94
oprypinf2501002017-04-12 05:00:56 -070095 return pesq_path, polqa_path
oprypin92220ff2017-03-23 03:40:03 -070096
97
oprypinabd101b2017-04-06 23:21:30 -070098def ExtractTestRuns(lines, echo=False):
99 """Extracts information about tests from the output of a test runner.
100
101 Produces tuples (android_device, test_name, reference_file, degraded_file).
102 """
103 for line in lines:
104 if echo:
105 sys.stdout.write(line)
106
107 # Output from Android has a prefix with the device name.
108 android_prefix_re = r'(?:I\b.+\brun_tests_on_device\((.+?)\)\s*)?'
109 test_re = r'^' + android_prefix_re + r'TEST (\w+) ([^ ]+?) ([^ ]+?)\s*$'
110
111 match = re.search(test_re, line)
112 if match:
113 yield match.groups()
114
115
116def _GetFile(file_path, out_dir, move=False,
117 android=False, adb_prefix=('adb',)):
oprypin6d305ba2017-03-30 04:01:30 -0700118 out_file_name = os.path.basename(file_path)
119 out_file_path = os.path.join(out_dir, out_file_name)
120
121 if android:
oprypinabd101b2017-04-06 23:21:30 -0700122 # Pull the file from the connected Android device.
123 adb_command = adb_prefix + ('pull', file_path, out_dir)
oprypin6d305ba2017-03-30 04:01:30 -0700124 subprocess.check_call(_LogCommand(adb_command))
oprypinabd101b2017-04-06 23:21:30 -0700125 if move:
126 # Remove that file.
127 adb_command = adb_prefix + ('shell', 'rm', file_path)
128 subprocess.check_call(_LogCommand(adb_command))
oprypin6d305ba2017-03-30 04:01:30 -0700129 elif os.path.abspath(file_path) != os.path.abspath(out_file_path):
oprypinabd101b2017-04-06 23:21:30 -0700130 if move:
131 shutil.move(file_path, out_file_path)
132 else:
133 shutil.copy(file_path, out_file_path)
oprypin6d305ba2017-03-30 04:01:30 -0700134
135 return out_file_path
136
137
oprypinf2501002017-04-12 05:00:56 -0700138def _RunPesq(executable_path, reference_file, degraded_file,
139 sample_rate_hz=16000):
140 directory = os.path.dirname(reference_file)
141 assert os.path.dirname(degraded_file) == directory
142
143 # Analyze audio.
144 command = [executable_path, '+%d' % sample_rate_hz,
145 os.path.basename(reference_file),
146 os.path.basename(degraded_file)]
147 # Need to provide paths in the current directory due to a bug in PESQ:
148 # On Mac, for some 'path/to/file.wav', if 'file.wav' is longer than
149 # 'path/to', PESQ crashes.
150 out = subprocess.check_output(_LogCommand(command),
151 cwd=directory, stderr=subprocess.STDOUT)
152
153 # Find the scores in stdout of PESQ.
154 match = re.search(
155 r'Prediction \(Raw MOS, MOS-LQO\):\s+=\s+([\d.]+)\s+([\d.]+)', out)
156 if match:
157 raw_mos, _ = match.groups()
158
159 return {'pesq_mos': (raw_mos, 'score')}
160 else:
161 logging.error('PESQ: %s', out.splitlines()[-1])
162 return {}
163
164
165def _RunPolqa(executable_path, reference_file, degraded_file):
166 # Analyze audio.
167 command = [executable_path, '-q', '-LC', 'NB',
168 '-Ref', reference_file, '-Test', degraded_file]
Edward Lemurb0250f02017-10-04 14:41:17 +0200169 process = subprocess.Popen(_LogCommand(command),
170 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
oprypinf2501002017-04-12 05:00:56 -0700171 out, err = process.communicate()
172
173 # Find the scores in stdout of POLQA.
174 match = re.search(r'\bMOS-LQO:\s+([\d.]+)', out)
175
176 if process.returncode != 0 or not match:
177 if process.returncode == 2:
178 logging.warning('%s (2)', err.strip())
179 logging.warning('POLQA license error, skipping test.')
180 else:
181 logging.error('%s (%d)', err.strip(), process.returncode)
182 return {}
183
184 mos_lqo, = match.groups()
185 return {'polqa_mos_lqo': (mos_lqo, 'score')}
186
187
188Analyzer = collections.namedtuple('Analyzer', ['func', 'executable',
189 'sample_rate_hz'])
190
191
kjellander8f8d1a02017-03-06 04:01:16 -0800192def main():
193 # pylint: disable=W0101
194 logging.basicConfig(level=logging.INFO)
195
196 args = _ParseArgs()
197
Edward Lemurb0250f02017-10-04 14:41:17 +0200198 pesq_path, polqa_path = _GetPathToTools()
199 if pesq_path is None:
200 return 1
kjellander8f8d1a02017-03-06 04:01:16 -0800201
oprypin6d305ba2017-03-30 04:01:30 -0700202 out_dir = os.path.join(args.build_dir, '..')
203 if args.android:
204 test_command = [os.path.join(args.build_dir, 'bin',
205 'run_low_bandwidth_audio_test'), '-v']
206 else:
207 test_command = [os.path.join(args.build_dir, 'low_bandwidth_audio_test')]
oprypin92220ff2017-03-23 03:40:03 -0700208
oprypinf2501002017-04-12 05:00:56 -0700209 analyzers = [Analyzer(_RunPesq, pesq_path, 16000)]
210 # Check if POLQA can run at all, or skip the 48 kHz tests entirely.
211 example_path = os.path.join(SRC_DIR, 'resources',
212 'voice_engine', 'audio_tiny48.wav')
Edward Lemurb0250f02017-10-04 14:41:17 +0200213 if polqa_path and _RunPolqa(polqa_path, example_path, example_path):
oprypinf2501002017-04-12 05:00:56 -0700214 analyzers.append(Analyzer(_RunPolqa, polqa_path, 48000))
oprypin92220ff2017-03-23 03:40:03 -0700215
oprypinf2501002017-04-12 05:00:56 -0700216 for analyzer in analyzers:
217 # Start the test executable that produces audio files.
218 test_process = subprocess.Popen(
219 _LogCommand(test_command + ['--sample_rate_hz=%d' %
220 analyzer.sample_rate_hz]),
oprypin4f1f4582017-06-14 09:35:11 -0700221 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
oprypinf2501002017-04-12 05:00:56 -0700222 try:
223 lines = iter(test_process.stdout.readline, '')
224 for result in ExtractTestRuns(lines, echo=True):
225 (android_device, test_name, reference_file, degraded_file) = result
oprypin92220ff2017-03-23 03:40:03 -0700226
oprypinf2501002017-04-12 05:00:56 -0700227 adb_prefix = (args.adb_path,)
228 if android_device:
229 adb_prefix += ('-s', android_device)
oprypin92220ff2017-03-23 03:40:03 -0700230
oprypinf2501002017-04-12 05:00:56 -0700231 reference_file = _GetFile(reference_file, out_dir,
232 android=args.android, adb_prefix=adb_prefix)
233 degraded_file = _GetFile(degraded_file, out_dir, move=True,
234 android=args.android, adb_prefix=adb_prefix)
oprypin92220ff2017-03-23 03:40:03 -0700235
oprypinf2501002017-04-12 05:00:56 -0700236 analyzer_results = analyzer.func(analyzer.executable,
237 reference_file, degraded_file)
238 for metric, (value, units) in analyzer_results.items():
239 # Output a result for the perf dashboard.
240 print 'RESULT %s: %s= %s %s' % (metric, test_name, value, units)
oprypin92220ff2017-03-23 03:40:03 -0700241
oprypinf2501002017-04-12 05:00:56 -0700242 if args.remove:
243 os.remove(reference_file)
244 os.remove(degraded_file)
245 finally:
246 test_process.terminate()
oprypin6d305ba2017-03-30 04:01:30 -0700247
oprypin92220ff2017-03-23 03:40:03 -0700248 return test_process.wait()
kjellander8f8d1a02017-03-06 04:01:16 -0800249
250
251if __name__ == '__main__':
252 sys.exit(main())