blob: cdeda25d70da9b8c23319cc36cbb08ac90e6bc3d [file] [log] [blame]
Nigel Taod2075ce2018-04-25 15:26:29 +10001// Copyright 2018 The Wuffs Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// This file contains a hand-written C benchmark of different strategies for
16// decoding PNG data.
17//
18// For a PNG image with width W and height H, the H rows can be decompressed
19// one-at-a-time or all-at-once. Roughly speaking, this corresponds to H versus
20// 1 call into the zlib decoder. The former (call it "fragmented dst") requires
21// less scratch-space memory than the latter ("full dst"): 2 * bytes_per_row
22// instead of H * bytes_per row, but the latter can be faster.
23//
24// The zlib-compressed data can be split into multiple IDAT chunks. Similarly,
25// these chunks can be decompressed separately ("fragmented IDAT") or together
26// ("full IDAT"), again providing a memory vs speed trade-off.
27//
28// This program reports the speed of combining the independent frag/full dst
29// and frag/full IDAT techniques.
30//
31// For example, with gcc 7.3 (and -O3) as of April 2018:
32//
33// On ../test/data/hat.png (90 × 112 pixels):
34// name time/op relative
35// FragDstFragIDAT/gcc 203µs ± 1% 1.00x
36// FragDstFullIDAT/gcc 203µs ± 0% 1.00x
37// FullDstFragIDAT/gcc 170µs ± 0% 1.19x
38// FullDstFullIDAT/gcc 147µs ± 0% 1.38x
39//
40// On ../test/data/hibiscus.png (312 × 442 pixels):
41// name time/op relative
42// FragDstFragIDAT/gcc 2.62ms ± 1% 1.00x
43// FragDstFullIDAT/gcc 2.61ms ± 1% 1.00x
44// FullDstFragIDAT/gcc 2.44ms ± 0% 1.07x
45// FullDstFullIDAT/gcc 2.03ms ± 1% 1.29x
46//
47// On ../test/data/harvesters.png (1165 × 859 pixels):
48// name time/op relative
49// FragDstFragIDAT/gcc 18.3ms ± 0% 1.00x
50// FragDstFullIDAT/gcc 18.3ms ± 1% 1.00x
51// FullDstFragIDAT/gcc 17.1ms ± 0% 1.07x
52// FullDstFullIDAT/gcc 13.9ms ± 0% 1.32x
53
54#include <errno.h>
55#include <inttypes.h>
56#include <stdio.h>
57#include <string.h>
58#include <sys/time.h>
59#include <unistd.h>
60
61// If building this program in an environment that doesn't easily accomodate
62// relative includes, you can use the script/inline-c-relative-includes.go
63// program to generate a stand-alone C file.
64#include "../gen/c/std/deflate.c"
65#include "../gen/c/std/zlib.c"
66
67// The order matters here. Clang also defines "__GNUC__".
68#if defined(__clang__)
69const char* cc = "clang";
70const char* cc_version = __clang_version__;
71#elif defined(__GNUC__)
72const char* cc = "gcc";
73const char* cc_version = __VERSION__;
74#elif defined(_MSC_VER)
75const char* cc = "cl";
76const char* cc_version = "???";
77#else
78const char* cc = "cc";
79const char* cc_version = "???";
80#endif
81
82static inline uint32_t load_u32be(uint8_t* p) {
83 return ((uint32_t)(p[0]) << 24) | ((uint32_t)(p[1]) << 16) |
84 ((uint32_t)(p[2]) << 8) | ((uint32_t)(p[3]) << 0);
85}
86
87// Limit the input PNG image (and therefore its IDAT data) to (64 MiB - 1 byte)
88// compressed, in up to 1024 IDAT chunks, and 256 MiB and 16384 × 16384 pixels
89// uncompressed. This is a limitation of this program (which uses the Wuffs
90// standard library), not a limitation of Wuffs per se.
91#define DST_BUFFER_SIZE (256 * 1024 * 1024)
92#define SRC_BUFFER_SIZE (64 * 1024 * 1024)
93#define MAX_DIMENSION (16384)
94#define MAX_IDAT_CHUNKS (1024)
95
96uint8_t dst_buffer[DST_BUFFER_SIZE] = {0};
97size_t dst_len = 0;
98uint8_t src_buffer[SRC_BUFFER_SIZE] = {0};
99size_t src_len = 0;
100uint8_t idat_buffer[SRC_BUFFER_SIZE] = {0};
101// The n'th IDAT chunk data (where n is a zero-based count) is in
102// idat_buffer[i:j], where i = idat_splits[n+0] and j = idat_splits[n+1].
103size_t idat_splits[MAX_IDAT_CHUNKS + 1] = {0};
104uint32_t num_idat_chunks = 0;
105
106uint32_t width = 0;
107uint32_t height = 0;
108uint64_t bytes_per_pixel = 0;
109uint64_t bytes_per_row = 0;
110uint64_t bytes_per_frame = 0;
111
112const char* read_stdin() {
113 while (src_len < SRC_BUFFER_SIZE) {
114 const int stdin_fd = 0;
115 ssize_t n = read(stdin_fd, src_buffer + src_len, SRC_BUFFER_SIZE - src_len);
116 if (n > 0) {
117 src_len += n;
118 } else if (n == 0) {
119 return NULL;
120 } else if (errno == EINTR) {
121 // No-op.
122 } else {
123 return strerror(errno);
124 }
125 }
126 return "input is too large";
127}
128
129const char* process_png_chunks(uint8_t* p, size_t n) {
130 while (n > 0) {
131 // Process the 8 byte chunk header.
132 if (n < 8) {
133 return "invalid PNG chunk";
134 }
135 uint32_t chunk_len = load_u32be(p + 0);
136 uint32_t chunk_type = load_u32be(p + 4);
137 p += 8;
138 n -= 8;
139
140 // Process the chunk payload.
141 if (n < chunk_len) {
142 return "short PNG chunk data";
143 }
144 switch (chunk_type) {
145 case 0x49484452: // "IHDR"
146 if (chunk_len != 13) {
147 return "invalid PNG IDAT chunk";
148 }
149 width = load_u32be(p + 0);
150 height = load_u32be(p + 4);
151 if ((width == 0) || (height == 0)) {
152 return "image dimensions are too small";
153 }
154 if ((width > MAX_DIMENSION) || (height > MAX_DIMENSION)) {
155 return "image dimensions are too large";
156 }
157 if (p[8] != 8) {
158 return "unsupported PNG bit depth";
159 }
160 if (bytes_per_pixel != 0) {
161 return "duplicate PNG IHDR chunk";
162 }
163 // Process the color type, as per the PNG spec table 11.1.
164 switch (p[9]) {
165 case 0:
166 bytes_per_pixel = 1;
167 break;
168 case 2:
169 bytes_per_pixel = 3;
170 break;
171 case 3:
172 bytes_per_pixel = 1;
173 break;
174 case 4:
175 bytes_per_pixel = 2;
176 break;
177 case 6:
178 bytes_per_pixel = 4;
179 break;
180 default:
181 return "unsupported PNG color type";
182 }
183 if (p[12] != 0) {
184 return "unsupported PNG interlacing";
185 }
186 break;
187
188 case 0x49444154: // "IDAT"
189 if (num_idat_chunks == MAX_IDAT_CHUNKS - 1) {
190 return "too many IDAT chunks";
191 }
192 memcpy(idat_buffer + idat_splits[num_idat_chunks], p, chunk_len);
193 idat_splits[num_idat_chunks + 1] =
194 idat_splits[num_idat_chunks] + chunk_len;
195 num_idat_chunks++;
196 break;
197 }
198 p += chunk_len;
199 n -= chunk_len;
200
201 // Process (and ignore) the 4 byte chunk footer (a checksum).
202 if (n < 4) {
203 return "invalid PNG chunk";
204 }
205 p += 4;
206 n -= 4;
207 }
208 return NULL;
209}
210
211const char* decode_once(bool frag_dst, bool frag_idat) {
212 wuffs_zlib__decoder dec;
213 wuffs_zlib__decoder__initialize(&dec, WUFFS_VERSION, 0);
214
215 wuffs_base__io_buffer dst = {.ptr = dst_buffer, .len = bytes_per_frame};
216 wuffs_base__io_buffer idat = {.ptr = idat_buffer,
217 .len = SRC_BUFFER_SIZE,
218 .wi = idat_splits[num_idat_chunks],
219 .closed = true};
220 wuffs_base__io_writer dst_writer = {.buf = &dst};
221 wuffs_base__io_reader idat_reader = {.buf = &idat};
222
223 uint32_t i = 0; // Number of dst fragments processed, if frag_dst.
224 if (frag_dst) {
225 dst.len = bytes_per_row;
226 }
227
228 uint32_t j = 0; // Number of IDAT fragments processed, if frag_idat.
229 if (frag_idat) {
230 idat.wi = idat_splits[1];
231 idat.closed = (num_idat_chunks == 1);
232 }
233
234 while (true) {
235 wuffs_zlib__status s =
236 wuffs_zlib__decoder__decode(&dec, dst_writer, idat_reader);
237
238 if (s == WUFFS_ZLIB__STATUS_OK) {
239 break;
240 }
241 if ((s == WUFFS_ZLIB__SUSPENSION_SHORT_WRITE) && frag_dst &&
242 (i < height - 1)) {
243 i++;
244 dst.len = bytes_per_row * (i + 1);
245 continue;
246 }
247 if ((s == WUFFS_ZLIB__SUSPENSION_SHORT_READ) && frag_idat &&
248 (j < num_idat_chunks - 1)) {
249 j++;
250 idat.wi = idat_splits[j + 1];
251 idat.closed = (num_idat_chunks == j + 1);
252 continue;
253 }
254 return wuffs_zlib__status__string(s);
255 }
256
257 if (dst.wi != bytes_per_frame) {
258 return "unexpected number of bytes decoded";
259 }
260 return NULL;
261}
262
263const char* decode(bool frag_dst, bool frag_idat) {
264 int reps;
265 if (bytes_per_frame < 100000) {
266 reps = 1000;
267 } else if (bytes_per_frame < 1000000) {
268 reps = 100;
269 } else if (bytes_per_frame < 10000000) {
270 reps = 10;
271 } else {
272 reps = 1;
273 }
274
275 struct timeval bench_start_tv;
276 gettimeofday(&bench_start_tv, NULL);
277
278 int i;
279 for (i = 0; i < reps; i++) {
280 const char* msg = decode_once(frag_dst, frag_idat);
281 if (msg) {
282 return msg;
283 }
284 }
285
286 struct timeval bench_finish_tv;
287 gettimeofday(&bench_finish_tv, NULL);
288 int64_t micros =
289 (int64_t)(bench_finish_tv.tv_sec - bench_start_tv.tv_sec) * 1000000 +
290 (int64_t)(bench_finish_tv.tv_usec - bench_start_tv.tv_usec);
291 uint64_t nanos = 1;
292 if (micros > 0) {
293 nanos = (uint64_t)(micros)*1000;
294 }
295
296 printf("Benchmark%sDst%sIDAT/%s\t%8d\t%8" PRIu64 " ns/op\n",
297 frag_dst ? "Frag" : "Full", //
298 frag_idat ? "Frag" : "Full", //
299 cc, reps, nanos / reps);
300
301 return NULL;
302}
303
304int fail(const char* msg) {
305 const int stderr_fd = 2;
306 write(stderr_fd, msg, strnlen(msg, 4095));
307 write(stderr_fd, "\n", 1);
308 return 1;
309}
310
311int main(int argc, char** argv) {
312 const char* msg = read_stdin();
313 if (msg) {
314 return fail(msg);
315 }
316 if ((src_len < 8) || strncmp(src_buffer, "\x89PNG\x0D\x0A\x1A\x0A", 8)) {
317 return fail("invalid PNG");
318 }
319 msg = process_png_chunks(src_buffer + 8, src_len - 8);
320 if (msg) {
321 return fail(msg);
322 }
323 if (bytes_per_pixel == 0) {
324 return fail("missing PNG IHDR chunk");
325 }
326 if (num_idat_chunks == 0) {
327 return fail("missing PNG IDAT chunk");
328 }
329 // The +1 here is for the per-row filter byte.
330 bytes_per_row = (uint64_t)width * bytes_per_pixel + 1;
331 bytes_per_frame = (uint64_t)height * bytes_per_row;
332 if (bytes_per_frame > DST_BUFFER_SIZE) {
333 return fail("decompressed data is too large");
334 }
335
336 printf("# %s version %s\n#\n", cc, cc_version);
337 printf(
338 "# The output format, including the \"Benchmark\" prefixes, is "
339 "compatible with the\n"
340 "# https://godoc.org/golang.org/x/perf/cmd/benchstat tool. To install "
341 "it, first\n"
342 "# install Go, then run \"go get golang.org/x/perf/cmd/benchstat\".\n");
343
344 int i;
345 for (i = 0; i < 5; i++) {
346 msg = decode(true, true);
347 if (msg) {
348 return fail(msg);
349 }
350 msg = decode(true, false);
351 if (msg) {
352 return fail(msg);
353 }
354 msg = decode(false, true);
355 if (msg) {
356 return fail(msg);
357 }
358 msg = decode(false, false);
359 if (msg) {
360 return fail(msg);
361 }
362 }
363
364 return 0;
365}