blob: d665c7601b7acf7a91ef3708fd521c4165e0891f [file] [log] [blame]
José Fonseca0b956fd2011-06-04 22:51:45 +01001#!/usr/bin/env python
2##########################################################################
3#
4# Copyright 2011 Jose Fonseca
5# All Rights Reserved.
6#
7# Permission is hereby granted, free of charge, to any person obtaining a copy
8# of this software and associated documentation files (the 'Software'), to deal
9# in the Software without restriction, including without limitation the rights
10# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11# copies of the Software, and to permit persons to whom the Software is
12# furnished to do so, subject to the following conditions:
13#
14# The above copyright notice and this permission notice shall be included in
15# all copies or substantial portions of the Software.
16#
17# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23# THE SOFTWARE.
24#
25##########################################################################/
26
27'''Run two retrace instances in parallel, comparing generated snapshots.
28'''
29
30
31import optparse
32import os.path
José Fonseca0b956fd2011-06-04 22:51:45 +010033import subprocess
34import platform
35import sys
José Fonseca0b956fd2011-06-04 22:51:45 +010036
José Fonsecabcca5f72011-09-06 00:07:41 +010037from PIL import Image
38
José Fonseca0b956fd2011-06-04 22:51:45 +010039from snapdiff import Comparer
José Fonseca01908962012-03-16 09:56:09 +000040from highlight import AutoHighlighter
José Fonseca0b956fd2011-06-04 22:51:45 +010041import jsondiff
42
43
44# Null file, to use when we're not interested in subprocesses output
45if platform.system() == 'Windows':
46 NULL = open('NUL:', 'wt')
47else:
48 NULL = open('/dev/null', 'wt')
49
50
51class Setup:
52
53 def __init__(self, args, env=None):
54 self.args = args
55 self.env = env
56
José Fonseca20303032011-10-20 16:12:10 +020057 def _retrace(self, args):
José Fonseca0b956fd2011-06-04 22:51:45 +010058 cmd = [
59 options.retrace,
José Fonseca20303032011-10-20 16:12:10 +020060 ] + args + self.args
61 try:
62 return subprocess.Popen(cmd, env=self.env, stdout=subprocess.PIPE, stderr=NULL)
63 except OSError, ex:
64 sys.stderr.write('error: failed to execute %s: %s\n' % (cmd[0], ex.strerror))
65 sys.exit(1)
66
67 def retrace(self):
68 return self._retrace([
José Fonsecabcca5f72011-09-06 00:07:41 +010069 '-s', '-',
José Fonseca0b956fd2011-06-04 22:51:45 +010070 '-S', options.snapshot_frequency,
José Fonseca20303032011-10-20 16:12:10 +020071 ])
José Fonseca0b956fd2011-06-04 22:51:45 +010072
73 def dump_state(self, call_no):
74 '''Get the state dump at the specified call no.'''
75
José Fonseca20303032011-10-20 16:12:10 +020076 p = self._retrace([
José Fonseca0b956fd2011-06-04 22:51:45 +010077 '-D', str(call_no),
José Fonseca20303032011-10-20 16:12:10 +020078 ])
José Fonseca0b956fd2011-06-04 22:51:45 +010079 state = jsondiff.load(p.stdout)
80 p.wait()
José Fonsecab96ab8e2011-09-06 10:22:56 +010081 return state.get('parameters', {})
José Fonseca0b956fd2011-06-04 22:51:45 +010082
José Fonsecad8ea58f2012-02-09 14:35:27 +000083 def diff_state(self, ref_call_no, src_call_no, stream):
José Fonseca36fa87c2011-09-06 00:15:32 +010084 '''Compare the state between two calls.'''
85
86 ref_state = self.dump_state(ref_call_no)
87 src_state = self.dump_state(src_call_no)
José Fonsecab96ab8e2011-09-06 10:22:56 +010088
José Fonsecad8ea58f2012-02-09 14:35:27 +000089 stream.flush()
90 differ = jsondiff.Differ(stream)
José Fonseca36fa87c2011-09-06 00:15:32 +010091 differ.visit(ref_state, src_state)
José Fonsecad8ea58f2012-02-09 14:35:27 +000092 stream.write('\n')
José Fonseca36fa87c2011-09-06 00:15:32 +010093
José Fonseca0b956fd2011-06-04 22:51:45 +010094
José Fonsecabcca5f72011-09-06 00:07:41 +010095def read_pnm(stream):
96 '''Read a PNM from the stream, and return the image object, and the comment.'''
97
98 magic = stream.readline()
99 if not magic:
100 return None, None
José Fonseca0ee87892012-10-30 15:54:04 +0000101 magic = magic.rstrip()
102 if magic == 'P5':
103 channels = 1
104 mode = 'L'
105 elif magic == 'P6':
106 channels = 3
107 mode = 'RGB'
108 else:
109 raise Exception('Unsupported magic `%s`' % magic)
José Fonsecabcca5f72011-09-06 00:07:41 +0100110 comment = ''
111 line = stream.readline()
112 while line.startswith('#'):
113 comment += line[1:]
114 line = stream.readline()
115 width, height = map(int, line.strip().split())
116 maximum = int(stream.readline().strip())
117 assert maximum == 255
José Fonseca0ee87892012-10-30 15:54:04 +0000118 data = stream.read(height * width * channels)
119 image = Image.frombuffer(mode, (width, height), data, 'raw', mode, 0, 1)
José Fonsecabcca5f72011-09-06 00:07:41 +0100120 return image, comment
121
122
José Fonseca0b956fd2011-06-04 22:51:45 +0100123def parse_env(optparser, entries):
124 '''Translate a list of NAME=VALUE entries into an environment dictionary.'''
125
126 env = os.environ.copy()
127 for entry in entries:
128 try:
129 name, var = entry.split('=', 1)
130 except Exception:
131 optparser.error('invalid environment entry %r' % entry)
132 env[name] = var
133 return env
134
135
136def main():
137 '''Main program.
138 '''
139
140 global options
141
142 # Parse command line options
143 optparser = optparse.OptionParser(
144 usage='\n\t%prog [options] -- [glretrace options] <trace>',
145 version='%%prog')
146 optparser.add_option(
147 '-r', '--retrace', metavar='PROGRAM',
148 type='string', dest='retrace', default='glretrace',
149 help='retrace command [default: %default]')
150 optparser.add_option(
151 '--ref-env', metavar='NAME=VALUE',
152 type='string', action='append', dest='ref_env', default=[],
José Fonsecabcca5f72011-09-06 00:07:41 +0100153 help='add variable to reference environment')
José Fonseca0b956fd2011-06-04 22:51:45 +0100154 optparser.add_option(
155 '--src-env', metavar='NAME=VALUE',
156 type='string', action='append', dest='src_env', default=[],
José Fonsecabcca5f72011-09-06 00:07:41 +0100157 help='add variable to source environment')
José Fonseca0b956fd2011-06-04 22:51:45 +0100158 optparser.add_option(
159 '--diff-prefix', metavar='PATH',
160 type='string', dest='diff_prefix', default='.',
José Fonsecabcca5f72011-09-06 00:07:41 +0100161 help='prefix for the difference images')
José Fonseca0b956fd2011-06-04 22:51:45 +0100162 optparser.add_option(
163 '-t', '--threshold', metavar='BITS',
164 type="float", dest="threshold", default=12.0,
165 help="threshold precision [default: %default]")
166 optparser.add_option(
José Fonseca225193d2012-01-26 19:08:32 +0000167 '-S', '--snapshot-frequency', metavar='CALLSET',
José Fonseca0b956fd2011-06-04 22:51:45 +0100168 type="string", dest="snapshot_frequency", default='draw',
José Fonseca225193d2012-01-26 19:08:32 +0000169 help="calls to compare [default: %default]")
José Fonsecad8ea58f2012-02-09 14:35:27 +0000170 optparser.add_option(
171 '-o', '--output', metavar='FILE',
172 type="string", dest="output",
173 help="output file [default: stdout]")
José Fonseca0b956fd2011-06-04 22:51:45 +0100174
175 (options, args) = optparser.parse_args(sys.argv[1:])
176 ref_env = parse_env(optparser, options.ref_env)
177 src_env = parse_env(optparser, options.src_env)
178 if not args:
179 optparser.error("incorrect number of arguments")
180
181 ref_setup = Setup(args, ref_env)
182 src_setup = Setup(args, src_env)
183
José Fonsecad8ea58f2012-02-09 14:35:27 +0000184 if options.output:
185 output = open(options.output, 'wt')
186 else:
187 output = sys.stdout
188
José Fonseca01908962012-03-16 09:56:09 +0000189 highligher = AutoHighlighter(output)
José Fonsecab96ab8e2011-09-06 10:22:56 +0100190
191 highligher.write('call\tprecision\n')
José Fonseca0b956fd2011-06-04 22:51:45 +0100192
José Fonseca0b956fd2011-06-04 22:51:45 +0100193 last_bad = -1
José Fonseca36fa87c2011-09-06 00:15:32 +0100194 last_good = 0
José Fonsecabcca5f72011-09-06 00:07:41 +0100195 ref_proc = ref_setup.retrace()
José Fonseca0b956fd2011-06-04 22:51:45 +0100196 try:
José Fonsecabcca5f72011-09-06 00:07:41 +0100197 src_proc = src_setup.retrace()
José Fonseca0b956fd2011-06-04 22:51:45 +0100198 try:
José Fonsecabcca5f72011-09-06 00:07:41 +0100199 while True:
200 # Get the reference image
201 ref_image, ref_comment = read_pnm(ref_proc.stdout)
202 if ref_image is None:
203 break
José Fonseca0b956fd2011-06-04 22:51:45 +0100204
José Fonsecabcca5f72011-09-06 00:07:41 +0100205 # Get the source image
206 src_image, src_comment = read_pnm(src_proc.stdout)
207 if src_image is None:
208 break
José Fonseca0b956fd2011-06-04 22:51:45 +0100209
José Fonsecabcca5f72011-09-06 00:07:41 +0100210 assert ref_comment == src_comment
José Fonseca0b956fd2011-06-04 22:51:45 +0100211
José Fonsecabcca5f72011-09-06 00:07:41 +0100212 call_no = int(ref_comment.strip())
213
214 # Compare the two images
215 comparer = Comparer(ref_image, src_image)
216 precision = comparer.precision()
217
José Fonsecab96ab8e2011-09-06 10:22:56 +0100218 mismatch = precision < options.threshold
José Fonsecabcca5f72011-09-06 00:07:41 +0100219
José Fonsecab96ab8e2011-09-06 10:22:56 +0100220 if mismatch:
221 highligher.color(highligher.red)
222 highligher.bold()
223 highligher.write('%u\t%f\n' % (call_no, precision))
224 if mismatch:
225 highligher.normal()
226
227 if mismatch:
José Fonsecabcca5f72011-09-06 00:07:41 +0100228 if options.diff_prefix:
229 prefix = os.path.join(options.diff_prefix, '%010u' % call_no)
230 prefix_dir = os.path.dirname(prefix)
231 if not os.path.isdir(prefix_dir):
232 os.makedirs(prefix_dir)
233 ref_image.save(prefix + '.ref.png')
234 src_image.save(prefix + '.src.png')
235 comparer.write_diff(prefix + '.diff.png')
236 if last_bad < last_good:
José Fonsecad8ea58f2012-02-09 14:35:27 +0000237 src_setup.diff_state(last_good, call_no, output)
José Fonsecabcca5f72011-09-06 00:07:41 +0100238 last_bad = call_no
239 else:
240 last_good = call_no
241
José Fonsecab96ab8e2011-09-06 10:22:56 +0100242 highligher.flush()
José Fonseca0b956fd2011-06-04 22:51:45 +0100243 finally:
José Fonsecabcca5f72011-09-06 00:07:41 +0100244 src_proc.terminate()
José Fonseca0b956fd2011-06-04 22:51:45 +0100245 finally:
José Fonsecabcca5f72011-09-06 00:07:41 +0100246 ref_proc.terminate()
José Fonseca0b956fd2011-06-04 22:51:45 +0100247
248
249if __name__ == '__main__':
250 main()