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