]> git.sesse.net Git - ffmpeg/blob - libavutil/eval.c
id3v2: skip broken tags with invalid size
[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 Libav.
6  *
7  * Libav 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  * Libav 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 Libav; 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, e_isnan,
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_isnan:  return e->value * !!isnan(eval_expr(p, e->param[0]));
148         case e_while: {
149             double d = NAN;
150             while (eval_expr(p, e->param[0]))
151                 d=eval_expr(p, e->param[1]);
152             return d;
153         }
154         default: {
155             double d = eval_expr(p, e->param[0]);
156             double d2 = eval_expr(p, e->param[1]);
157             switch (e->type) {
158                 case e_mod: return e->value * (d - floor(d/d2)*d2);
159                 case e_max: return e->value * (d >  d2 ?   d : d2);
160                 case e_min: return e->value * (d <  d2 ?   d : d2);
161                 case e_eq:  return e->value * (d == d2 ? 1.0 : 0.0);
162                 case e_gt:  return e->value * (d >  d2 ? 1.0 : 0.0);
163                 case e_gte: return e->value * (d >= d2 ? 1.0 : 0.0);
164                 case e_pow: return e->value * pow(d, d2);
165                 case e_mul: return e->value * (d * d2);
166                 case e_div: return e->value * (d / d2);
167                 case e_add: return e->value * (d + d2);
168                 case e_last:return e->value * d2;
169                 case e_st : return e->value * (p->var[av_clip(d, 0, VARS-1)]= d2);
170             }
171         }
172     }
173     return NAN;
174 }
175
176 static int parse_expr(AVExpr **e, Parser *p);
177
178 void av_expr_free(AVExpr *e)
179 {
180     if (!e) return;
181     av_expr_free(e->param[0]);
182     av_expr_free(e->param[1]);
183     av_freep(&e);
184 }
185
186 static int parse_primary(AVExpr **e, Parser *p)
187 {
188     AVExpr *d = av_mallocz(sizeof(AVExpr));
189     char *next = p->s, *s0 = p->s;
190     int ret, i;
191
192     if (!d)
193         return AVERROR(ENOMEM);
194
195     /* number */
196     d->value = av_strtod(p->s, &next);
197     if (next != p->s) {
198         d->type = e_value;
199         p->s= next;
200         *e = d;
201         return 0;
202     }
203     d->value = 1;
204
205     /* named constants */
206     for (i=0; p->const_names && p->const_names[i]; i++) {
207         if (strmatch(p->s, p->const_names[i])) {
208             p->s+= strlen(p->const_names[i]);
209             d->type = e_const;
210             d->a.const_index = i;
211             *e = d;
212             return 0;
213         }
214     }
215
216     p->s= strchr(p->s, '(');
217     if (p->s==NULL) {
218         av_log(p, AV_LOG_ERROR, "Undefined constant or missing '(' in '%s'\n", s0);
219         p->s= next;
220         av_expr_free(d);
221         return AVERROR(EINVAL);
222     }
223     p->s++; // "("
224     if (*next == '(') { // special case do-nothing
225         av_freep(&d);
226         if ((ret = parse_expr(&d, p)) < 0)
227             return ret;
228         if (p->s[0] != ')') {
229             av_log(p, AV_LOG_ERROR, "Missing ')' in '%s'\n", s0);
230             av_expr_free(d);
231             return AVERROR(EINVAL);
232         }
233         p->s++; // ")"
234         *e = d;
235         return 0;
236     }
237     if ((ret = parse_expr(&(d->param[0]), p)) < 0) {
238         av_expr_free(d);
239         return ret;
240     }
241     if (p->s[0]== ',') {
242         p->s++; // ","
243         parse_expr(&d->param[1], p);
244     }
245     if (p->s[0] != ')') {
246         av_log(p, AV_LOG_ERROR, "Missing ')' or too many args in '%s'\n", s0);
247         av_expr_free(d);
248         return AVERROR(EINVAL);
249     }
250     p->s++; // ")"
251
252     d->type = e_func0;
253          if (strmatch(next, "sinh"  )) d->a.func0 = sinh;
254     else if (strmatch(next, "cosh"  )) d->a.func0 = cosh;
255     else if (strmatch(next, "tanh"  )) d->a.func0 = tanh;
256     else if (strmatch(next, "sin"   )) d->a.func0 = sin;
257     else if (strmatch(next, "cos"   )) d->a.func0 = cos;
258     else if (strmatch(next, "tan"   )) d->a.func0 = tan;
259     else if (strmatch(next, "atan"  )) d->a.func0 = atan;
260     else if (strmatch(next, "asin"  )) d->a.func0 = asin;
261     else if (strmatch(next, "acos"  )) d->a.func0 = acos;
262     else if (strmatch(next, "exp"   )) d->a.func0 = exp;
263     else if (strmatch(next, "log"   )) d->a.func0 = log;
264     else if (strmatch(next, "abs"   )) d->a.func0 = fabs;
265     else if (strmatch(next, "squish")) d->type = e_squish;
266     else if (strmatch(next, "gauss" )) d->type = e_gauss;
267     else if (strmatch(next, "mod"   )) d->type = e_mod;
268     else if (strmatch(next, "max"   )) d->type = e_max;
269     else if (strmatch(next, "min"   )) d->type = e_min;
270     else if (strmatch(next, "eq"    )) d->type = e_eq;
271     else if (strmatch(next, "gte"   )) d->type = e_gte;
272     else if (strmatch(next, "gt"    )) d->type = e_gt;
273     else if (strmatch(next, "lte"   )) { AVExpr *tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gt; }
274     else if (strmatch(next, "lt"    )) { AVExpr *tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gte; }
275     else if (strmatch(next, "ld"    )) d->type = e_ld;
276     else if (strmatch(next, "isnan" )) d->type = e_isnan;
277     else if (strmatch(next, "st"    )) d->type = e_st;
278     else if (strmatch(next, "while" )) d->type = e_while;
279     else {
280         for (i=0; p->func1_names && p->func1_names[i]; i++) {
281             if (strmatch(next, p->func1_names[i])) {
282                 d->a.func1 = p->funcs1[i];
283                 d->type = e_func1;
284                 *e = d;
285                 return 0;
286             }
287         }
288
289         for (i=0; p->func2_names && p->func2_names[i]; i++) {
290             if (strmatch(next, p->func2_names[i])) {
291                 d->a.func2 = p->funcs2[i];
292                 d->type = e_func2;
293                 *e = d;
294                 return 0;
295             }
296         }
297
298         av_log(p, AV_LOG_ERROR, "Unknown function in '%s'\n", s0);
299         av_expr_free(d);
300         return AVERROR(EINVAL);
301     }
302
303     *e = d;
304     return 0;
305 }
306
307 static AVExpr *new_eval_expr(int type, int value, AVExpr *p0, AVExpr *p1)
308 {
309     AVExpr *e = av_mallocz(sizeof(AVExpr));
310     if (!e)
311         return NULL;
312     e->type     =type   ;
313     e->value    =value  ;
314     e->param[0] =p0     ;
315     e->param[1] =p1     ;
316     return e;
317 }
318
319 static int parse_pow(AVExpr **e, Parser *p, int *sign)
320 {
321     *sign= (*p->s == '+') - (*p->s == '-');
322     p->s += *sign&1;
323     return parse_primary(e, p);
324 }
325
326 static int parse_factor(AVExpr **e, Parser *p)
327 {
328     int sign, sign2, ret;
329     AVExpr *e0, *e1, *e2;
330     if ((ret = parse_pow(&e0, p, &sign)) < 0)
331         return ret;
332     while(p->s[0]=='^'){
333         e1 = e0;
334         p->s++;
335         if ((ret = parse_pow(&e2, p, &sign2)) < 0) {
336             av_expr_free(e1);
337             return ret;
338         }
339         e0 = new_eval_expr(e_pow, 1, e1, e2);
340         if (!e0) {
341             av_expr_free(e1);
342             av_expr_free(e2);
343             return AVERROR(ENOMEM);
344         }
345         if (e0->param[1]) e0->param[1]->value *= (sign2|1);
346     }
347     if (e0) e0->value *= (sign|1);
348
349     *e = e0;
350     return 0;
351 }
352
353 static int parse_term(AVExpr **e, Parser *p)
354 {
355     int ret;
356     AVExpr *e0, *e1, *e2;
357     if ((ret = parse_factor(&e0, p)) < 0)
358         return ret;
359     while (p->s[0]=='*' || p->s[0]=='/') {
360         int c= *p->s++;
361         e1 = e0;
362         if ((ret = parse_factor(&e2, p)) < 0) {
363             av_expr_free(e1);
364             return ret;
365         }
366         e0 = new_eval_expr(c == '*' ? e_mul : e_div, 1, e1, e2);
367         if (!e0) {
368             av_expr_free(e1);
369             av_expr_free(e2);
370             return AVERROR(ENOMEM);
371         }
372     }
373     *e = e0;
374     return 0;
375 }
376
377 static int parse_subexpr(AVExpr **e, Parser *p)
378 {
379     int ret;
380     AVExpr *e0, *e1, *e2;
381     if ((ret = parse_term(&e0, p)) < 0)
382         return ret;
383     while (*p->s == '+' || *p->s == '-') {
384         e1 = e0;
385         if ((ret = parse_term(&e2, p)) < 0) {
386             av_expr_free(e1);
387             return ret;
388         }
389         e0 = new_eval_expr(e_add, 1, e1, e2);
390         if (!e0) {
391             av_expr_free(e1);
392             av_expr_free(e2);
393             return AVERROR(ENOMEM);
394         }
395     };
396
397     *e = e0;
398     return 0;
399 }
400
401 static int parse_expr(AVExpr **e, Parser *p)
402 {
403     int ret;
404     AVExpr *e0, *e1, *e2;
405     if (p->stack_index <= 0) //protect against stack overflows
406         return AVERROR(EINVAL);
407     p->stack_index--;
408
409     if ((ret = parse_subexpr(&e0, p)) < 0)
410         return ret;
411     while (*p->s == ';') {
412         p->s++;
413         e1 = e0;
414         if ((ret = parse_subexpr(&e2, p)) < 0) {
415             av_expr_free(e1);
416             return ret;
417         }
418         e0 = new_eval_expr(e_last, 1, e1, e2);
419         if (!e0) {
420             av_expr_free(e1);
421             av_expr_free(e2);
422             return AVERROR(ENOMEM);
423         }
424     };
425
426     p->stack_index++;
427     *e = e0;
428     return 0;
429 }
430
431 static int verify_expr(AVExpr *e)
432 {
433     if (!e) return 0;
434     switch (e->type) {
435         case e_value:
436         case e_const: return 1;
437         case e_func0:
438         case e_func1:
439         case e_squish:
440         case e_ld:
441         case e_gauss:
442         case e_isnan: return verify_expr(e->param[0]);
443         default: return verify_expr(e->param[0]) && verify_expr(e->param[1]);
444     }
445 }
446
447 int av_expr_parse(AVExpr **expr, const char *s,
448                   const char * const *const_names,
449                   const char * const *func1_names, double (* const *funcs1)(void *, double),
450                   const char * const *func2_names, double (* const *funcs2)(void *, double, double),
451                   int log_offset, void *log_ctx)
452 {
453     Parser p;
454     AVExpr *e = NULL;
455     char *w = av_malloc(strlen(s) + 1);
456     char *wp = w;
457     const char *s0 = s;
458     int ret = 0;
459
460     if (!w)
461         return AVERROR(ENOMEM);
462
463     while (*s)
464         if (!isspace(*s++)) *wp++ = s[-1];
465     *wp++ = 0;
466
467     p.class      = &class;
468     p.stack_index=100;
469     p.s= w;
470     p.const_names = const_names;
471     p.funcs1      = funcs1;
472     p.func1_names = func1_names;
473     p.funcs2      = funcs2;
474     p.func2_names = func2_names;
475     p.log_offset = log_offset;
476     p.log_ctx    = log_ctx;
477
478     if ((ret = parse_expr(&e, &p)) < 0)
479         goto end;
480     if (*p.s) {
481         av_log(&p, AV_LOG_ERROR, "Invalid chars '%s' at the end of expression '%s'\n", p.s, s0);
482         ret = AVERROR(EINVAL);
483         goto end;
484     }
485     if (!verify_expr(e)) {
486         av_expr_free(e);
487         ret = AVERROR(EINVAL);
488         goto end;
489     }
490     *expr = e;
491 end:
492     av_free(w);
493     return ret;
494 }
495
496 double av_expr_eval(AVExpr *e, const double *const_values, void *opaque)
497 {
498     Parser p;
499
500     p.const_values = const_values;
501     p.opaque     = opaque;
502     return eval_expr(&p, e);
503 }
504
505 int av_expr_parse_and_eval(double *d, const char *s,
506                            const char * const *const_names, const double *const_values,
507                            const char * const *func1_names, double (* const *funcs1)(void *, double),
508                            const char * const *func2_names, double (* const *funcs2)(void *, double, double),
509                            void *opaque, int log_offset, void *log_ctx)
510 {
511     AVExpr *e = NULL;
512     int ret = av_expr_parse(&e, s, const_names, func1_names, funcs1, func2_names, funcs2, log_offset, log_ctx);
513
514     if (ret < 0) {
515         *d = NAN;
516         return ret;
517     }
518     *d = av_expr_eval(e, const_values, opaque);
519     av_expr_free(e);
520     return isnan(*d) ? AVERROR(EINVAL) : 0;
521 }
522
523 #if FF_API_OLD_EVAL_NAMES
524 int av_parse_expr(AVExpr **expr, const char *s,
525                   const char * const *const_names,
526                   const char * const *func1_names, double (* const *funcs1)(void *, double),
527                   const char * const *func2_names, double (* const *funcs2)(void *, double, double),
528                   int log_offset, void *log_ctx)
529 {
530     return av_expr_parse(expr, s, const_names, func1_names, funcs1, func2_names, funcs2,
531                       log_offset, log_ctx);
532 }
533
534 double av_eval_expr(AVExpr *e, const double *const_values, void *opaque)
535 {
536     return av_expr_eval(e, const_values, opaque);
537 }
538
539 int av_parse_and_eval_expr(double *res, const char *s,
540                            const char * const *const_names, const double *const_values,
541                            const char * const *func1_names, double (* const *funcs1)(void *, double),
542                            const char * const *func2_names, double (* const *funcs2)(void *, double, double),
543                            void *opaque, int log_offset, void *log_ctx)
544 {
545     return av_expr_parse_and_eval(res, s, const_names, const_values, func1_names, funcs1, func2_names, funcs2,
546                                   opaque, log_offset, log_ctx);
547 }
548
549 void av_free_expr(AVExpr *e)
550 {
551     av_expr_free(e);
552 }
553 #endif /* FF_API_OLD_EVAL_NAMES */
554
555 #ifdef TEST
556 #undef printf
557 static double const_values[] = {
558     M_PI,
559     M_E,
560     0
561 };
562
563 static const char *const_names[] = {
564     "PI",
565     "E",
566     0
567 };
568
569 int main(void)
570 {
571     int i;
572     double d;
573     const char **expr, *exprs[] = {
574         "",
575         "1;2",
576         "-20",
577         "-PI",
578         "+PI",
579         "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)",
580         "80G/80Gi"
581         "1k",
582         "1Gi",
583         "1gi",
584         "1GiFoo",
585         "1k+1k",
586         "1Gi*3foo",
587         "foo",
588         "foo(",
589         "foo()",
590         "foo)",
591         "sin",
592         "sin(",
593         "sin()",
594         "sin)",
595         "sin 10",
596         "sin(1,2,3)",
597         "sin(1 )",
598         "1",
599         "1foo",
600         "bar + PI + E + 100f*2 + foo",
601         "13k + 12f - foo(1, 2)",
602         "1gi",
603         "1Gi",
604         "st(0, 123)",
605         "st(1, 123); ld(1)",
606         /* compute 1+2+...+N */
607         "st(0, 1); while(lte(ld(0), 100), st(1, ld(1)+ld(0));st(0, ld(0)+1)); ld(1)",
608         /* compute Fib(N) */
609         "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)",
610         "while(0, 10)",
611         "st(0, 1); while(lte(ld(0),100), st(1, ld(1)+ld(0)); st(0, ld(0)+1))",
612         "isnan(1)",
613         "isnan(NAN)",
614         NULL
615     };
616
617     for (expr = exprs; *expr; expr++) {
618         printf("Evaluating '%s'\n", *expr);
619         av_expr_parse_and_eval(&d, *expr,
620                                const_names, const_values,
621                                NULL, NULL, NULL, NULL, NULL, 0, NULL);
622         printf("'%s' -> %f\n\n", *expr, d);
623     }
624
625     av_expr_parse_and_eval(&d, "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)",
626                            const_names, const_values,
627                            NULL, NULL, NULL, NULL, NULL, 0, NULL);
628     printf("%f == 12.7\n", d);
629     av_expr_parse_and_eval(&d, "80G/80Gi",
630                            const_names, const_values,
631                            NULL, NULL, NULL, NULL, NULL, 0, NULL);
632     printf("%f == 0.931322575\n", d);
633
634     for (i=0; i<1050; i++) {
635         START_TIMER
636             av_expr_parse_and_eval(&d, "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)",
637                                    const_names, const_values,
638                                    NULL, NULL, NULL, NULL, NULL, 0, NULL);
639         STOP_TIMER("av_expr_parse_and_eval")
640     }
641     return 0;
642 }
643 #endif