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