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 "config.h"
24 
25 #if CONFIG_LINUX_PERF
26 # ifndef _GNU_SOURCE
27 #  define _GNU_SOURCE // for syscall (performance monitoring API)
28 # endif
29 #endif
30 
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include "checkasm.h"
36 #include "libavutil/common.h"
37 #include "libavutil/cpu.h"
38 #include "libavutil/intfloat.h"
39 #include "libavutil/random_seed.h"
40 
41 #if HAVE_IO_H
42 #include <io.h>
43 #endif
44 
45 #if HAVE_SETCONSOLETEXTATTRIBUTE && HAVE_GETSTDHANDLE
46 #include <windows.h>
47 #define COLOR_RED    FOREGROUND_RED
48 #define COLOR_GREEN  FOREGROUND_GREEN
49 #define COLOR_YELLOW (FOREGROUND_RED|FOREGROUND_GREEN)
50 #else
51 #define COLOR_RED    1
52 #define COLOR_GREEN  2
53 #define COLOR_YELLOW 3
54 #endif
55 
56 #if HAVE_UNISTD_H
57 #include <unistd.h>
58 #endif
59 
60 #if !HAVE_ISATTY
61 #define isatty(fd) 1
62 #endif
63 
64 #if ARCH_ARM && HAVE_ARMV5TE_EXTERNAL
65 #include "libavutil/arm/cpu.h"
66 
67 void (*checkasm_checked_call)(void *func, int dummy, ...) = checkasm_checked_call_novfp;
68 #endif
69 
70 /* List of tests to invoke */
71 static const struct {
72     const char *name;
73     void (*func)(void);
74 } tests[] = {
75 #if CONFIG_AVCODEC
76     #if CONFIG_AAC_DECODER
77         { "aacpsdsp", checkasm_check_aacpsdsp },
78         { "sbrdsp",   checkasm_check_sbrdsp },
79     #endif
80     #if CONFIG_ALAC_DECODER
81         { "alacdsp", checkasm_check_alacdsp },
82     #endif
83     #if CONFIG_AUDIODSP
84         { "audiodsp", checkasm_check_audiodsp },
85     #endif
86     #if CONFIG_BLOCKDSP
87         { "blockdsp", checkasm_check_blockdsp },
88     #endif
89     #if CONFIG_BSWAPDSP
90         { "bswapdsp", checkasm_check_bswapdsp },
91     #endif
92     #if CONFIG_DCA_DECODER
93         { "synth_filter", checkasm_check_synth_filter },
94     #endif
95     #if CONFIG_EXR_DECODER
96         { "exrdsp", checkasm_check_exrdsp },
97     #endif
98     #if CONFIG_FLACDSP
99         { "flacdsp", checkasm_check_flacdsp },
100     #endif
101     #if CONFIG_FMTCONVERT
102         { "fmtconvert", checkasm_check_fmtconvert },
103     #endif
104     #if CONFIG_G722DSP
105         { "g722dsp", checkasm_check_g722dsp },
106     #endif
107     #if CONFIG_H264DSP
108         { "h264dsp", checkasm_check_h264dsp },
109     #endif
110     #if CONFIG_H264PRED
111         { "h264pred", checkasm_check_h264pred },
112     #endif
113     #if CONFIG_H264QPEL
114         { "h264qpel", checkasm_check_h264qpel },
115     #endif
116     #if CONFIG_HEVC_DECODER
117         { "hevc_add_res", checkasm_check_hevc_add_res },
118         { "hevc_idct", checkasm_check_hevc_idct },
119         { "hevc_qpel", checkasm_check_hevc_qpel },
120         { "hevc_qpel_uni", checkasm_check_hevc_qpel_uni },
121         { "hevc_qpel_uni_w", checkasm_check_hevc_qpel_uni_w },
122         { "hevc_qpel_bi", checkasm_check_hevc_qpel_bi },
123         { "hevc_qpel_bi_w", checkasm_check_hevc_qpel_bi_w },
124         { "hevc_epel", checkasm_check_hevc_epel },
125         { "hevc_epel_uni", checkasm_check_hevc_epel_uni },
126         { "hevc_epel_uni_w", checkasm_check_hevc_epel_uni_w },
127         { "hevc_epel_bi", checkasm_check_hevc_epel_bi },
128         { "hevc_epel_bi_w", checkasm_check_hevc_epel_bi_w },
129         { "hevc_sao", checkasm_check_hevc_sao },
130     #endif
131     #if CONFIG_HUFFYUV_DECODER
132         { "huffyuvdsp", checkasm_check_huffyuvdsp },
133     #endif
134     #if CONFIG_JPEG2000_DECODER
135         { "jpeg2000dsp", checkasm_check_jpeg2000dsp },
136     #endif
137     #if CONFIG_HUFFYUVDSP
138         { "llviddsp", checkasm_check_llviddsp },
139     #endif
140     #if CONFIG_LLVIDENCDSP
141         { "llviddspenc", checkasm_check_llviddspenc },
142     #endif
143     #if CONFIG_OPUS_DECODER
144         { "opusdsp", checkasm_check_opusdsp },
145     #endif
146     #if CONFIG_PIXBLOCKDSP
147         { "pixblockdsp", checkasm_check_pixblockdsp },
148     #endif
149     #if CONFIG_UTVIDEO_DECODER
150         { "utvideodsp", checkasm_check_utvideodsp },
151     #endif
152     #if CONFIG_V210_DECODER
153         { "v210dec", checkasm_check_v210dec },
154     #endif
155     #if CONFIG_V210_ENCODER
156         { "v210enc", checkasm_check_v210enc },
157     #endif
158     #if CONFIG_VP8DSP
159         { "vp8dsp", checkasm_check_vp8dsp },
160     #endif
161     #if CONFIG_VP9_DECODER
162         { "vp9dsp", checkasm_check_vp9dsp },
163     #endif
164     #if CONFIG_VIDEODSP
165         { "videodsp", checkasm_check_videodsp },
166     #endif
167 #endif
168 #if CONFIG_AVFILTER
169     #if CONFIG_AFIR_FILTER
170         { "af_afir", checkasm_check_afir },
171     #endif
172     #if CONFIG_BLEND_FILTER
173         { "vf_blend", checkasm_check_blend },
174     #endif
175     #if CONFIG_COLORSPACE_FILTER
176         { "vf_colorspace", checkasm_check_colorspace },
177     #endif
178     #if CONFIG_EQ_FILTER
179         { "vf_eq", checkasm_check_vf_eq },
180     #endif
181     #if CONFIG_GBLUR_FILTER
182         { "vf_gblur", checkasm_check_vf_gblur },
183     #endif
184     #if CONFIG_HFLIP_FILTER
185         { "vf_hflip", checkasm_check_vf_hflip },
186     #endif
187     #if CONFIG_NLMEANS_FILTER
188         { "vf_nlmeans", checkasm_check_nlmeans },
189     #endif
190     #if CONFIG_THRESHOLD_FILTER
191         { "vf_threshold", checkasm_check_vf_threshold },
192     #endif
193 #endif
194 #if CONFIG_SWSCALE
195     { "sw_rgb", checkasm_check_sw_rgb },
196     { "sw_scale", checkasm_check_sw_scale },
197 #endif
198 #if CONFIG_AVUTIL
199         { "fixed_dsp", checkasm_check_fixed_dsp },
200         { "float_dsp", checkasm_check_float_dsp },
201 #endif
202     { NULL }
203 };
204 
205 /* List of cpu flags to check */
206 static const struct {
207     const char *name;
208     const char *suffix;
209     int flag;
210 } cpus[] = {
211 #if   ARCH_AARCH64
212     { "ARMV8",    "armv8",    AV_CPU_FLAG_ARMV8 },
213     { "NEON",     "neon",     AV_CPU_FLAG_NEON },
214 #elif ARCH_ARM
215     { "ARMV5TE",  "armv5te",  AV_CPU_FLAG_ARMV5TE },
216     { "ARMV6",    "armv6",    AV_CPU_FLAG_ARMV6 },
217     { "ARMV6T2",  "armv6t2",  AV_CPU_FLAG_ARMV6T2 },
218     { "VFP",      "vfp",      AV_CPU_FLAG_VFP },
219     { "VFP_VM",   "vfp_vm",   AV_CPU_FLAG_VFP_VM },
220     { "VFPV3",    "vfp3",     AV_CPU_FLAG_VFPV3 },
221     { "NEON",     "neon",     AV_CPU_FLAG_NEON },
222 #elif ARCH_PPC
223     { "ALTIVEC",  "altivec",  AV_CPU_FLAG_ALTIVEC },
224     { "VSX",      "vsx",      AV_CPU_FLAG_VSX },
225     { "POWER8",   "power8",   AV_CPU_FLAG_POWER8 },
226 #elif ARCH_MIPS
227     { "MMI",      "mmi",      AV_CPU_FLAG_MMI },
228     { "MSA",      "msa",      AV_CPU_FLAG_MSA },
229 #elif ARCH_X86
230     { "MMX",      "mmx",      AV_CPU_FLAG_MMX|AV_CPU_FLAG_CMOV },
231     { "MMXEXT",   "mmxext",   AV_CPU_FLAG_MMXEXT },
232     { "3DNOW",    "3dnow",    AV_CPU_FLAG_3DNOW },
233     { "3DNOWEXT", "3dnowext", AV_CPU_FLAG_3DNOWEXT },
234     { "SSE",      "sse",      AV_CPU_FLAG_SSE },
235     { "SSE2",     "sse2",     AV_CPU_FLAG_SSE2|AV_CPU_FLAG_SSE2SLOW },
236     { "SSE3",     "sse3",     AV_CPU_FLAG_SSE3|AV_CPU_FLAG_SSE3SLOW },
237     { "SSSE3",    "ssse3",    AV_CPU_FLAG_SSSE3|AV_CPU_FLAG_ATOM },
238     { "SSE4.1",   "sse4",     AV_CPU_FLAG_SSE4 },
239     { "SSE4.2",   "sse42",    AV_CPU_FLAG_SSE42 },
240     { "AES-NI",   "aesni",    AV_CPU_FLAG_AESNI },
241     { "AVX",      "avx",      AV_CPU_FLAG_AVX },
242     { "XOP",      "xop",      AV_CPU_FLAG_XOP },
243     { "FMA3",     "fma3",     AV_CPU_FLAG_FMA3 },
244     { "FMA4",     "fma4",     AV_CPU_FLAG_FMA4 },
245     { "AVX2",     "avx2",     AV_CPU_FLAG_AVX2 },
246     { "AVX-512",  "avx512",   AV_CPU_FLAG_AVX512 },
247 #endif
248     { NULL }
249 };
250 
251 typedef struct CheckasmFuncVersion {
252     struct CheckasmFuncVersion *next;
253     void *func;
254     int ok;
255     int cpu;
256     CheckasmPerf perf;
257 } CheckasmFuncVersion;
258 
259 /* Binary search tree node */
260 typedef struct CheckasmFunc {
261     struct CheckasmFunc *child[2];
262     CheckasmFuncVersion versions;
263     uint8_t color; /* 0 = red, 1 = black */
264     char name[1];
265 } CheckasmFunc;
266 
267 /* Internal state */
268 static struct {
269     CheckasmFunc *funcs;
270     CheckasmFunc *current_func;
271     CheckasmFuncVersion *current_func_ver;
272     const char *current_test_name;
273     const char *bench_pattern;
274     int bench_pattern_len;
275     int num_checked;
276     int num_failed;
277 
278     /* perf */
279     int nop_time;
280     int sysfd;
281 
282     int cpu_flag;
283     const char *cpu_flag_name;
284     const char *test_name;
285     int verbose;
286 } state;
287 
288 /* PRNG state */
289 AVLFG checkasm_lfg;
290 
291 /* float compare support code */
is_negative(union av_intfloat32 u)292 static int is_negative(union av_intfloat32 u)
293 {
294     return u.i >> 31;
295 }
296 
float_near_ulp(float a,float b,unsigned max_ulp)297 int float_near_ulp(float a, float b, unsigned max_ulp)
298 {
299     union av_intfloat32 x, y;
300 
301     x.f = a;
302     y.f = b;
303 
304     if (is_negative(x) != is_negative(y)) {
305         // handle -0.0 == +0.0
306         return a == b;
307     }
308 
309     if (llabs((int64_t)x.i - y.i) <= max_ulp)
310         return 1;
311 
312     return 0;
313 }
314 
float_near_ulp_array(const float * a,const float * b,unsigned max_ulp,unsigned len)315 int float_near_ulp_array(const float *a, const float *b, unsigned max_ulp,
316                          unsigned len)
317 {
318     unsigned i;
319 
320     for (i = 0; i < len; i++) {
321         if (!float_near_ulp(a[i], b[i], max_ulp))
322             return 0;
323     }
324     return 1;
325 }
326 
float_near_abs_eps(float a,float b,float eps)327 int float_near_abs_eps(float a, float b, float eps)
328 {
329     float abs_diff = fabsf(a - b);
330     if (abs_diff < eps)
331         return 1;
332 
333     fprintf(stderr, "test failed comparing %g with %g (abs diff=%g with EPS=%g)\n", a, b, abs_diff, eps);
334 
335     return 0;
336 }
337 
float_near_abs_eps_array(const float * a,const float * b,float eps,unsigned len)338 int float_near_abs_eps_array(const float *a, const float *b, float eps,
339                          unsigned len)
340 {
341     unsigned i;
342 
343     for (i = 0; i < len; i++) {
344         if (!float_near_abs_eps(a[i], b[i], eps))
345             return 0;
346     }
347     return 1;
348 }
349 
float_near_abs_eps_ulp(float a,float b,float eps,unsigned max_ulp)350 int float_near_abs_eps_ulp(float a, float b, float eps, unsigned max_ulp)
351 {
352     return float_near_ulp(a, b, max_ulp) || float_near_abs_eps(a, b, eps);
353 }
354 
float_near_abs_eps_array_ulp(const float * a,const float * b,float eps,unsigned max_ulp,unsigned len)355 int float_near_abs_eps_array_ulp(const float *a, const float *b, float eps,
356                          unsigned max_ulp, unsigned len)
357 {
358     unsigned i;
359 
360     for (i = 0; i < len; i++) {
361         if (!float_near_abs_eps_ulp(a[i], b[i], eps, max_ulp))
362             return 0;
363     }
364     return 1;
365 }
366 
double_near_abs_eps(double a,double b,double eps)367 int double_near_abs_eps(double a, double b, double eps)
368 {
369     double abs_diff = fabs(a - b);
370 
371     return abs_diff < eps;
372 }
373 
double_near_abs_eps_array(const double * a,const double * b,double eps,unsigned len)374 int double_near_abs_eps_array(const double *a, const double *b, double eps,
375                               unsigned len)
376 {
377     unsigned i;
378 
379     for (i = 0; i < len; i++) {
380         if (!double_near_abs_eps(a[i], b[i], eps))
381             return 0;
382     }
383     return 1;
384 }
385 
386 /* Print colored text to stderr if the terminal supports it */
color_printf(int color,const char * fmt,...)387 static void color_printf(int color, const char *fmt, ...)
388 {
389     static int use_color = -1;
390     va_list arg;
391 
392 #if HAVE_SETCONSOLETEXTATTRIBUTE && HAVE_GETSTDHANDLE
393     static HANDLE con;
394     static WORD org_attributes;
395 
396     if (use_color < 0) {
397         CONSOLE_SCREEN_BUFFER_INFO con_info;
398         con = GetStdHandle(STD_ERROR_HANDLE);
399         if (con && con != INVALID_HANDLE_VALUE && GetConsoleScreenBufferInfo(con, &con_info)) {
400             org_attributes = con_info.wAttributes;
401             use_color = 1;
402         } else
403             use_color = 0;
404     }
405     if (use_color)
406         SetConsoleTextAttribute(con, (org_attributes & 0xfff0) | (color & 0x0f));
407 #else
408     if (use_color < 0) {
409         const char *term = getenv("TERM");
410         use_color = term && strcmp(term, "dumb") && isatty(2);
411     }
412     if (use_color)
413         fprintf(stderr, "\x1b[%d;3%dm", (color & 0x08) >> 3, color & 0x07);
414 #endif
415 
416     va_start(arg, fmt);
417     vfprintf(stderr, fmt, arg);
418     va_end(arg);
419 
420     if (use_color) {
421 #if HAVE_SETCONSOLETEXTATTRIBUTE && HAVE_GETSTDHANDLE
422         SetConsoleTextAttribute(con, org_attributes);
423 #else
424         fprintf(stderr, "\x1b[0m");
425 #endif
426     }
427 }
428 
429 /* Deallocate a tree */
destroy_func_tree(CheckasmFunc * f)430 static void destroy_func_tree(CheckasmFunc *f)
431 {
432     if (f) {
433         CheckasmFuncVersion *v = f->versions.next;
434         while (v) {
435             CheckasmFuncVersion *next = v->next;
436             free(v);
437             v = next;
438         }
439 
440         destroy_func_tree(f->child[0]);
441         destroy_func_tree(f->child[1]);
442         free(f);
443     }
444 }
445 
446 /* Allocate a zero-initialized block, clean up and exit on failure */
checkasm_malloc(size_t size)447 static void *checkasm_malloc(size_t size)
448 {
449     void *ptr = calloc(1, size);
450     if (!ptr) {
451         fprintf(stderr, "checkasm: malloc failed\n");
452         destroy_func_tree(state.funcs);
453         exit(1);
454     }
455     return ptr;
456 }
457 
458 /* Get the suffix of the specified cpu flag */
cpu_suffix(int cpu)459 static const char *cpu_suffix(int cpu)
460 {
461     int i = FF_ARRAY_ELEMS(cpus);
462 
463     while (--i >= 0)
464         if (cpu & cpus[i].flag)
465             return cpus[i].suffix;
466 
467     return "c";
468 }
469 
cmp_nop(const void * a,const void * b)470 static int cmp_nop(const void *a, const void *b)
471 {
472     return *(const uint16_t*)a - *(const uint16_t*)b;
473 }
474 
475 /* Measure the overhead of the timing code (in decicycles) */
measure_nop_time(void)476 static int measure_nop_time(void)
477 {
478     uint16_t nops[10000];
479     int i, nop_sum = 0;
480     av_unused const int sysfd = state.sysfd;
481 
482     uint64_t t = 0;
483     for (i = 0; i < 10000; i++) {
484         PERF_START(t);
485         PERF_STOP(t);
486         nops[i] = t;
487     }
488 
489     qsort(nops, 10000, sizeof(uint16_t), cmp_nop);
490     for (i = 2500; i < 7500; i++)
491         nop_sum += nops[i];
492 
493     return nop_sum / 500;
494 }
495 
496 /* Print benchmark results */
print_benchs(CheckasmFunc * f)497 static void print_benchs(CheckasmFunc *f)
498 {
499     if (f) {
500         print_benchs(f->child[0]);
501 
502         /* Only print functions with at least one assembly version */
503         if (f->versions.cpu || f->versions.next) {
504             CheckasmFuncVersion *v = &f->versions;
505             do {
506                 CheckasmPerf *p = &v->perf;
507                 if (p->iterations) {
508                     int decicycles = (10*p->cycles/p->iterations - state.nop_time) / 4;
509                     printf("%s_%s: %d.%d\n", f->name, cpu_suffix(v->cpu), decicycles/10, decicycles%10);
510                 }
511             } while ((v = v->next));
512         }
513 
514         print_benchs(f->child[1]);
515     }
516 }
517 
518 /* ASCIIbetical sort except preserving natural order for numbers */
cmp_func_names(const char * a,const char * b)519 static int cmp_func_names(const char *a, const char *b)
520 {
521     const char *start = a;
522     int ascii_diff, digit_diff;
523 
524     for (; !(ascii_diff = *(const unsigned char*)a - *(const unsigned char*)b) && *a; a++, b++);
525     for (; av_isdigit(*a) && av_isdigit(*b); a++, b++);
526 
527     if (a > start && av_isdigit(a[-1]) && (digit_diff = av_isdigit(*a) - av_isdigit(*b)))
528         return digit_diff;
529 
530     return ascii_diff;
531 }
532 
533 /* Perform a tree rotation in the specified direction and return the new root */
rotate_tree(CheckasmFunc * f,int dir)534 static CheckasmFunc *rotate_tree(CheckasmFunc *f, int dir)
535 {
536     CheckasmFunc *r = f->child[dir^1];
537     f->child[dir^1] = r->child[dir];
538     r->child[dir] = f;
539     r->color = f->color;
540     f->color = 0;
541     return r;
542 }
543 
544 #define is_red(f) ((f) && !(f)->color)
545 
546 /* Balance a left-leaning red-black tree at the specified node */
balance_tree(CheckasmFunc ** root)547 static void balance_tree(CheckasmFunc **root)
548 {
549     CheckasmFunc *f = *root;
550 
551     if (is_red(f->child[0]) && is_red(f->child[1])) {
552         f->color ^= 1;
553         f->child[0]->color = f->child[1]->color = 1;
554     }
555 
556     if (!is_red(f->child[0]) && is_red(f->child[1]))
557         *root = rotate_tree(f, 0); /* Rotate left */
558     else if (is_red(f->child[0]) && is_red(f->child[0]->child[0]))
559         *root = rotate_tree(f, 1); /* Rotate right */
560 }
561 
562 /* Get a node with the specified name, creating it if it doesn't exist */
get_func(CheckasmFunc ** root,const char * name)563 static CheckasmFunc *get_func(CheckasmFunc **root, const char *name)
564 {
565     CheckasmFunc *f = *root;
566 
567     if (f) {
568         /* Search the tree for a matching node */
569         int cmp = cmp_func_names(name, f->name);
570         if (cmp) {
571             f = get_func(&f->child[cmp > 0], name);
572 
573             /* Rebalance the tree on the way up if a new node was inserted */
574             if (!f->versions.func)
575                 balance_tree(root);
576         }
577     } else {
578         /* Allocate and insert a new node into the tree */
579         int name_length = strlen(name);
580         f = *root = checkasm_malloc(sizeof(CheckasmFunc) + name_length);
581         memcpy(f->name, name, name_length + 1);
582     }
583 
584     return f;
585 }
586 
587 /* Perform tests and benchmarks for the specified cpu flag if supported by the host */
check_cpu_flag(const char * name,int flag)588 static void check_cpu_flag(const char *name, int flag)
589 {
590     int old_cpu_flag = state.cpu_flag;
591 
592     flag |= old_cpu_flag;
593     av_force_cpu_flags(-1);
594     state.cpu_flag = flag & av_get_cpu_flags();
595     av_force_cpu_flags(state.cpu_flag);
596 
597     if (!flag || state.cpu_flag != old_cpu_flag) {
598         int i;
599 
600         state.cpu_flag_name = name;
601         for (i = 0; tests[i].func; i++) {
602             if (state.test_name && strcmp(tests[i].name, state.test_name))
603                 continue;
604             state.current_test_name = tests[i].name;
605             tests[i].func();
606         }
607     }
608 }
609 
610 /* Print the name of the current CPU flag, but only do it once */
print_cpu_name(void)611 static void print_cpu_name(void)
612 {
613     if (state.cpu_flag_name) {
614         color_printf(COLOR_YELLOW, "%s:\n", state.cpu_flag_name);
615         state.cpu_flag_name = NULL;
616     }
617 }
618 
619 #if CONFIG_LINUX_PERF
bench_init_linux(void)620 static int bench_init_linux(void)
621 {
622     struct perf_event_attr attr = {
623         .type           = PERF_TYPE_HARDWARE,
624         .size           = sizeof(struct perf_event_attr),
625         .config         = PERF_COUNT_HW_CPU_CYCLES,
626         .disabled       = 1, // start counting only on demand
627         .exclude_kernel = 1,
628         .exclude_hv     = 1,
629     };
630 
631     printf("benchmarking with Linux Perf Monitoring API\n");
632 
633     state.sysfd = syscall(__NR_perf_event_open, &attr, 0, -1, -1, 0);
634     if (state.sysfd == -1) {
635         perror("syscall");
636         return -1;
637     }
638     return 0;
639 }
640 #endif
641 
642 #if !CONFIG_LINUX_PERF
bench_init_ffmpeg(void)643 static int bench_init_ffmpeg(void)
644 {
645 #ifdef AV_READ_TIME
646     printf("benchmarking with native FFmpeg timers\n");
647     return 0;
648 #else
649     fprintf(stderr, "checkasm: --bench is not supported on your system\n");
650     return -1;
651 #endif
652 }
653 #endif
654 
bench_init(void)655 static int bench_init(void)
656 {
657 #if CONFIG_LINUX_PERF
658     int ret = bench_init_linux();
659 #else
660     int ret = bench_init_ffmpeg();
661 #endif
662     if (ret < 0)
663         return ret;
664 
665     state.nop_time = measure_nop_time();
666     printf("nop: %d.%d\n", state.nop_time/10, state.nop_time%10);
667     return 0;
668 }
669 
bench_uninit(void)670 static void bench_uninit(void)
671 {
672 #if CONFIG_LINUX_PERF
673     if (state.sysfd > 0)
674         close(state.sysfd);
675 #endif
676 }
677 
main(int argc,char * argv[])678 int main(int argc, char *argv[])
679 {
680     unsigned int seed = av_get_random_seed();
681     int i, ret = 0;
682 
683 #if ARCH_ARM && HAVE_ARMV5TE_EXTERNAL
684     if (have_vfp(av_get_cpu_flags()) || have_neon(av_get_cpu_flags()))
685         checkasm_checked_call = checkasm_checked_call_vfp;
686 #endif
687 
688     if (!tests[0].func || !cpus[0].flag) {
689         fprintf(stderr, "checkasm: no tests to perform\n");
690         return 0;
691     }
692 
693     while (argc > 1) {
694         if (!strncmp(argv[1], "--bench", 7)) {
695             if (bench_init() < 0)
696                 return 1;
697             if (argv[1][7] == '=') {
698                 state.bench_pattern = argv[1] + 8;
699                 state.bench_pattern_len = strlen(state.bench_pattern);
700             } else
701                 state.bench_pattern = "";
702         } else if (!strncmp(argv[1], "--test=", 7)) {
703             state.test_name = argv[1] + 7;
704         } else if (!strcmp(argv[1], "--verbose") || !strcmp(argv[1], "-v")) {
705             state.verbose = 1;
706         } else {
707             seed = strtoul(argv[1], NULL, 10);
708         }
709 
710         argc--;
711         argv++;
712     }
713 
714     fprintf(stderr, "checkasm: using random seed %u\n", seed);
715     av_lfg_init(&checkasm_lfg, seed);
716 
717     check_cpu_flag(NULL, 0);
718     for (i = 0; cpus[i].flag; i++)
719         check_cpu_flag(cpus[i].name, cpus[i].flag);
720 
721     if (state.num_failed) {
722         fprintf(stderr, "checkasm: %d of %d tests have failed\n", state.num_failed, state.num_checked);
723         ret = 1;
724     } else {
725         fprintf(stderr, "checkasm: all %d tests passed\n", state.num_checked);
726         if (state.bench_pattern) {
727             print_benchs(state.funcs);
728         }
729     }
730 
731     destroy_func_tree(state.funcs);
732     bench_uninit();
733     return ret;
734 }
735 
736 /* Decide whether or not the specified function needs to be tested and
737  * allocate/initialize data structures if needed. Returns a pointer to a
738  * reference function if the function should be tested, otherwise NULL */
checkasm_check_func(void * func,const char * name,...)739 void *checkasm_check_func(void *func, const char *name, ...)
740 {
741     char name_buf[256];
742     void *ref = func;
743     CheckasmFuncVersion *v;
744     int name_length;
745     va_list arg;
746 
747     va_start(arg, name);
748     name_length = vsnprintf(name_buf, sizeof(name_buf), name, arg);
749     va_end(arg);
750 
751     if (!func || name_length <= 0 || name_length >= sizeof(name_buf))
752         return NULL;
753 
754     state.current_func = get_func(&state.funcs, name_buf);
755     state.funcs->color = 1;
756     v = &state.current_func->versions;
757 
758     if (v->func) {
759         CheckasmFuncVersion *prev;
760         do {
761             /* Only test functions that haven't already been tested */
762             if (v->func == func)
763                 return NULL;
764 
765             if (v->ok)
766                 ref = v->func;
767 
768             prev = v;
769         } while ((v = v->next));
770 
771         v = prev->next = checkasm_malloc(sizeof(CheckasmFuncVersion));
772     }
773 
774     v->func = func;
775     v->ok = 1;
776     v->cpu = state.cpu_flag;
777     state.current_func_ver = v;
778 
779     if (state.cpu_flag)
780         state.num_checked++;
781 
782     return ref;
783 }
784 
785 /* Decide whether or not the current function needs to be benchmarked */
checkasm_bench_func(void)786 int checkasm_bench_func(void)
787 {
788     return !state.num_failed && state.bench_pattern &&
789            !strncmp(state.current_func->name, state.bench_pattern, state.bench_pattern_len);
790 }
791 
792 /* Indicate that the current test has failed */
checkasm_fail_func(const char * msg,...)793 void checkasm_fail_func(const char *msg, ...)
794 {
795     if (state.current_func_ver->cpu && state.current_func_ver->ok) {
796         va_list arg;
797 
798         print_cpu_name();
799         fprintf(stderr, "   %s_%s (", state.current_func->name, cpu_suffix(state.current_func_ver->cpu));
800         va_start(arg, msg);
801         vfprintf(stderr, msg, arg);
802         va_end(arg);
803         fprintf(stderr, ")\n");
804 
805         state.current_func_ver->ok = 0;
806         state.num_failed++;
807     }
808 }
809 
810 /* Get the benchmark context of the current function */
checkasm_get_perf_context(void)811 CheckasmPerf *checkasm_get_perf_context(void)
812 {
813     CheckasmPerf *perf = &state.current_func_ver->perf;
814     memset(perf, 0, sizeof(*perf));
815     perf->sysfd = state.sysfd;
816     return perf;
817 }
818 
819 /* Print the outcome of all tests performed since the last time this function was called */
checkasm_report(const char * name,...)820 void checkasm_report(const char *name, ...)
821 {
822     static int prev_checked, prev_failed, max_length;
823 
824     if (state.num_checked > prev_checked) {
825         int pad_length = max_length + 4;
826         va_list arg;
827 
828         print_cpu_name();
829         pad_length -= fprintf(stderr, " - %s.", state.current_test_name);
830         va_start(arg, name);
831         pad_length -= vfprintf(stderr, name, arg);
832         va_end(arg);
833         fprintf(stderr, "%*c", FFMAX(pad_length, 0) + 2, '[');
834 
835         if (state.num_failed == prev_failed)
836             color_printf(COLOR_GREEN, "OK");
837         else
838             color_printf(COLOR_RED, "FAILED");
839         fprintf(stderr, "]\n");
840 
841         prev_checked = state.num_checked;
842         prev_failed  = state.num_failed;
843     } else if (!state.cpu_flag) {
844         /* Calculate the amount of padding required to make the output vertically aligned */
845         int length = strlen(state.current_test_name);
846         va_list arg;
847 
848         va_start(arg, name);
849         length += vsnprintf(NULL, 0, name, arg);
850         va_end(arg);
851 
852         if (length > max_length)
853             max_length = length;
854     }
855 }
856 
857 #define DEF_CHECKASM_CHECK_FUNC(type, fmt) \
858 int checkasm_check_##type(const char *const file, const int line, \
859                           const type *buf1, ptrdiff_t stride1, \
860                           const type *buf2, ptrdiff_t stride2, \
861                           const int w, int h, const char *const name) \
862 { \
863     int y = 0; \
864     stride1 /= sizeof(*buf1); \
865     stride2 /= sizeof(*buf2); \
866     for (y = 0; y < h; y++) \
867         if (memcmp(&buf1[y*stride1], &buf2[y*stride2], w*sizeof(*buf1))) \
868             break; \
869     if (y == h) \
870         return 0; \
871     checkasm_fail_func("%s:%d", file, line); \
872     if (!state.verbose) \
873         return 1; \
874     fprintf(stderr, "%s:\n", name); \
875     while (h--) { \
876         for (int x = 0; x < w; x++) \
877             fprintf(stderr, " " fmt, buf1[x]); \
878         fprintf(stderr, "    "); \
879         for (int x = 0; x < w; x++) \
880             fprintf(stderr, " " fmt, buf2[x]); \
881         fprintf(stderr, "    "); \
882         for (int x = 0; x < w; x++) \
883             fprintf(stderr, "%c", buf1[x] != buf2[x] ? 'x' : '.'); \
884         buf1 += stride1; \
885         buf2 += stride2; \
886         fprintf(stderr, "\n"); \
887     } \
888     return 1; \
889 }
890 
891 DEF_CHECKASM_CHECK_FUNC(uint8_t,  "%02x")
892 DEF_CHECKASM_CHECK_FUNC(uint16_t, "%04x")
893 DEF_CHECKASM_CHECK_FUNC(int16_t,  "%6d")
894 DEF_CHECKASM_CHECK_FUNC(int32_t,  "%9d")
895