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