]> git.sesse.net Git - ffmpeg/blob - tests/checkasm/checkasm.c
Merge commit 'e02de9df4b218bd6e1e927b67fd4075741545688'
[ffmpeg] / tests / checkasm / checkasm.c
1 /*
2  * Assembly testing and benchmarking tool
3  * Copyright (c) 2015 Henrik Gramner
4  * Copyright (c) 2008 Loren Merritt
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with FFmpeg; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include "checkasm.h"
28 #include "libavutil/common.h"
29 #include "libavutil/cpu.h"
30 #include "libavutil/random_seed.h"
31
32 #if HAVE_IO_H
33 #include <io.h>
34 #endif
35
36 #if HAVE_SETCONSOLETEXTATTRIBUTE
37 #include <windows.h>
38 #define COLOR_RED    FOREGROUND_RED
39 #define COLOR_GREEN  FOREGROUND_GREEN
40 #define COLOR_YELLOW (FOREGROUND_RED|FOREGROUND_GREEN)
41 #else
42 #define COLOR_RED    1
43 #define COLOR_GREEN  2
44 #define COLOR_YELLOW 3
45 #endif
46
47 #if HAVE_UNISTD_H
48 #include <unistd.h>
49 #endif
50
51 #if !HAVE_ISATTY
52 #define isatty(fd) 1
53 #endif
54
55 /* List of tests to invoke */
56 static const struct {
57     const char *name;
58     void (*func)(void);
59 } tests[] = {
60 #if CONFIG_AVCODEC
61     #if CONFIG_ALAC_DECODER
62         { "alacdsp", checkasm_check_alacdsp },
63     #endif
64     #if CONFIG_BSWAPDSP
65         { "bswapdsp", checkasm_check_bswapdsp },
66     #endif
67     #if CONFIG_FLACDSP
68         { "flacdsp", checkasm_check_flacdsp },
69     #endif
70     #if CONFIG_H264PRED
71         { "h264pred", checkasm_check_h264pred },
72     #endif
73     #if CONFIG_H264QPEL
74         { "h264qpel", checkasm_check_h264qpel },
75     #endif
76     #if CONFIG_JPEG2000_DECODER
77         { "jpeg2000dsp", checkasm_check_jpeg2000dsp },
78     #endif
79     #if CONFIG_PIXBLOCKDSP
80         { "pixblockdsp", checkasm_check_pixblockdsp },
81     #endif
82     #if CONFIG_V210_ENCODER
83         { "v210enc", checkasm_check_v210enc },
84     #endif
85     #if CONFIG_VP9_DECODER
86         { "vp9dsp", checkasm_check_vp9dsp },
87     #endif
88 #endif
89     { NULL }
90 };
91
92 /* List of cpu flags to check */
93 static const struct {
94     const char *name;
95     const char *suffix;
96     int flag;
97 } cpus[] = {
98 #if   ARCH_AARCH64
99     { "ARMV8",    "armv8",    AV_CPU_FLAG_ARMV8 },
100     { "NEON",     "neon",     AV_CPU_FLAG_NEON },
101 #elif ARCH_ARM
102     { "ARMV5TE",  "armv5te",  AV_CPU_FLAG_ARMV5TE },
103     { "ARMV6",    "armv6",    AV_CPU_FLAG_ARMV6 },
104     { "ARMV6T2",  "armv6t2",  AV_CPU_FLAG_ARMV6T2 },
105     { "VFP",      "vfp",      AV_CPU_FLAG_VFP },
106     { "VFPV3",    "vfp3",     AV_CPU_FLAG_VFPV3 },
107     { "NEON",     "neon",     AV_CPU_FLAG_NEON },
108 #elif ARCH_PPC
109     { "ALTIVEC",  "altivec",  AV_CPU_FLAG_ALTIVEC },
110     { "VSX",      "vsx",      AV_CPU_FLAG_VSX },
111     { "POWER8",   "power8",   AV_CPU_FLAG_POWER8 },
112 #elif ARCH_X86
113     { "MMX",      "mmx",      AV_CPU_FLAG_MMX|AV_CPU_FLAG_CMOV },
114     { "MMXEXT",   "mmxext",   AV_CPU_FLAG_MMXEXT },
115     { "3DNOW",    "3dnow",    AV_CPU_FLAG_3DNOW },
116     { "3DNOWEXT", "3dnowext", AV_CPU_FLAG_3DNOWEXT },
117     { "SSE",      "sse",      AV_CPU_FLAG_SSE },
118     { "SSE2",     "sse2",     AV_CPU_FLAG_SSE2|AV_CPU_FLAG_SSE2SLOW },
119     { "SSE3",     "sse3",     AV_CPU_FLAG_SSE3|AV_CPU_FLAG_SSE3SLOW },
120     { "SSSE3",    "ssse3",    AV_CPU_FLAG_SSSE3|AV_CPU_FLAG_ATOM },
121     { "SSE4.1",   "sse4",     AV_CPU_FLAG_SSE4 },
122     { "SSE4.2",   "sse42",    AV_CPU_FLAG_SSE42 },
123     { "AES-NI",   "aesni",    AV_CPU_FLAG_AESNI },
124     { "AVX",      "avx",      AV_CPU_FLAG_AVX },
125     { "XOP",      "xop",      AV_CPU_FLAG_XOP },
126     { "FMA3",     "fma3",     AV_CPU_FLAG_FMA3 },
127     { "FMA4",     "fma4",     AV_CPU_FLAG_FMA4 },
128     { "AVX2",     "avx2",     AV_CPU_FLAG_AVX2 },
129 #endif
130     { NULL }
131 };
132
133 typedef struct CheckasmFuncVersion {
134     struct CheckasmFuncVersion *next;
135     void *func;
136     int ok;
137     int cpu;
138     int iterations;
139     uint64_t cycles;
140 } CheckasmFuncVersion;
141
142 /* Binary search tree node */
143 typedef struct CheckasmFunc {
144     struct CheckasmFunc *child[2];
145     CheckasmFuncVersion versions;
146     uint8_t color; /* 0 = red, 1 = black */
147     char name[1];
148 } CheckasmFunc;
149
150 /* Internal state */
151 static struct {
152     CheckasmFunc *funcs;
153     CheckasmFunc *current_func;
154     CheckasmFuncVersion *current_func_ver;
155     const char *current_test_name;
156     const char *bench_pattern;
157     int bench_pattern_len;
158     int num_checked;
159     int num_failed;
160     int nop_time;
161     int cpu_flag;
162     const char *cpu_flag_name;
163 } state;
164
165 /* PRNG state */
166 AVLFG checkasm_lfg;
167
168 /* Print colored text to stderr if the terminal supports it */
169 static void color_printf(int color, const char *fmt, ...)
170 {
171     static int use_color = -1;
172     va_list arg;
173
174 #if HAVE_SETCONSOLETEXTATTRIBUTE
175     static HANDLE con;
176     static WORD org_attributes;
177
178     if (use_color < 0) {
179         CONSOLE_SCREEN_BUFFER_INFO con_info;
180         con = GetStdHandle(STD_ERROR_HANDLE);
181         if (con && con != INVALID_HANDLE_VALUE && GetConsoleScreenBufferInfo(con, &con_info)) {
182             org_attributes = con_info.wAttributes;
183             use_color = 1;
184         } else
185             use_color = 0;
186     }
187     if (use_color)
188         SetConsoleTextAttribute(con, (org_attributes & 0xfff0) | (color & 0x0f));
189 #else
190     if (use_color < 0) {
191         const char *term = getenv("TERM");
192         use_color = term && strcmp(term, "dumb") && isatty(2);
193     }
194     if (use_color)
195         fprintf(stderr, "\x1b[%d;3%dm", (color & 0x08) >> 3, color & 0x07);
196 #endif
197
198     va_start(arg, fmt);
199     vfprintf(stderr, fmt, arg);
200     va_end(arg);
201
202     if (use_color) {
203 #if HAVE_SETCONSOLETEXTATTRIBUTE
204         SetConsoleTextAttribute(con, org_attributes);
205 #else
206         fprintf(stderr, "\x1b[0m");
207 #endif
208     }
209 }
210
211 /* Deallocate a tree */
212 static void destroy_func_tree(CheckasmFunc *f)
213 {
214     if (f) {
215         CheckasmFuncVersion *v = f->versions.next;
216         while (v) {
217             CheckasmFuncVersion *next = v->next;
218             free(v);
219             v = next;
220         }
221
222         destroy_func_tree(f->child[0]);
223         destroy_func_tree(f->child[1]);
224         free(f);
225     }
226 }
227
228 /* Allocate a zero-initialized block, clean up and exit on failure */
229 static void *checkasm_malloc(size_t size)
230 {
231     void *ptr = calloc(1, size);
232     if (!ptr) {
233         fprintf(stderr, "checkasm: malloc failed\n");
234         destroy_func_tree(state.funcs);
235         exit(1);
236     }
237     return ptr;
238 }
239
240 /* Get the suffix of the specified cpu flag */
241 static const char *cpu_suffix(int cpu)
242 {
243     int i = FF_ARRAY_ELEMS(cpus);
244
245     while (--i >= 0)
246         if (cpu & cpus[i].flag)
247             return cpus[i].suffix;
248
249     return "c";
250 }
251
252 #ifdef AV_READ_TIME
253 static int cmp_nop(const void *a, const void *b)
254 {
255     return *(const uint16_t*)a - *(const uint16_t*)b;
256 }
257
258 /* Measure the overhead of the timing code (in decicycles) */
259 static int measure_nop_time(void)
260 {
261     uint16_t nops[10000];
262     int i, nop_sum = 0;
263
264     for (i = 0; i < 10000; i++) {
265         uint64_t t = AV_READ_TIME();
266         nops[i] = AV_READ_TIME() - t;
267     }
268
269     qsort(nops, 10000, sizeof(uint16_t), cmp_nop);
270     for (i = 2500; i < 7500; i++)
271         nop_sum += nops[i];
272
273     return nop_sum / 500;
274 }
275
276 /* Print benchmark results */
277 static void print_benchs(CheckasmFunc *f)
278 {
279     if (f) {
280         print_benchs(f->child[0]);
281
282         /* Only print functions with at least one assembly version */
283         if (f->versions.cpu || f->versions.next) {
284             CheckasmFuncVersion *v = &f->versions;
285             do {
286                 if (v->iterations) {
287                     int decicycles = (10*v->cycles/v->iterations - state.nop_time) / 4;
288                     printf("%s_%s: %d.%d\n", f->name, cpu_suffix(v->cpu), decicycles/10, decicycles%10);
289                 }
290             } while ((v = v->next));
291         }
292
293         print_benchs(f->child[1]);
294     }
295 }
296 #endif
297
298 /* ASCIIbetical sort except preserving natural order for numbers */
299 static int cmp_func_names(const char *a, const char *b)
300 {
301     const char *start = a;
302     int ascii_diff, digit_diff;
303
304     for (; !(ascii_diff = *(const unsigned char*)a - *(const unsigned char*)b) && *a; a++, b++);
305     for (; av_isdigit(*a) && av_isdigit(*b); a++, b++);
306
307     if (a > start && av_isdigit(a[-1]) && (digit_diff = av_isdigit(*a) - av_isdigit(*b)))
308         return digit_diff;
309
310     return ascii_diff;
311 }
312
313 /* Perform a tree rotation in the specified direction and return the new root */
314 static CheckasmFunc *rotate_tree(CheckasmFunc *f, int dir)
315 {
316     CheckasmFunc *r = f->child[dir^1];
317     f->child[dir^1] = r->child[dir];
318     r->child[dir] = f;
319     r->color = f->color;
320     f->color = 0;
321     return r;
322 }
323
324 #define is_red(f) ((f) && !(f)->color)
325
326 /* Balance a left-leaning red-black tree at the specified node */
327 static void balance_tree(CheckasmFunc **root)
328 {
329     CheckasmFunc *f = *root;
330
331     if (is_red(f->child[0]) && is_red(f->child[1])) {
332         f->color ^= 1;
333         f->child[0]->color = f->child[1]->color = 1;
334     }
335
336     if (!is_red(f->child[0]) && is_red(f->child[1]))
337         *root = rotate_tree(f, 0); /* Rotate left */
338     else if (is_red(f->child[0]) && is_red(f->child[0]->child[0]))
339         *root = rotate_tree(f, 1); /* Rotate right */
340 }
341
342 /* Get a node with the specified name, creating it if it doesn't exist */
343 static CheckasmFunc *get_func(CheckasmFunc **root, const char *name)
344 {
345     CheckasmFunc *f = *root;
346
347     if (f) {
348         /* Search the tree for a matching node */
349         int cmp = cmp_func_names(name, f->name);
350         if (cmp) {
351             f = get_func(&f->child[cmp > 0], name);
352
353             /* Rebalance the tree on the way up if a new node was inserted */
354             if (!f->versions.func)
355                 balance_tree(root);
356         }
357     } else {
358         /* Allocate and insert a new node into the tree */
359         int name_length = strlen(name);
360         f = *root = checkasm_malloc(sizeof(CheckasmFunc) + name_length);
361         memcpy(f->name, name, name_length + 1);
362     }
363
364     return f;
365 }
366
367 /* Perform tests and benchmarks for the specified cpu flag if supported by the host */
368 static void check_cpu_flag(const char *name, int flag)
369 {
370     int old_cpu_flag = state.cpu_flag;
371
372     flag |= old_cpu_flag;
373     av_force_cpu_flags(-1);
374     state.cpu_flag = flag & av_get_cpu_flags();
375     av_force_cpu_flags(state.cpu_flag);
376
377     if (!flag || state.cpu_flag != old_cpu_flag) {
378         int i;
379
380         state.cpu_flag_name = name;
381         for (i = 0; tests[i].func; i++) {
382             state.current_test_name = tests[i].name;
383             tests[i].func();
384         }
385     }
386 }
387
388 /* Print the name of the current CPU flag, but only do it once */
389 static void print_cpu_name(void)
390 {
391     if (state.cpu_flag_name) {
392         color_printf(COLOR_YELLOW, "%s:\n", state.cpu_flag_name);
393         state.cpu_flag_name = NULL;
394     }
395 }
396
397 int main(int argc, char *argv[])
398 {
399     int i, seed, ret = 0;
400
401     if (!tests[0].func || !cpus[0].flag) {
402         fprintf(stderr, "checkasm: no tests to perform\n");
403         return 0;
404     }
405
406     if (argc > 1 && !strncmp(argv[1], "--bench", 7)) {
407 #ifndef AV_READ_TIME
408         fprintf(stderr, "checkasm: --bench is not supported on your system\n");
409         return 1;
410 #endif
411         if (argv[1][7] == '=') {
412             state.bench_pattern = argv[1] + 8;
413             state.bench_pattern_len = strlen(state.bench_pattern);
414         } else
415             state.bench_pattern = "";
416
417         argc--;
418         argv++;
419     }
420
421     seed = (argc > 1) ? atoi(argv[1]) : av_get_random_seed();
422     fprintf(stderr, "checkasm: using random seed %u\n", seed);
423     av_lfg_init(&checkasm_lfg, seed);
424
425     check_cpu_flag(NULL, 0);
426     for (i = 0; cpus[i].flag; i++)
427         check_cpu_flag(cpus[i].name, cpus[i].flag);
428
429     if (state.num_failed) {
430         fprintf(stderr, "checkasm: %d of %d tests have failed\n", state.num_failed, state.num_checked);
431         ret = 1;
432     } else {
433         fprintf(stderr, "checkasm: all %d tests passed\n", state.num_checked);
434 #ifdef AV_READ_TIME
435         if (state.bench_pattern) {
436             state.nop_time = measure_nop_time();
437             printf("nop: %d.%d\n", state.nop_time/10, state.nop_time%10);
438             print_benchs(state.funcs);
439         }
440 #endif
441     }
442
443     destroy_func_tree(state.funcs);
444     return ret;
445 }
446
447 /* Decide whether or not the specified function needs to be tested and
448  * allocate/initialize data structures if needed. Returns a pointer to a
449  * reference function if the function should be tested, otherwise NULL */
450 void *checkasm_check_func(void *func, const char *name, ...)
451 {
452     char name_buf[256];
453     void *ref = func;
454     CheckasmFuncVersion *v;
455     int name_length;
456     va_list arg;
457
458     va_start(arg, name);
459     name_length = vsnprintf(name_buf, sizeof(name_buf), name, arg);
460     va_end(arg);
461
462     if (!func || name_length <= 0 || name_length >= sizeof(name_buf))
463         return NULL;
464
465     state.current_func = get_func(&state.funcs, name_buf);
466     state.funcs->color = 1;
467     v = &state.current_func->versions;
468
469     if (v->func) {
470         CheckasmFuncVersion *prev;
471         do {
472             /* Only test functions that haven't already been tested */
473             if (v->func == func)
474                 return NULL;
475
476             if (v->ok)
477                 ref = v->func;
478
479             prev = v;
480         } while ((v = v->next));
481
482         v = prev->next = checkasm_malloc(sizeof(CheckasmFuncVersion));
483     }
484
485     v->func = func;
486     v->ok = 1;
487     v->cpu = state.cpu_flag;
488     state.current_func_ver = v;
489
490     if (state.cpu_flag)
491         state.num_checked++;
492
493     return ref;
494 }
495
496 /* Decide whether or not the current function needs to be benchmarked */
497 int checkasm_bench_func(void)
498 {
499     return !state.num_failed && state.bench_pattern &&
500            !strncmp(state.current_func->name, state.bench_pattern, state.bench_pattern_len);
501 }
502
503 /* Indicate that the current test has failed */
504 void checkasm_fail_func(const char *msg, ...)
505 {
506     if (state.current_func_ver->cpu && state.current_func_ver->ok) {
507         va_list arg;
508
509         print_cpu_name();
510         fprintf(stderr, "   %s_%s (", state.current_func->name, cpu_suffix(state.current_func_ver->cpu));
511         va_start(arg, msg);
512         vfprintf(stderr, msg, arg);
513         va_end(arg);
514         fprintf(stderr, ")\n");
515
516         state.current_func_ver->ok = 0;
517         state.num_failed++;
518     }
519 }
520
521 /* Update benchmark results of the current function */
522 void checkasm_update_bench(int iterations, uint64_t cycles)
523 {
524     state.current_func_ver->iterations += iterations;
525     state.current_func_ver->cycles += cycles;
526 }
527
528 /* Print the outcome of all tests performed since the last time this function was called */
529 void checkasm_report(const char *name, ...)
530 {
531     static int prev_checked, prev_failed, max_length;
532
533     if (state.num_checked > prev_checked) {
534         int pad_length = max_length + 4;
535         va_list arg;
536
537         print_cpu_name();
538         pad_length -= fprintf(stderr, " - %s.", state.current_test_name);
539         va_start(arg, name);
540         pad_length -= vfprintf(stderr, name, arg);
541         va_end(arg);
542         fprintf(stderr, "%*c", FFMAX(pad_length, 0) + 2, '[');
543
544         if (state.num_failed == prev_failed)
545             color_printf(COLOR_GREEN, "OK");
546         else
547             color_printf(COLOR_RED, "FAILED");
548         fprintf(stderr, "]\n");
549
550         prev_checked = state.num_checked;
551         prev_failed  = state.num_failed;
552     } else if (!state.cpu_flag) {
553         /* Calculate the amount of padding required to make the output vertically aligned */
554         int length = strlen(state.current_test_name);
555         va_list arg;
556
557         va_start(arg, name);
558         length += vsnprintf(NULL, 0, name, arg);
559         va_end(arg);
560
561         if (length > max_length)
562             max_length = length;
563     }
564 }