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