]> git.sesse.net Git - ffmpeg/blob - libavutil/eval.c
a4ae2695d7d45b160ae59eb05af684252e6711fe
[ffmpeg] / libavutil / eval.c
1 /*
2  * Copyright (c) 2002-2006 Michael Niedermayer <michaelni@gmx.at>
3  * Copyright (c) 2006 Oded Shimon <ods15@ods15.dyndns.org>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * simple arithmetic expression evaluator.
25  *
26  * see http://joe.hotchkiss.com/programming/eval/eval.html
27  */
28
29 #include "libavutil/avutil.h"
30 #include "eval.h"
31
32 typedef struct Parser {
33     const AVClass *class;
34     int stack_index;
35     char *s;
36     const double *const_values;
37     const char * const *const_names;          // NULL terminated
38     double (* const *funcs1)(void *, double a);           // NULL terminated
39     const char * const *func1_names;          // NULL terminated
40     double (* const *funcs2)(void *, double a, double b); // NULL terminated
41     const char * const *func2_names;          // NULL terminated
42     void *opaque;
43     int log_offset;
44     void *log_ctx;
45 #define VARS 10
46     double var[VARS];
47 } Parser;
48
49 static const AVClass class = { "Eval", av_default_item_name, NULL, LIBAVUTIL_VERSION_INT, offsetof(Parser,log_offset), offsetof(Parser,log_ctx) };
50
51 static const int8_t si_prefixes['z' - 'E' + 1] = {
52     ['y'-'E']= -24,
53     ['z'-'E']= -21,
54     ['a'-'E']= -18,
55     ['f'-'E']= -15,
56     ['p'-'E']= -12,
57     ['n'-'E']= - 9,
58     ['u'-'E']= - 6,
59     ['m'-'E']= - 3,
60     ['c'-'E']= - 2,
61     ['d'-'E']= - 1,
62     ['h'-'E']=   2,
63     ['k'-'E']=   3,
64     ['K'-'E']=   3,
65     ['M'-'E']=   6,
66     ['G'-'E']=   9,
67     ['T'-'E']=  12,
68     ['P'-'E']=  15,
69     ['E'-'E']=  18,
70     ['Z'-'E']=  21,
71     ['Y'-'E']=  24,
72 };
73
74 double av_strtod(const char *numstr, char **tail)
75 {
76     double d;
77     char *next;
78     d = strtod(numstr, &next);
79     /* if parsing succeeded, check for and interpret postfixes */
80     if (next!=numstr) {
81         if (*next >= 'E' && *next <= 'z') {
82             int e= si_prefixes[*next - 'E'];
83             if (e) {
84                 if (next[1] == 'i') {
85                     d*= pow( 2, e/0.3);
86                     next+=2;
87                 } else {
88                     d*= pow(10, e);
89                     next++;
90                 }
91             }
92         }
93
94         if (*next=='B') {
95             d*=8;
96             next++;
97         }
98     }
99     /* if requested, fill in tail with the position after the last parsed
100        character */
101     if (tail)
102         *tail = next;
103     return d;
104 }
105
106 #define IS_IDENTIFIER_CHAR(c) ((c) - '0' <= 9U || (c) - 'a' <= 25U || (c) - 'A' <= 25U || (c) == '_')
107
108 static int strmatch(const char *s, const char *prefix)
109 {
110     int i;
111     for (i=0; prefix[i]; i++) {
112         if (prefix[i] != s[i]) return 0;
113     }
114     /* return 1 only if the s identifier is terminated */
115     return !IS_IDENTIFIER_CHAR(s[i]);
116 }
117
118 struct AVExpr {
119     enum {
120         e_value, e_const, e_func0, e_func1, e_func2,
121         e_squish, e_gauss, e_ld,
122         e_mod, e_max, e_min, e_eq, e_gt, e_gte,
123         e_pow, e_mul, e_div, e_add,
124         e_last, e_st, e_while,
125     } type;
126     double value; // is sign in other types
127     union {
128         int const_index;
129         double (*func0)(double);
130         double (*func1)(void *, double);
131         double (*func2)(void *, double, double);
132     } a;
133     struct AVExpr *param[2];
134 };
135
136 static double eval_expr(Parser *p, AVExpr *e)
137 {
138     switch (e->type) {
139         case e_value:  return e->value;
140         case e_const:  return e->value * p->const_values[e->a.const_index];
141         case e_func0:  return e->value * e->a.func0(eval_expr(p, e->param[0]));
142         case e_func1:  return e->value * e->a.func1(p->opaque, eval_expr(p, e->param[0]));
143         case e_func2:  return e->value * e->a.func2(p->opaque, eval_expr(p, e->param[0]), eval_expr(p, e->param[1]));
144         case e_squish: return 1/(1+exp(4*eval_expr(p, e->param[0])));
145         case e_gauss: { double d = eval_expr(p, e->param[0]); return exp(-d*d/2)/sqrt(2*M_PI); }
146         case e_ld:     return e->value * p->var[av_clip(eval_expr(p, e->param[0]), 0, VARS-1)];
147         case e_while: {
148             double d = NAN;
149             while (eval_expr(p, e->param[0]))
150                 d=eval_expr(p, e->param[1]);
151             return d;
152         }
153         default: {
154             double d = eval_expr(p, e->param[0]);
155             double d2 = eval_expr(p, e->param[1]);
156             switch (e->type) {
157                 case e_mod: return e->value * (d - floor(d/d2)*d2);
158                 case e_max: return e->value * (d >  d2 ?   d : d2);
159                 case e_min: return e->value * (d <  d2 ?   d : d2);
160                 case e_eq:  return e->value * (d == d2 ? 1.0 : 0.0);
161                 case e_gt:  return e->value * (d >  d2 ? 1.0 : 0.0);
162                 case e_gte: return e->value * (d >= d2 ? 1.0 : 0.0);
163                 case e_pow: return e->value * pow(d, d2);
164                 case e_mul: return e->value * (d * d2);
165                 case e_div: return e->value * (d / d2);
166                 case e_add: return e->value * (d + d2);
167                 case e_last:return e->value * d2;
168                 case e_st : return e->value * (p->var[av_clip(d, 0, VARS-1)]= d2);
169             }
170         }
171     }
172     return NAN;
173 }
174
175 static int parse_expr(AVExpr **e, Parser *p);
176
177 void av_free_expr(AVExpr *e)
178 {
179     if (!e) return;
180     av_free_expr(e->param[0]);
181     av_free_expr(e->param[1]);
182     av_freep(&e);
183 }
184
185 static int parse_primary(AVExpr **e, Parser *p)
186 {
187     AVExpr *d = av_mallocz(sizeof(AVExpr));
188     char *next = p->s, *s0 = p->s;
189     int ret, i;
190
191     if (!d)
192         return AVERROR(ENOMEM);
193
194     /* number */
195     d->value = av_strtod(p->s, &next);
196     if (next != p->s) {
197         d->type = e_value;
198         p->s= next;
199         *e = d;
200         return 0;
201     }
202     d->value = 1;
203
204     /* named constants */
205     for (i=0; p->const_names && p->const_names[i]; i++) {
206         if (strmatch(p->s, p->const_names[i])) {
207             p->s+= strlen(p->const_names[i]);
208             d->type = e_const;
209             d->a.const_index = i;
210             *e = d;
211             return 0;
212         }
213     }
214
215     p->s= strchr(p->s, '(');
216     if (p->s==NULL) {
217         av_log(p, AV_LOG_ERROR, "Undefined constant or missing '(' in '%s'\n", s0);
218         p->s= next;
219         av_free_expr(d);
220         return AVERROR(EINVAL);
221     }
222     p->s++; // "("
223     if (*next == '(') { // special case do-nothing
224         av_freep(&d);
225         if ((ret = parse_expr(&d, p)) < 0)
226             return ret;
227         if (p->s[0] != ')') {
228             av_log(p, AV_LOG_ERROR, "Missing ')' in '%s'\n", s0);
229             av_free_expr(d);
230             return AVERROR(EINVAL);
231         }
232         p->s++; // ")"
233         *e = d;
234         return 0;
235     }
236     if ((ret = parse_expr(&(d->param[0]), p)) < 0) {
237         av_free_expr(d);
238         return ret;
239     }
240     if (p->s[0]== ',') {
241         p->s++; // ","
242         parse_expr(&d->param[1], p);
243     }
244     if (p->s[0] != ')') {
245         av_log(p, AV_LOG_ERROR, "Missing ')' or too many args in '%s'\n", s0);
246         av_free_expr(d);
247         return AVERROR(EINVAL);
248     }
249     p->s++; // ")"
250
251     d->type = e_func0;
252          if (strmatch(next, "sinh"  )) d->a.func0 = sinh;
253     else if (strmatch(next, "cosh"  )) d->a.func0 = cosh;
254     else if (strmatch(next, "tanh"  )) d->a.func0 = tanh;
255     else if (strmatch(next, "sin"   )) d->a.func0 = sin;
256     else if (strmatch(next, "cos"   )) d->a.func0 = cos;
257     else if (strmatch(next, "tan"   )) d->a.func0 = tan;
258     else if (strmatch(next, "atan"  )) d->a.func0 = atan;
259     else if (strmatch(next, "asin"  )) d->a.func0 = asin;
260     else if (strmatch(next, "acos"  )) d->a.func0 = acos;
261     else if (strmatch(next, "exp"   )) d->a.func0 = exp;
262     else if (strmatch(next, "log"   )) d->a.func0 = log;
263     else if (strmatch(next, "abs"   )) d->a.func0 = fabs;
264     else if (strmatch(next, "squish")) d->type = e_squish;
265     else if (strmatch(next, "gauss" )) d->type = e_gauss;
266     else if (strmatch(next, "mod"   )) d->type = e_mod;
267     else if (strmatch(next, "max"   )) d->type = e_max;
268     else if (strmatch(next, "min"   )) d->type = e_min;
269     else if (strmatch(next, "eq"    )) d->type = e_eq;
270     else if (strmatch(next, "gte"   )) d->type = e_gte;
271     else if (strmatch(next, "gt"    )) d->type = e_gt;
272     else if (strmatch(next, "lte"   )) { AVExpr *tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gt; }
273     else if (strmatch(next, "lt"    )) { AVExpr *tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gte; }
274     else if (strmatch(next, "ld"    )) d->type = e_ld;
275     else if (strmatch(next, "st"    )) d->type = e_st;
276     else if (strmatch(next, "while" )) d->type = e_while;
277     else {
278         for (i=0; p->func1_names && p->func1_names[i]; i++) {
279             if (strmatch(next, p->func1_names[i])) {
280                 d->a.func1 = p->funcs1[i];
281                 d->type = e_func1;
282                 *e = d;
283                 return 0;
284             }
285         }
286
287         for (i=0; p->func2_names && p->func2_names[i]; i++) {
288             if (strmatch(next, p->func2_names[i])) {
289                 d->a.func2 = p->funcs2[i];
290                 d->type = e_func2;
291                 *e = d;
292                 return 0;
293             }
294         }
295
296         av_log(p, AV_LOG_ERROR, "Unknown function in '%s'\n", s0);
297         av_free_expr(d);
298         return AVERROR(EINVAL);
299     }
300
301     *e = d;
302     return 0;
303 }
304
305 static AVExpr *new_eval_expr(int type, int value, AVExpr *p0, AVExpr *p1)
306 {
307     AVExpr *e = av_mallocz(sizeof(AVExpr));
308     if (!e)
309         return NULL;
310     e->type     =type   ;
311     e->value    =value  ;
312     e->param[0] =p0     ;
313     e->param[1] =p1     ;
314     return e;
315 }
316
317 static int parse_pow(AVExpr **e, Parser *p, int *sign)
318 {
319     *sign= (*p->s == '+') - (*p->s == '-');
320     p->s += *sign&1;
321     return parse_primary(e, p);
322 }
323
324 static int parse_factor(AVExpr **e, Parser *p)
325 {
326     int sign, sign2, ret;
327     AVExpr *e0, *e1, *e2;
328     if ((ret = parse_pow(&e0, p, &sign)) < 0)
329         return ret;
330     while(p->s[0]=='^'){
331         e1 = e0;
332         p->s++;
333         if ((ret = parse_pow(&e2, p, &sign2)) < 0) {
334             av_free_expr(e1);
335             return ret;
336         }
337         e0 = new_eval_expr(e_pow, 1, e1, e2);
338         if (!e0) {
339             av_free_expr(e1);
340             av_free_expr(e2);
341             return AVERROR(ENOMEM);
342         }
343         if (e0->param[1]) e0->param[1]->value *= (sign2|1);
344     }
345     if (e0) e0->value *= (sign|1);
346
347     *e = e0;
348     return 0;
349 }
350
351 static int parse_term(AVExpr **e, Parser *p)
352 {
353     int ret;
354     AVExpr *e0, *e1, *e2;
355     if ((ret = parse_factor(&e0, p)) < 0)
356         return ret;
357     while (p->s[0]=='*' || p->s[0]=='/') {
358         int c= *p->s++;
359         e1 = e0;
360         if ((ret = parse_factor(&e2, p)) < 0) {
361             av_free_expr(e1);
362             return ret;
363         }
364         e0 = new_eval_expr(c == '*' ? e_mul : e_div, 1, e1, e2);
365         if (!e0) {
366             av_free_expr(e1);
367             av_free_expr(e2);
368             return AVERROR(ENOMEM);
369         }
370     }
371     *e = e0;
372     return 0;
373 }
374
375 static int parse_subexpr(AVExpr **e, Parser *p)
376 {
377     int ret;
378     AVExpr *e0, *e1, *e2;
379     if ((ret = parse_term(&e0, p)) < 0)
380         return ret;
381     while (*p->s == '+' || *p->s == '-') {
382         e1 = e0;
383         if ((ret = parse_term(&e2, p)) < 0) {
384             av_free_expr(e1);
385             return ret;
386         }
387         e0 = new_eval_expr(e_add, 1, e1, e2);
388         if (!e0) {
389             av_free_expr(e1);
390             av_free_expr(e2);
391             return AVERROR(ENOMEM);
392         }
393     };
394
395     *e = e0;
396     return 0;
397 }
398
399 static int parse_expr(AVExpr **e, Parser *p)
400 {
401     int ret;
402     AVExpr *e0, *e1, *e2;
403     if (p->stack_index <= 0) //protect against stack overflows
404         return AVERROR(EINVAL);
405     p->stack_index--;
406
407     if ((ret = parse_subexpr(&e0, p)) < 0)
408         return ret;
409     while (*p->s == ';') {
410         p->s++;
411         e1 = e0;
412         if ((ret = parse_subexpr(&e2, p)) < 0) {
413             av_free_expr(e1);
414             return ret;
415         }
416         e0 = new_eval_expr(e_last, 1, e1, e2);
417         if (!e0) {
418             av_free_expr(e1);
419             av_free_expr(e2);
420             return AVERROR(ENOMEM);
421         }
422     };
423
424     p->stack_index++;
425     *e = e0;
426     return 0;
427 }
428
429 static int verify_expr(AVExpr *e)
430 {
431     if (!e) return 0;
432     switch (e->type) {
433         case e_value:
434         case e_const: return 1;
435         case e_func0:
436         case e_func1:
437         case e_squish:
438         case e_ld:
439         case e_gauss: return verify_expr(e->param[0]);
440         default: return verify_expr(e->param[0]) && verify_expr(e->param[1]);
441     }
442 }
443
444 int av_parse_expr(AVExpr **expr, const char *s,
445                   const char * const *const_names,
446                   const char * const *func1_names, double (* const *funcs1)(void *, double),
447                   const char * const *func2_names, double (* const *funcs2)(void *, double, double),
448                   int log_offset, void *log_ctx)
449 {
450     Parser p;
451     AVExpr *e = NULL;
452     char *w = av_malloc(strlen(s) + 1);
453     char *wp = w;
454     const char *s0 = s;
455     int ret = 0;
456
457     if (!w)
458         return AVERROR(ENOMEM);
459
460     while (*s)
461         if (!isspace(*s++)) *wp++ = s[-1];
462     *wp++ = 0;
463
464     p.class      = &class;
465     p.stack_index=100;
466     p.s= w;
467     p.const_names = const_names;
468     p.funcs1      = funcs1;
469     p.func1_names = func1_names;
470     p.funcs2      = funcs2;
471     p.func2_names = func2_names;
472     p.log_offset = log_offset;
473     p.log_ctx    = log_ctx;
474
475     if ((ret = parse_expr(&e, &p)) < 0)
476         goto end;
477     if (*p.s) {
478         av_log(&p, AV_LOG_ERROR, "Invalid chars '%s' at the end of expression '%s'\n", p.s, s0);
479         ret = AVERROR(EINVAL);
480         goto end;
481     }
482     if (!verify_expr(e)) {
483         av_free_expr(e);
484         ret = AVERROR(EINVAL);
485         goto end;
486     }
487     *expr = e;
488 end:
489     av_free(w);
490     return ret;
491 }
492
493 double av_eval_expr(AVExpr *e, const double *const_values, void *opaque)
494 {
495     Parser p;
496
497     p.const_values = const_values;
498     p.opaque     = opaque;
499     return eval_expr(&p, e);
500 }
501
502 int av_parse_and_eval_expr(double *d, const char *s,
503                            const char * const *const_names, const double *const_values,
504                            const char * const *func1_names, double (* const *funcs1)(void *, double),
505                            const char * const *func2_names, double (* const *funcs2)(void *, double, double),
506                            void *opaque, int log_offset, void *log_ctx)
507 {
508     AVExpr *e = NULL;
509     int ret = av_parse_expr(&e, s, const_names, func1_names, funcs1, func2_names, funcs2, log_offset, log_ctx);
510
511     if (ret < 0) {
512         *d = NAN;
513         return ret;
514     }
515     *d = av_eval_expr(e, const_values, opaque);
516     av_free_expr(e);
517     return isnan(*d) ? AVERROR(EINVAL) : 0;
518 }
519
520 #ifdef TEST
521 #undef printf
522 static double const_values[] = {
523     M_PI,
524     M_E,
525     0
526 };
527
528 static const char *const_names[] = {
529     "PI",
530     "E",
531     0
532 };
533
534 int main(void)
535 {
536     int i;
537     double d;
538     const char **expr, *exprs[] = {
539         "",
540         "1;2",
541         "-20",
542         "-PI",
543         "+PI",
544         "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)",
545         "80G/80Gi"
546         "1k",
547         "1Gi",
548         "1gi",
549         "1GiFoo",
550         "1k+1k",
551         "1Gi*3foo",
552         "foo",
553         "foo(",
554         "foo()",
555         "foo)",
556         "sin",
557         "sin(",
558         "sin()",
559         "sin)",
560         "sin 10",
561         "sin(1,2,3)",
562         "sin(1 )",
563         "1",
564         "1foo",
565         "bar + PI + E + 100f*2 + foo",
566         "13k + 12f - foo(1, 2)",
567         "1gi",
568         "1Gi",
569         "st(0, 123)",
570         "st(1, 123); ld(1)",
571         /* compute 1+2+...+N */
572         "st(0, 1); while(lte(ld(0), 100), st(1, ld(1)+ld(0));st(0, ld(0)+1)); ld(1)",
573         /* compute Fib(N) */
574         "st(1, 1); st(2, 2); st(0, 1); while(lte(ld(0),10), st(3, ld(1)+ld(2)); st(1, ld(2)); st(2, ld(3)); st(0, ld(0)+1)); ld(3)",
575         "while(0, 10)",
576         "st(0, 1); while(lte(ld(0),100), st(1, ld(1)+ld(0)); st(0, ld(0)+1))",
577         NULL
578     };
579
580     for (expr = exprs; *expr; expr++) {
581         printf("Evaluating '%s'\n", *expr);
582         av_parse_and_eval_expr(&d, *expr,
583                                const_names, const_values,
584                                NULL, NULL, NULL, NULL, NULL, 0, NULL);
585         printf("'%s' -> %f\n\n", *expr, d);
586     }
587
588     av_parse_and_eval_expr(&d, "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)",
589                            const_names, const_values,
590                            NULL, NULL, NULL, NULL, NULL, 0, NULL);
591     printf("%f == 12.7\n", d);
592     av_parse_and_eval_expr(&d, "80G/80Gi",
593                            const_names, const_values,
594                            NULL, NULL, NULL, NULL, NULL, 0, NULL);
595     printf("%f == 0.931322575\n", d);
596
597     for (i=0; i<1050; i++) {
598         START_TIMER
599             av_parse_and_eval_expr(&d, "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)",
600                                    const_names, const_values,
601                                    NULL, NULL, NULL, NULL, NULL, 0, NULL);
602         STOP_TIMER("av_parse_and_eval_expr")
603     }
604     return 0;
605 }
606 #endif