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