blob: 3606e682224b0ce0606d6571a74aad90450969bb [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__))
28SRC_DIR = os.path.normpath(os.path.join(SCRIPT_DIR, os.pardir, os.pardir,
29 os.pardir))
30
31
oprypin92220ff2017-03-23 03:40:03 -070032def _LogCommand(command):
33 logging.info('Running %r', command)
34 return command
kjellander8f8d1a02017-03-06 04:01:16 -080035
36
37def _ParseArgs():
38 parser = argparse.ArgumentParser(description='Run low-bandwidth audio tests.')
39 parser.add_argument('build_dir',
40 help='Path to the build directory (e.g. out/Release).')
oprypin92220ff2017-03-23 03:40:03 -070041 parser.add_argument('--remove', action='store_true',
42 help='Remove output audio files after testing.')
oprypin6d305ba2017-03-30 04:01:30 -070043 parser.add_argument('--android', action='store_true',
44 help='Perform the test on a connected Android device instead.')
45 parser.add_argument('--adb-path', help='Path to adb binary.', default='adb')
kjellander8f8d1a02017-03-06 04:01:16 -080046 args = parser.parse_args()
47 return args
48
49
oprypin92220ff2017-03-23 03:40:03 -070050def _GetPlatform():
51 if sys.platform == 'win32':
52 return 'win'
53 elif sys.platform == 'darwin':
54 return 'mac'
55 elif sys.platform.startswith('linux'):
56 return 'linux'
57
58
oprypin92220ff2017-03-23 03:40:03 -070059def _DownloadTools():
Henrik Kjellander90fd7d82017-05-09 08:30:10 +020060 tools_dir = os.path.join(SRC_DIR, 'tools_webrtc')
oprypin92220ff2017-03-23 03:40:03 -070061 toolchain_dir = os.path.join(tools_dir, 'audio_quality')
62
oprypinf2501002017-04-12 05:00:56 -070063 # Download PESQ and POLQA.
oprypin92220ff2017-03-23 03:40:03 -070064 download_script = os.path.join(tools_dir, 'download_tools.py')
65 command = [sys.executable, download_script, toolchain_dir]
66 subprocess.check_call(_LogCommand(command))
67
oprypin6d305ba2017-03-30 04:01:30 -070068 pesq_path = os.path.join(toolchain_dir, _GetPlatform(), 'pesq')
oprypinf2501002017-04-12 05:00:56 -070069 polqa_path = os.path.join(toolchain_dir, _GetPlatform(), 'PolqaOem64')
70 return pesq_path, polqa_path
oprypin92220ff2017-03-23 03:40:03 -070071
72
oprypinabd101b2017-04-06 23:21:30 -070073def ExtractTestRuns(lines, echo=False):
74 """Extracts information about tests from the output of a test runner.
75
76 Produces tuples (android_device, test_name, reference_file, degraded_file).
77 """
78 for line in lines:
79 if echo:
80 sys.stdout.write(line)
81
82 # Output from Android has a prefix with the device name.
83 android_prefix_re = r'(?:I\b.+\brun_tests_on_device\((.+?)\)\s*)?'
84 test_re = r'^' + android_prefix_re + r'TEST (\w+) ([^ ]+?) ([^ ]+?)\s*$'
85
86 match = re.search(test_re, line)
87 if match:
88 yield match.groups()
89
90
91def _GetFile(file_path, out_dir, move=False,
92 android=False, adb_prefix=('adb',)):
oprypin6d305ba2017-03-30 04:01:30 -070093 out_file_name = os.path.basename(file_path)
94 out_file_path = os.path.join(out_dir, out_file_name)
95
96 if android:
oprypinabd101b2017-04-06 23:21:30 -070097 # Pull the file from the connected Android device.
98 adb_command = adb_prefix + ('pull', file_path, out_dir)
oprypin6d305ba2017-03-30 04:01:30 -070099 subprocess.check_call(_LogCommand(adb_command))
oprypinabd101b2017-04-06 23:21:30 -0700100 if move:
101 # Remove that file.
102 adb_command = adb_prefix + ('shell', 'rm', file_path)
103 subprocess.check_call(_LogCommand(adb_command))
oprypin6d305ba2017-03-30 04:01:30 -0700104 elif os.path.abspath(file_path) != os.path.abspath(out_file_path):
oprypinabd101b2017-04-06 23:21:30 -0700105 if move:
106 shutil.move(file_path, out_file_path)
107 else:
108 shutil.copy(file_path, out_file_path)
oprypin6d305ba2017-03-30 04:01:30 -0700109
110 return out_file_path
111
112
oprypinf2501002017-04-12 05:00:56 -0700113def _RunPesq(executable_path, reference_file, degraded_file,
114 sample_rate_hz=16000):
115 directory = os.path.dirname(reference_file)
116 assert os.path.dirname(degraded_file) == directory
117
118 # Analyze audio.
119 command = [executable_path, '+%d' % sample_rate_hz,
120 os.path.basename(reference_file),
121 os.path.basename(degraded_file)]
122 # Need to provide paths in the current directory due to a bug in PESQ:
123 # On Mac, for some 'path/to/file.wav', if 'file.wav' is longer than
124 # 'path/to', PESQ crashes.
125 out = subprocess.check_output(_LogCommand(command),
126 cwd=directory, stderr=subprocess.STDOUT)
127
128 # Find the scores in stdout of PESQ.
129 match = re.search(
130 r'Prediction \(Raw MOS, MOS-LQO\):\s+=\s+([\d.]+)\s+([\d.]+)', out)
131 if match:
132 raw_mos, _ = match.groups()
133
134 return {'pesq_mos': (raw_mos, 'score')}
135 else:
136 logging.error('PESQ: %s', out.splitlines()[-1])
137 return {}
138
139
140def _RunPolqa(executable_path, reference_file, degraded_file):
141 # Analyze audio.
142 command = [executable_path, '-q', '-LC', 'NB',
143 '-Ref', reference_file, '-Test', degraded_file]
144 try:
145 process = subprocess.Popen(_LogCommand(command),
146 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
147 except OSError as e:
148 if e.errno == os.errno.ENOENT:
149 logging.warning('POLQA executable missing, skipping test.')
150 return {}
151 else:
152 raise
153 out, err = process.communicate()
154
155 # Find the scores in stdout of POLQA.
156 match = re.search(r'\bMOS-LQO:\s+([\d.]+)', out)
157
158 if process.returncode != 0 or not match:
159 if process.returncode == 2:
160 logging.warning('%s (2)', err.strip())
161 logging.warning('POLQA license error, skipping test.')
162 else:
163 logging.error('%s (%d)', err.strip(), process.returncode)
164 return {}
165
166 mos_lqo, = match.groups()
167 return {'polqa_mos_lqo': (mos_lqo, 'score')}
168
169
170Analyzer = collections.namedtuple('Analyzer', ['func', 'executable',
171 'sample_rate_hz'])
172
173
kjellander8f8d1a02017-03-06 04:01:16 -0800174def main():
175 # pylint: disable=W0101
176 logging.basicConfig(level=logging.INFO)
177
178 args = _ParseArgs()
179
oprypinf2501002017-04-12 05:00:56 -0700180 pesq_path, polqa_path = _DownloadTools()
kjellander8f8d1a02017-03-06 04:01:16 -0800181
oprypin6d305ba2017-03-30 04:01:30 -0700182 out_dir = os.path.join(args.build_dir, '..')
183 if args.android:
184 test_command = [os.path.join(args.build_dir, 'bin',
185 'run_low_bandwidth_audio_test'), '-v']
186 else:
187 test_command = [os.path.join(args.build_dir, 'low_bandwidth_audio_test')]
oprypin92220ff2017-03-23 03:40:03 -0700188
oprypinf2501002017-04-12 05:00:56 -0700189 analyzers = [Analyzer(_RunPesq, pesq_path, 16000)]
190 # Check if POLQA can run at all, or skip the 48 kHz tests entirely.
191 example_path = os.path.join(SRC_DIR, 'resources',
192 'voice_engine', 'audio_tiny48.wav')
193 if _RunPolqa(polqa_path, example_path, example_path):
194 analyzers.append(Analyzer(_RunPolqa, polqa_path, 48000))
oprypin92220ff2017-03-23 03:40:03 -0700195
oprypinf2501002017-04-12 05:00:56 -0700196 for analyzer in analyzers:
197 # Start the test executable that produces audio files.
198 test_process = subprocess.Popen(
199 _LogCommand(test_command + ['--sample_rate_hz=%d' %
200 analyzer.sample_rate_hz]),
201 stdout=subprocess.PIPE)
202 try:
203 lines = iter(test_process.stdout.readline, '')
204 for result in ExtractTestRuns(lines, echo=True):
205 (android_device, test_name, reference_file, degraded_file) = result
oprypin92220ff2017-03-23 03:40:03 -0700206
oprypinf2501002017-04-12 05:00:56 -0700207 adb_prefix = (args.adb_path,)
208 if android_device:
209 adb_prefix += ('-s', android_device)
oprypin92220ff2017-03-23 03:40:03 -0700210
oprypinf2501002017-04-12 05:00:56 -0700211 reference_file = _GetFile(reference_file, out_dir,
212 android=args.android, adb_prefix=adb_prefix)
213 degraded_file = _GetFile(degraded_file, out_dir, move=True,
214 android=args.android, adb_prefix=adb_prefix)
oprypin92220ff2017-03-23 03:40:03 -0700215
oprypinf2501002017-04-12 05:00:56 -0700216 analyzer_results = analyzer.func(analyzer.executable,
217 reference_file, degraded_file)
218 for metric, (value, units) in analyzer_results.items():
219 # Output a result for the perf dashboard.
220 print 'RESULT %s: %s= %s %s' % (metric, test_name, value, units)
oprypin92220ff2017-03-23 03:40:03 -0700221
oprypinf2501002017-04-12 05:00:56 -0700222 if args.remove:
223 os.remove(reference_file)
224 os.remove(degraded_file)
225 finally:
226 test_process.terminate()
oprypin6d305ba2017-03-30 04:01:30 -0700227
oprypin92220ff2017-03-23 03:40:03 -0700228 return test_process.wait()
kjellander8f8d1a02017-03-06 04:01:16 -0800229
230
231if __name__ == '__main__':
232 sys.exit(main())