]> git.sesse.net Git - ffmpeg/blob - libavutil/eval.c
Merge commit '7bcaeb408e3eb2d2f37a306009fa7fe7eb0f1d79'
[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 <float.h>
30 #include "avutil.h"
31 #include "common.h"
32 #include "eval.h"
33 #include "log.h"
34 #include "mathematics.h"
35 #include "time.h"
36
37 typedef struct Parser {
38     const AVClass *class;
39     int stack_index;
40     char *s;
41     const double *const_values;
42     const char * const *const_names;          // NULL terminated
43     double (* const *funcs1)(void *, double a);           // NULL terminated
44     const char * const *func1_names;          // NULL terminated
45     double (* const *funcs2)(void *, double a, double b); // NULL terminated
46     const char * const *func2_names;          // NULL terminated
47     void *opaque;
48     int log_offset;
49     void *log_ctx;
50 #define VARS 10
51     double *var;
52 } Parser;
53
54 static const AVClass class = { "Eval", av_default_item_name, NULL, LIBAVUTIL_VERSION_INT, offsetof(Parser,log_offset), offsetof(Parser,log_ctx) };
55
56 static const int8_t si_prefixes['z' - 'E' + 1] = {
57     ['y'-'E']= -24,
58     ['z'-'E']= -21,
59     ['a'-'E']= -18,
60     ['f'-'E']= -15,
61     ['p'-'E']= -12,
62     ['n'-'E']= - 9,
63     ['u'-'E']= - 6,
64     ['m'-'E']= - 3,
65     ['c'-'E']= - 2,
66     ['d'-'E']= - 1,
67     ['h'-'E']=   2,
68     ['k'-'E']=   3,
69     ['K'-'E']=   3,
70     ['M'-'E']=   6,
71     ['G'-'E']=   9,
72     ['T'-'E']=  12,
73     ['P'-'E']=  15,
74     ['E'-'E']=  18,
75     ['Z'-'E']=  21,
76     ['Y'-'E']=  24,
77 };
78
79 static const struct {
80     const char *name;
81     double value;
82 } constants[] = {
83     { "E",   M_E   },
84     { "PI",  M_PI  },
85     { "PHI", M_PHI },
86 };
87
88 double av_strtod(const char *numstr, char **tail)
89 {
90     double d;
91     char *next;
92     if(numstr[0]=='0' && (numstr[1]|0x20)=='x') {
93         d = strtoul(numstr, &next, 16);
94     } else
95         d = strtod(numstr, &next);
96     /* if parsing succeeded, check for and interpret postfixes */
97     if (next!=numstr) {
98         if (next[0] == 'd' && next[1] == 'B') {
99             /* treat dB as decibels instead of decibytes */
100             d = pow(10, d / 20);
101             next += 2;
102         } else if (*next >= 'E' && *next <= 'z') {
103             int e= si_prefixes[*next - 'E'];
104             if (e) {
105                 if (next[1] == 'i') {
106                     d*= pow( 2, e/0.3);
107                     next+=2;
108                 } else {
109                     d*= pow(10, e);
110                     next++;
111                 }
112             }
113         }
114
115         if (*next=='B') {
116             d*=8;
117             next++;
118         }
119     }
120     /* if requested, fill in tail with the position after the last parsed
121        character */
122     if (tail)
123         *tail = next;
124     return d;
125 }
126
127 #define IS_IDENTIFIER_CHAR(c) ((c) - '0' <= 9U || (c) - 'a' <= 25U || (c) - 'A' <= 25U || (c) == '_')
128
129 static int strmatch(const char *s, const char *prefix)
130 {
131     int i;
132     for (i=0; prefix[i]; i++) {
133         if (prefix[i] != s[i]) return 0;
134     }
135     /* return 1 only if the s identifier is terminated */
136     return !IS_IDENTIFIER_CHAR(s[i]);
137 }
138
139 struct AVExpr {
140     enum {
141         e_value, e_const, e_func0, e_func1, e_func2,
142         e_squish, e_gauss, e_ld, e_isnan, e_isinf,
143         e_mod, e_max, e_min, e_eq, e_gt, e_gte,
144         e_pow, e_mul, e_div, e_add,
145         e_last, e_st, e_while, e_taylor, e_root, e_floor, e_ceil, e_trunc,
146         e_sqrt, e_not, e_random, e_hypot, e_gcd,
147         e_if, e_ifnot,
148     } type;
149     double value; // is sign in other types
150     union {
151         int const_index;
152         double (*func0)(double);
153         double (*func1)(void *, double);
154         double (*func2)(void *, double, double);
155     } a;
156     struct AVExpr *param[3];
157     double *var;
158 };
159
160 static double etime(double v)
161 {
162     return av_gettime() * 0.000001;
163 }
164
165 static double eval_expr(Parser *p, AVExpr *e)
166 {
167     switch (e->type) {
168         case e_value:  return e->value;
169         case e_const:  return e->value * p->const_values[e->a.const_index];
170         case e_func0:  return e->value * e->a.func0(eval_expr(p, e->param[0]));
171         case e_func1:  return e->value * e->a.func1(p->opaque, eval_expr(p, e->param[0]));
172         case e_func2:  return e->value * e->a.func2(p->opaque, eval_expr(p, e->param[0]), eval_expr(p, e->param[1]));
173         case e_squish: return 1/(1+exp(4*eval_expr(p, e->param[0])));
174         case e_gauss: { double d = eval_expr(p, e->param[0]); return exp(-d*d/2)/sqrt(2*M_PI); }
175         case e_ld:     return e->value * p->var[av_clip(eval_expr(p, e->param[0]), 0, VARS-1)];
176         case e_isnan:  return e->value * !!isnan(eval_expr(p, e->param[0]));
177         case e_isinf:  return e->value * !!isinf(eval_expr(p, e->param[0]));
178         case e_floor:  return e->value * floor(eval_expr(p, e->param[0]));
179         case e_ceil :  return e->value * ceil (eval_expr(p, e->param[0]));
180         case e_trunc:  return e->value * trunc(eval_expr(p, e->param[0]));
181         case e_sqrt:   return e->value * sqrt (eval_expr(p, e->param[0]));
182         case e_not:    return e->value * (eval_expr(p, e->param[0]) == 0);
183         case e_if:     return e->value * (eval_expr(p, e->param[0]) ? eval_expr(p, e->param[1]) :
184                                           e->param[2] ? eval_expr(p, e->param[2]) : 0);
185         case e_ifnot:  return e->value * (!eval_expr(p, e->param[0]) ? eval_expr(p, e->param[1]) :
186                                           e->param[2] ? eval_expr(p, e->param[2]) : 0);
187         case e_random:{
188             int idx= av_clip(eval_expr(p, e->param[0]), 0, VARS-1);
189             uint64_t r= isnan(p->var[idx]) ? 0 : p->var[idx];
190             r= r*1664525+1013904223;
191             p->var[idx]= r;
192             return e->value * (r * (1.0/UINT64_MAX));
193         }
194         case e_while: {
195             double d = NAN;
196             while (eval_expr(p, e->param[0]))
197                 d=eval_expr(p, e->param[1]);
198             return d;
199         }
200         case e_taylor: {
201             double t = 1, d = 0, v;
202             double x = eval_expr(p, e->param[1]);
203             int id = e->param[2] ? av_clip(eval_expr(p, e->param[2]), 0, VARS-1) : 0;
204             int i;
205             double var0 = p->var[id];
206             for(i=0; i<1000; i++) {
207                 double ld = d;
208                 p->var[id] = i;
209                 v = eval_expr(p, e->param[0]);
210                 d += t*v;
211                 if(ld==d && v)
212                     break;
213                 t *= x / (i+1);
214             }
215             p->var[id] = var0;
216             return d;
217         }
218         case e_root: {
219             int i, j;
220             double low = -1, high = -1, v, low_v = -DBL_MAX, high_v = DBL_MAX;
221             double var0 = p->var[0];
222             double x_max = eval_expr(p, e->param[1]);
223             for(i=-1; i<1024; i++) {
224                 if(i<255) {
225                     p->var[0] = av_reverse[i&255]*x_max/255;
226                 } else {
227                     p->var[0] = x_max*pow(0.9, i-255);
228                     if (i&1) p->var[0] *= -1;
229                     if (i&2) p->var[0] += low;
230                     else     p->var[0] += high;
231                 }
232                 v = eval_expr(p, e->param[0]);
233                 if (v<=0 && v>low_v) {
234                     low    = p->var[0];
235                     low_v  = v;
236                 }
237                 if (v>=0 && v<high_v) {
238                     high   = p->var[0];
239                     high_v = v;
240                 }
241                 if (low>=0 && high>=0){
242                     for (j=0; j<1000; j++) {
243                         p->var[0] = (low+high)*0.5;
244                         if (low == p->var[0] || high == p->var[0])
245                             break;
246                         v = eval_expr(p, e->param[0]);
247                         if (v<=0) low = p->var[0];
248                         if (v>=0) high= p->var[0];
249                         if (isnan(v)) {
250                             low = high = v;
251                             break;
252                         }
253                     }
254                     break;
255                 }
256             }
257             p->var[0] = var0;
258             return -low_v<high_v ? low : high;
259         }
260         default: {
261             double d = eval_expr(p, e->param[0]);
262             double d2 = eval_expr(p, e->param[1]);
263             switch (e->type) {
264                 case e_mod: return e->value * (d - floor((!CONFIG_FTRAPV || d2) ? d / d2 : d * INFINITY) * d2);
265                 case e_gcd: return e->value * av_gcd(d,d2);
266                 case e_max: return e->value * (d >  d2 ?   d : d2);
267                 case e_min: return e->value * (d <  d2 ?   d : d2);
268                 case e_eq:  return e->value * (d == d2 ? 1.0 : 0.0);
269                 case e_gt:  return e->value * (d >  d2 ? 1.0 : 0.0);
270                 case e_gte: return e->value * (d >= d2 ? 1.0 : 0.0);
271                 case e_pow: return e->value * pow(d, d2);
272                 case e_mul: return e->value * (d * d2);
273                 case e_div: return e->value * ((!CONFIG_FTRAPV || d2 ) ? (d / d2) : d * INFINITY);
274                 case e_add: return e->value * (d + d2);
275                 case e_last:return e->value * d2;
276                 case e_st : return e->value * (p->var[av_clip(d, 0, VARS-1)]= d2);
277                 case e_hypot:return e->value * (sqrt(d*d + d2*d2));
278             }
279         }
280     }
281     return NAN;
282 }
283
284 static int parse_expr(AVExpr **e, Parser *p);
285
286 void av_expr_free(AVExpr *e)
287 {
288     if (!e) return;
289     av_expr_free(e->param[0]);
290     av_expr_free(e->param[1]);
291     av_expr_free(e->param[2]);
292     av_freep(&e->var);
293     av_freep(&e);
294 }
295
296 static int parse_primary(AVExpr **e, Parser *p)
297 {
298     AVExpr *d = av_mallocz(sizeof(AVExpr));
299     char *next = p->s, *s0 = p->s;
300     int ret, i;
301
302     if (!d)
303         return AVERROR(ENOMEM);
304
305     /* number */
306     d->value = av_strtod(p->s, &next);
307     if (next != p->s) {
308         d->type = e_value;
309         p->s= next;
310         *e = d;
311         return 0;
312     }
313     d->value = 1;
314
315     /* named constants */
316     for (i=0; p->const_names && p->const_names[i]; i++) {
317         if (strmatch(p->s, p->const_names[i])) {
318             p->s+= strlen(p->const_names[i]);
319             d->type = e_const;
320             d->a.const_index = i;
321             *e = d;
322             return 0;
323         }
324     }
325     for (i = 0; i < FF_ARRAY_ELEMS(constants); i++) {
326         if (strmatch(p->s, constants[i].name)) {
327             p->s += strlen(constants[i].name);
328             d->type = e_value;
329             d->value = constants[i].value;
330             *e = d;
331             return 0;
332         }
333     }
334
335     p->s= strchr(p->s, '(');
336     if (p->s==NULL) {
337         av_log(p, AV_LOG_ERROR, "Undefined constant or missing '(' in '%s'\n", s0);
338         p->s= next;
339         av_expr_free(d);
340         return AVERROR(EINVAL);
341     }
342     p->s++; // "("
343     if (*next == '(') { // special case do-nothing
344         av_freep(&d);
345         if ((ret = parse_expr(&d, p)) < 0)
346             return ret;
347         if (p->s[0] != ')') {
348             av_log(p, AV_LOG_ERROR, "Missing ')' in '%s'\n", s0);
349             av_expr_free(d);
350             return AVERROR(EINVAL);
351         }
352         p->s++; // ")"
353         *e = d;
354         return 0;
355     }
356     if ((ret = parse_expr(&(d->param[0]), p)) < 0) {
357         av_expr_free(d);
358         return ret;
359     }
360     if (p->s[0]== ',') {
361         p->s++; // ","
362         parse_expr(&d->param[1], p);
363     }
364     if (p->s[0]== ',') {
365         p->s++; // ","
366         parse_expr(&d->param[2], p);
367     }
368     if (p->s[0] != ')') {
369         av_log(p, AV_LOG_ERROR, "Missing ')' or too many args in '%s'\n", s0);
370         av_expr_free(d);
371         return AVERROR(EINVAL);
372     }
373     p->s++; // ")"
374
375     d->type = e_func0;
376          if (strmatch(next, "sinh"  )) d->a.func0 = sinh;
377     else if (strmatch(next, "cosh"  )) d->a.func0 = cosh;
378     else if (strmatch(next, "tanh"  )) d->a.func0 = tanh;
379     else if (strmatch(next, "sin"   )) d->a.func0 = sin;
380     else if (strmatch(next, "cos"   )) d->a.func0 = cos;
381     else if (strmatch(next, "tan"   )) d->a.func0 = tan;
382     else if (strmatch(next, "atan"  )) d->a.func0 = atan;
383     else if (strmatch(next, "asin"  )) d->a.func0 = asin;
384     else if (strmatch(next, "acos"  )) d->a.func0 = acos;
385     else if (strmatch(next, "exp"   )) d->a.func0 = exp;
386     else if (strmatch(next, "log"   )) d->a.func0 = log;
387     else if (strmatch(next, "abs"   )) d->a.func0 = fabs;
388     else if (strmatch(next, "time"  )) d->a.func0 = etime;
389     else if (strmatch(next, "squish")) d->type = e_squish;
390     else if (strmatch(next, "gauss" )) d->type = e_gauss;
391     else if (strmatch(next, "mod"   )) d->type = e_mod;
392     else if (strmatch(next, "max"   )) d->type = e_max;
393     else if (strmatch(next, "min"   )) d->type = e_min;
394     else if (strmatch(next, "eq"    )) d->type = e_eq;
395     else if (strmatch(next, "gte"   )) d->type = e_gte;
396     else if (strmatch(next, "gt"    )) d->type = e_gt;
397     else if (strmatch(next, "lte"   )) { AVExpr *tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gte; }
398     else if (strmatch(next, "lt"    )) { AVExpr *tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gt; }
399     else if (strmatch(next, "ld"    )) d->type = e_ld;
400     else if (strmatch(next, "isnan" )) d->type = e_isnan;
401     else if (strmatch(next, "isinf" )) d->type = e_isinf;
402     else if (strmatch(next, "st"    )) d->type = e_st;
403     else if (strmatch(next, "while" )) d->type = e_while;
404     else if (strmatch(next, "taylor")) d->type = e_taylor;
405     else if (strmatch(next, "root"  )) d->type = e_root;
406     else if (strmatch(next, "floor" )) d->type = e_floor;
407     else if (strmatch(next, "ceil"  )) d->type = e_ceil;
408     else if (strmatch(next, "trunc" )) d->type = e_trunc;
409     else if (strmatch(next, "sqrt"  )) d->type = e_sqrt;
410     else if (strmatch(next, "not"   )) d->type = e_not;
411     else if (strmatch(next, "pow"   )) d->type = e_pow;
412     else if (strmatch(next, "random")) d->type = e_random;
413     else if (strmatch(next, "hypot" )) d->type = e_hypot;
414     else if (strmatch(next, "gcd"   )) d->type = e_gcd;
415     else if (strmatch(next, "if"    )) d->type = e_if;
416     else if (strmatch(next, "ifnot" )) d->type = e_ifnot;
417     else {
418         for (i=0; p->func1_names && p->func1_names[i]; i++) {
419             if (strmatch(next, p->func1_names[i])) {
420                 d->a.func1 = p->funcs1[i];
421                 d->type = e_func1;
422                 *e = d;
423                 return 0;
424             }
425         }
426
427         for (i=0; p->func2_names && p->func2_names[i]; i++) {
428             if (strmatch(next, p->func2_names[i])) {
429                 d->a.func2 = p->funcs2[i];
430                 d->type = e_func2;
431                 *e = d;
432                 return 0;
433             }
434         }
435
436         av_log(p, AV_LOG_ERROR, "Unknown function in '%s'\n", s0);
437         av_expr_free(d);
438         return AVERROR(EINVAL);
439     }
440
441     *e = d;
442     return 0;
443 }
444
445 static AVExpr *new_eval_expr(int type, int value, AVExpr *p0, AVExpr *p1)
446 {
447     AVExpr *e = av_mallocz(sizeof(AVExpr));
448     if (!e)
449         return NULL;
450     e->type     =type   ;
451     e->value    =value  ;
452     e->param[0] =p0     ;
453     e->param[1] =p1     ;
454     return e;
455 }
456
457 static int parse_pow(AVExpr **e, Parser *p, int *sign)
458 {
459     *sign= (*p->s == '+') - (*p->s == '-');
460     p->s += *sign&1;
461     return parse_primary(e, p);
462 }
463
464 static int parse_dB(AVExpr **e, Parser *p, int *sign)
465 {
466     /* do not filter out the negative sign when parsing a dB value.
467        for example, -3dB is not the same as -(3dB) */
468     if (*p->s == '-') {
469         char *next;
470         strtod(p->s, &next);
471         if (next != p->s && next[0] == 'd' && next[1] == 'B') {
472             *sign = 0;
473             return parse_primary(e, p);
474         }
475     }
476     return parse_pow(e, p, sign);
477 }
478
479 static int parse_factor(AVExpr **e, Parser *p)
480 {
481     int sign, sign2, ret;
482     AVExpr *e0, *e1, *e2;
483     if ((ret = parse_dB(&e0, p, &sign)) < 0)
484         return ret;
485     while(p->s[0]=='^'){
486         e1 = e0;
487         p->s++;
488         if ((ret = parse_dB(&e2, p, &sign2)) < 0) {
489             av_expr_free(e1);
490             return ret;
491         }
492         e0 = new_eval_expr(e_pow, 1, e1, e2);
493         if (!e0) {
494             av_expr_free(e1);
495             av_expr_free(e2);
496             return AVERROR(ENOMEM);
497         }
498         if (e0->param[1]) e0->param[1]->value *= (sign2|1);
499     }
500     if (e0) e0->value *= (sign|1);
501
502     *e = e0;
503     return 0;
504 }
505
506 static int parse_term(AVExpr **e, Parser *p)
507 {
508     int ret;
509     AVExpr *e0, *e1, *e2;
510     if ((ret = parse_factor(&e0, p)) < 0)
511         return ret;
512     while (p->s[0]=='*' || p->s[0]=='/') {
513         int c= *p->s++;
514         e1 = e0;
515         if ((ret = parse_factor(&e2, p)) < 0) {
516             av_expr_free(e1);
517             return ret;
518         }
519         e0 = new_eval_expr(c == '*' ? e_mul : e_div, 1, e1, e2);
520         if (!e0) {
521             av_expr_free(e1);
522             av_expr_free(e2);
523             return AVERROR(ENOMEM);
524         }
525     }
526     *e = e0;
527     return 0;
528 }
529
530 static int parse_subexpr(AVExpr **e, Parser *p)
531 {
532     int ret;
533     AVExpr *e0, *e1, *e2;
534     if ((ret = parse_term(&e0, p)) < 0)
535         return ret;
536     while (*p->s == '+' || *p->s == '-') {
537         e1 = e0;
538         if ((ret = parse_term(&e2, p)) < 0) {
539             av_expr_free(e1);
540             return ret;
541         }
542         e0 = new_eval_expr(e_add, 1, e1, e2);
543         if (!e0) {
544             av_expr_free(e1);
545             av_expr_free(e2);
546             return AVERROR(ENOMEM);
547         }
548     };
549
550     *e = e0;
551     return 0;
552 }
553
554 static int parse_expr(AVExpr **e, Parser *p)
555 {
556     int ret;
557     AVExpr *e0, *e1, *e2;
558     if (p->stack_index <= 0) //protect against stack overflows
559         return AVERROR(EINVAL);
560     p->stack_index--;
561
562     if ((ret = parse_subexpr(&e0, p)) < 0)
563         return ret;
564     while (*p->s == ';') {
565         p->s++;
566         e1 = e0;
567         if ((ret = parse_subexpr(&e2, p)) < 0) {
568             av_expr_free(e1);
569             return ret;
570         }
571         e0 = new_eval_expr(e_last, 1, e1, e2);
572         if (!e0) {
573             av_expr_free(e1);
574             av_expr_free(e2);
575             return AVERROR(ENOMEM);
576         }
577     };
578
579     p->stack_index++;
580     *e = e0;
581     return 0;
582 }
583
584 static int verify_expr(AVExpr *e)
585 {
586     if (!e) return 0;
587     switch (e->type) {
588         case e_value:
589         case e_const: return 1;
590         case e_func0:
591         case e_func1:
592         case e_squish:
593         case e_ld:
594         case e_gauss:
595         case e_isnan:
596         case e_isinf:
597         case e_floor:
598         case e_ceil:
599         case e_trunc:
600         case e_sqrt:
601         case e_not:
602         case e_random:
603             return verify_expr(e->param[0]) && !e->param[1];
604         case e_if:
605         case e_ifnot:
606         case e_taylor:
607             return verify_expr(e->param[0]) && verify_expr(e->param[1])
608                    && (!e->param[2] || verify_expr(e->param[2]));
609         default: return verify_expr(e->param[0]) && verify_expr(e->param[1]) && !e->param[2];
610     }
611 }
612
613 int av_expr_parse(AVExpr **expr, const char *s,
614                   const char * const *const_names,
615                   const char * const *func1_names, double (* const *funcs1)(void *, double),
616                   const char * const *func2_names, double (* const *funcs2)(void *, double, double),
617                   int log_offset, void *log_ctx)
618 {
619     Parser p = { 0 };
620     AVExpr *e = NULL;
621     char *w = av_malloc(strlen(s) + 1);
622     char *wp = w;
623     const char *s0 = s;
624     int ret = 0;
625
626     if (!w)
627         return AVERROR(ENOMEM);
628
629     while (*s)
630         if (!isspace(*s++)) *wp++ = s[-1];
631     *wp++ = 0;
632
633     p.class      = &class;
634     p.stack_index=100;
635     p.s= w;
636     p.const_names = const_names;
637     p.funcs1      = funcs1;
638     p.func1_names = func1_names;
639     p.funcs2      = funcs2;
640     p.func2_names = func2_names;
641     p.log_offset = log_offset;
642     p.log_ctx    = log_ctx;
643
644     if ((ret = parse_expr(&e, &p)) < 0)
645         goto end;
646     if (*p.s) {
647         av_expr_free(e);
648         av_log(&p, AV_LOG_ERROR, "Invalid chars '%s' at the end of expression '%s'\n", p.s, s0);
649         ret = AVERROR(EINVAL);
650         goto end;
651     }
652     if (!verify_expr(e)) {
653         av_expr_free(e);
654         ret = AVERROR(EINVAL);
655         goto end;
656     }
657     e->var= av_mallocz(sizeof(double) *VARS);
658     *expr = e;
659 end:
660     av_free(w);
661     return ret;
662 }
663
664 double av_expr_eval(AVExpr *e, const double *const_values, void *opaque)
665 {
666     Parser p = { 0 };
667     p.var= e->var;
668
669     p.const_values = const_values;
670     p.opaque     = opaque;
671     return eval_expr(&p, e);
672 }
673
674 int av_expr_parse_and_eval(double *d, const char *s,
675                            const char * const *const_names, const double *const_values,
676                            const char * const *func1_names, double (* const *funcs1)(void *, double),
677                            const char * const *func2_names, double (* const *funcs2)(void *, double, double),
678                            void *opaque, int log_offset, void *log_ctx)
679 {
680     AVExpr *e = NULL;
681     int ret = av_expr_parse(&e, s, const_names, func1_names, funcs1, func2_names, funcs2, log_offset, log_ctx);
682
683     if (ret < 0) {
684         *d = NAN;
685         return ret;
686     }
687     *d = av_expr_eval(e, const_values, opaque);
688     av_expr_free(e);
689     return isnan(*d) ? AVERROR(EINVAL) : 0;
690 }
691
692 #ifdef TEST
693 #include <string.h>
694
695 static const double const_values[] = {
696     M_PI,
697     M_E,
698     0
699 };
700
701 static const char *const const_names[] = {
702     "PI",
703     "E",
704     0
705 };
706
707 int main(int argc, char **argv)
708 {
709     int i;
710     double d;
711     const char *const *expr;
712     static const char *const exprs[] = {
713         "",
714         "1;2",
715         "-20",
716         "-PI",
717         "+PI",
718         "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)",
719         "80G/80Gi",
720         "1k",
721         "1Gi",
722         "1gi",
723         "1GiFoo",
724         "1k+1k",
725         "1Gi*3foo",
726         "foo",
727         "foo(",
728         "foo()",
729         "foo)",
730         "sin",
731         "sin(",
732         "sin()",
733         "sin)",
734         "sin 10",
735         "sin(1,2,3)",
736         "sin(1 )",
737         "1",
738         "1foo",
739         "bar + PI + E + 100f*2 + foo",
740         "13k + 12f - foo(1, 2)",
741         "1gi",
742         "1Gi",
743         "st(0, 123)",
744         "st(1, 123); ld(1)",
745         "lte(0, 1)",
746         "lte(1, 1)",
747         "lte(1, 0)",
748         "lt(0, 1)",
749         "lt(1, 1)",
750         "gt(1, 0)",
751         "gt(2, 7)",
752         "gte(122, 122)",
753         /* compute 1+2+...+N */
754         "st(0, 1); while(lte(ld(0), 100), st(1, ld(1)+ld(0));st(0, ld(0)+1)); ld(1)",
755         /* compute Fib(N) */
756         "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)",
757         "while(0, 10)",
758         "st(0, 1); while(lte(ld(0),100), st(1, ld(1)+ld(0)); st(0, ld(0)+1))",
759         "isnan(1)",
760         "isnan(NAN)",
761         "isnan(INF)",
762         "isinf(1)",
763         "isinf(NAN)",
764         "isinf(INF)",
765         "floor(NAN)",
766         "floor(123.123)",
767         "floor(-123.123)",
768         "trunc(123.123)",
769         "trunc(-123.123)",
770         "ceil(123.123)",
771         "ceil(-123.123)",
772         "sqrt(1764)",
773         "isnan(sqrt(-1))",
774         "not(1)",
775         "not(NAN)",
776         "not(0)",
777         "6.0206dB",
778         "-3.0103dB",
779         "pow(0,1.23)",
780         "pow(PI,1.23)",
781         "PI^1.23",
782         "pow(-1,1.23)",
783         "if(1, 2)",
784         "if(1, 1, 2)",
785         "if(0, 1, 2)",
786         "ifnot(0, 23)",
787         "ifnot(1, NaN) + if(0, 1)",
788         "ifnot(1, 1, 2)",
789         "ifnot(0, 1, 2)",
790         "taylor(1, 1)",
791         "taylor(eq(mod(ld(1),4),1)-eq(mod(ld(1),4),3), PI/2, 1)",
792         "root(sin(ld(0))-1, 2)",
793         "root(sin(ld(0))+6+sin(ld(0)/12)-log(ld(0)), 100)",
794         "7000000B*random(0)",
795         "squish(2)",
796         "gauss(0.1)",
797         "hypot(4,3)",
798         "gcd(30,55)*min(9,1)",
799         NULL
800     };
801
802     for (expr = exprs; *expr; expr++) {
803         printf("Evaluating '%s'\n", *expr);
804         av_expr_parse_and_eval(&d, *expr,
805                                const_names, const_values,
806                                NULL, NULL, NULL, NULL, NULL, 0, NULL);
807         if (isnan(d))
808             printf("'%s' -> nan\n\n", *expr);
809         else
810             printf("'%s' -> %f\n\n", *expr, d);
811     }
812
813     av_expr_parse_and_eval(&d, "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)",
814                            const_names, const_values,
815                            NULL, NULL, NULL, NULL, NULL, 0, NULL);
816     printf("%f == 12.7\n", d);
817     av_expr_parse_and_eval(&d, "80G/80Gi",
818                            const_names, const_values,
819                            NULL, NULL, NULL, NULL, NULL, 0, NULL);
820     printf("%f == 0.931322575\n", d);
821
822     if (argc > 1 && !strcmp(argv[1], "-t")) {
823         for (i = 0; i < 1050; i++) {
824             START_TIMER;
825             av_expr_parse_and_eval(&d, "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)",
826                                    const_names, const_values,
827                                    NULL, NULL, NULL, NULL, NULL, 0, NULL);
828             STOP_TIMER("av_expr_parse_and_eval");
829         }
830     }
831
832     return 0;
833 }
834 #endif