Make ff_parse_expr() and ff_parse_and_eval_expr() return an int
[libav.git] / libavcodec / eval.c
1 /*
2 * Copyright (c) 2002-2006 Michael Niedermayer <michaelni@gmx.at>
3 * Copyright (c) 2006 Oded Shimon <ods15@ods15.dyndns.org>
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 /**
23 * @file
24 * simple arithmetic expression evaluator.
25 *
26 * see http://joe.hotchkiss.com/programming/eval/eval.html
27 */
28
29 #include "libavutil/avutil.h"
30 #include "eval.h"
31
32 typedef struct Parser{
33 const AVClass *class;
34 int stack_index;
35 char *s;
36 const double *const_value;
37 const char * const *const_name; // NULL terminated
38 double (* const *func1)(void *, double a); // NULL terminated
39 const char * const *func1_name; // NULL terminated
40 double (* const *func2)(void *, double a, double b); // NULL terminated
41 const char * const *func2_name; // 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 double d;
76 char *next;
77 d = strtod(numstr, &next);
78 /* if parsing succeeded, check for and interpret postfixes */
79 if (next!=numstr) {
80
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 static int strmatch(const char *s, const char *prefix){
107 int i;
108 for(i=0; prefix[i]; i++){
109 if(prefix[i] != s[i]) return 0;
110 }
111 return 1;
112 }
113
114 struct AVExpr {
115 enum {
116 e_value, e_const, e_func0, e_func1, e_func2,
117 e_squish, e_gauss, e_ld,
118 e_mod, e_max, e_min, e_eq, e_gt, e_gte,
119 e_pow, e_mul, e_div, e_add,
120 e_last, e_st, e_while,
121 } type;
122 double value; // is sign in other types
123 union {
124 int const_index;
125 double (*func0)(double);
126 double (*func1)(void *, double);
127 double (*func2)(void *, double, double);
128 } a;
129 struct AVExpr *param[2];
130 };
131
132 static double eval_expr(Parser * p, AVExpr * e) {
133 switch (e->type) {
134 case e_value: return e->value;
135 case e_const: return e->value * p->const_value[e->a.const_index];
136 case e_func0: return e->value * e->a.func0(eval_expr(p, e->param[0]));
137 case e_func1: return e->value * e->a.func1(p->opaque, eval_expr(p, e->param[0]));
138 case e_func2: return e->value * e->a.func2(p->opaque, eval_expr(p, e->param[0]), eval_expr(p, e->param[1]));
139 case e_squish: return 1/(1+exp(4*eval_expr(p, e->param[0])));
140 case e_gauss: { double d = eval_expr(p, e->param[0]); return exp(-d*d/2)/sqrt(2*M_PI); }
141 case e_ld: return e->value * p->var[av_clip(eval_expr(p, e->param[0]), 0, VARS-1)];
142 case e_while: {
143 double d = NAN;
144 while(eval_expr(p, e->param[0]))
145 d=eval_expr(p, e->param[1]);
146 return d;
147 }
148 default: {
149 double d = eval_expr(p, e->param[0]);
150 double d2 = eval_expr(p, e->param[1]);
151 switch (e->type) {
152 case e_mod: return e->value * (d - floor(d/d2)*d2);
153 case e_max: return e->value * (d > d2 ? d : d2);
154 case e_min: return e->value * (d < d2 ? d : d2);
155 case e_eq: return e->value * (d == d2 ? 1.0 : 0.0);
156 case e_gt: return e->value * (d > d2 ? 1.0 : 0.0);
157 case e_gte: return e->value * (d >= d2 ? 1.0 : 0.0);
158 case e_pow: return e->value * pow(d, d2);
159 case e_mul: return e->value * (d * d2);
160 case e_div: return e->value * (d / d2);
161 case e_add: return e->value * (d + d2);
162 case e_last:return e->value * d2;
163 case e_st : return e->value * (p->var[av_clip(d, 0, VARS-1)]= d2);
164 }
165 }
166 }
167 return NAN;
168 }
169
170 static int parse_expr(AVExpr **e, Parser *p);
171
172 void ff_free_expr(AVExpr * e) {
173 if (!e) return;
174 ff_free_expr(e->param[0]);
175 ff_free_expr(e->param[1]);
176 av_freep(&e);
177 }
178
179 static int parse_primary(AVExpr **e, Parser *p)
180 {
181 AVExpr * d = av_mallocz(sizeof(AVExpr));
182 char *next= p->s;
183 int ret, i;
184
185 if (!d)
186 return AVERROR(ENOMEM);
187
188 /* number */
189 d->value = av_strtod(p->s, &next);
190 if(next != p->s){
191 d->type = e_value;
192 p->s= next;
193 *e = d;
194 return 0;
195 }
196 d->value = 1;
197
198 /* named constants */
199 for(i=0; p->const_name && p->const_name[i]; i++){
200 if(strmatch(p->s, p->const_name[i])){
201 p->s+= strlen(p->const_name[i]);
202 d->type = e_const;
203 d->a.const_index = i;
204 *e = d;
205 return 0;
206 }
207 }
208
209 p->s= strchr(p->s, '(');
210 if(p->s==NULL){
211 av_log(p, AV_LOG_ERROR, "undefined constant or missing (\n");
212 p->s= next;
213 ff_free_expr(d);
214 return AVERROR(EINVAL);
215 }
216 p->s++; // "("
217 if (*next == '(') { // special case do-nothing
218 av_freep(&d);
219 if ((ret = parse_expr(&d, p)) < 0)
220 return ret;
221 if(p->s[0] != ')'){
222 av_log(p, AV_LOG_ERROR, "missing )\n");
223 ff_free_expr(d);
224 return AVERROR(EINVAL);
225 }
226 p->s++; // ")"
227 *e = d;
228 return 0;
229 }
230 if ((ret = parse_expr(&(d->param[0]), p)) < 0) {
231 ff_free_expr(d);
232 return ret;
233 }
234 if(p->s[0]== ','){
235 p->s++; // ","
236 parse_expr(&d->param[1], p);
237 }
238 if(p->s[0] != ')'){
239 av_log(p, AV_LOG_ERROR, "missing )\n");
240 ff_free_expr(d);
241 return AVERROR(EINVAL);
242 }
243 p->s++; // ")"
244
245 d->type = e_func0;
246 if( strmatch(next, "sinh" ) ) d->a.func0 = sinh;
247 else if( strmatch(next, "cosh" ) ) d->a.func0 = cosh;
248 else if( strmatch(next, "tanh" ) ) d->a.func0 = tanh;
249 else if( strmatch(next, "sin" ) ) d->a.func0 = sin;
250 else if( strmatch(next, "cos" ) ) d->a.func0 = cos;
251 else if( strmatch(next, "tan" ) ) d->a.func0 = tan;
252 else if( strmatch(next, "atan" ) ) d->a.func0 = atan;
253 else if( strmatch(next, "asin" ) ) d->a.func0 = asin;
254 else if( strmatch(next, "acos" ) ) d->a.func0 = acos;
255 else if( strmatch(next, "exp" ) ) d->a.func0 = exp;
256 else if( strmatch(next, "log" ) ) d->a.func0 = log;
257 else if( strmatch(next, "abs" ) ) d->a.func0 = fabs;
258 else if( strmatch(next, "squish") ) d->type = e_squish;
259 else if( strmatch(next, "gauss" ) ) d->type = e_gauss;
260 else if( strmatch(next, "mod" ) ) d->type = e_mod;
261 else if( strmatch(next, "max" ) ) d->type = e_max;
262 else if( strmatch(next, "min" ) ) d->type = e_min;
263 else if( strmatch(next, "eq" ) ) d->type = e_eq;
264 else if( strmatch(next, "gte" ) ) d->type = e_gte;
265 else if( strmatch(next, "gt" ) ) d->type = e_gt;
266 else if( strmatch(next, "lte" ) ) { AVExpr * tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gt; }
267 else if( strmatch(next, "lt" ) ) { AVExpr * tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gte; }
268 else if( strmatch(next, "ld" ) ) d->type = e_ld;
269 else if( strmatch(next, "st" ) ) d->type = e_st;
270 else if( strmatch(next, "while" ) ) d->type = e_while;
271 else {
272 for(i=0; p->func1_name && p->func1_name[i]; i++){
273 if(strmatch(next, p->func1_name[i])){
274 d->a.func1 = p->func1[i];
275 d->type = e_func1;
276 *e = d;
277 return 0;
278 }
279 }
280
281 for(i=0; p->func2_name && p->func2_name[i]; i++){
282 if(strmatch(next, p->func2_name[i])){
283 d->a.func2 = p->func2[i];
284 d->type = e_func2;
285 *e = d;
286 return 0;
287 }
288 }
289
290 av_log(p, AV_LOG_ERROR, "unknown function\n");
291 ff_free_expr(d);
292 return AVERROR(EINVAL);
293 }
294
295 *e = d;
296 return 0;
297 }
298
299 static AVExpr * new_eval_expr(int type, int value, AVExpr *p0, AVExpr *p1){
300 AVExpr * e = av_mallocz(sizeof(AVExpr));
301 if (!e)
302 return NULL;
303 e->type =type ;
304 e->value =value ;
305 e->param[0] =p0 ;
306 e->param[1] =p1 ;
307 return e;
308 }
309
310 static int parse_pow(AVExpr **e, Parser *p, int *sign)
311 {
312 *sign= (*p->s == '+') - (*p->s == '-');
313 p->s += *sign&1;
314 return parse_primary(e, p);
315 }
316
317 static int parse_factor(AVExpr **e, Parser *p)
318 {
319 int sign, sign2, ret;
320 AVExpr *e0, *e1, *e2;
321 if ((ret = parse_pow(&e0, p, &sign)) < 0)
322 return ret;
323 while(p->s[0]=='^'){
324 e1 = e0;
325 p->s++;
326 if ((ret = parse_pow(&e2, p, &sign2)) < 0) {
327 ff_free_expr(e1);
328 return ret;
329 }
330 e0 = new_eval_expr(e_pow, 1, e1, e2);
331 if (!e0) {
332 ff_free_expr(e1);
333 ff_free_expr(e2);
334 return AVERROR(ENOMEM);
335 }
336 if (e0->param[1]) e0->param[1]->value *= (sign2|1);
337 }
338 if (e0) e0->value *= (sign|1);
339
340 *e = e0;
341 return 0;
342 }
343
344 static int parse_term(AVExpr **e, Parser *p)
345 {
346 int ret;
347 AVExpr *e0, *e1, *e2;
348 if ((ret = parse_factor(&e0, p)) < 0)
349 return ret;
350 while(p->s[0]=='*' || p->s[0]=='/'){
351 int c= *p->s++;
352 e1 = e0;
353 if ((ret = parse_factor(&e2, p)) < 0) {
354 ff_free_expr(e1);
355 return ret;
356 }
357 e0 = new_eval_expr(c == '*' ? e_mul : e_div, 1, e1, e2);
358 if (!e0) {
359 ff_free_expr(e1);
360 ff_free_expr(e2);
361 return AVERROR(ENOMEM);
362 }
363 }
364 *e = e0;
365 return 0;
366 }
367
368 static int parse_subexpr(AVExpr **e, Parser *p)
369 {
370 int ret;
371 AVExpr *e0, *e1, *e2;
372 if ((ret = parse_term(&e0, p)) < 0)
373 return ret;
374 while(*p->s == '+' || *p->s == '-') {
375 e1 = e0;
376 if ((ret = parse_term(&e2, p)) < 0) {
377 ff_free_expr(e1);
378 return ret;
379 }
380 e0 = new_eval_expr(e_add, 1, e1, e2);
381 if (!e0) {
382 ff_free_expr(e1);
383 ff_free_expr(e2);
384 return AVERROR(ENOMEM);
385 }
386 };
387
388 *e = e0;
389 return 0;
390 }
391
392 static int parse_expr(AVExpr **e, Parser *p)
393 {
394 int ret;
395 AVExpr *e0, *e1, *e2;
396 if(p->stack_index <= 0) //protect against stack overflows
397 return AVERROR(EINVAL);
398 p->stack_index--;
399
400 if ((ret = parse_subexpr(&e0, p)) < 0)
401 return ret;
402 while(*p->s == ';') {
403 e1 = e0;
404 if ((ret = parse_subexpr(&e2, p)) < 0) {
405 ff_free_expr(e1);
406 return ret;
407 }
408 p->s++;
409 e0 = new_eval_expr(e_last, 1, e1, e2);
410 if (!e0) {
411 ff_free_expr(e1);
412 ff_free_expr(e2);
413 return AVERROR(ENOMEM);
414 }
415 };
416
417 p->stack_index++;
418 *e = e0;
419 return 0;
420 }
421
422 static int verify_expr(AVExpr * e) {
423 if (!e) return 0;
424 switch (e->type) {
425 case e_value:
426 case e_const: return 1;
427 case e_func0:
428 case e_func1:
429 case e_squish:
430 case e_ld:
431 case e_gauss: return verify_expr(e->param[0]);
432 default: return verify_expr(e->param[0]) && verify_expr(e->param[1]);
433 }
434 }
435
436 int ff_parse_expr(AVExpr **expr, const char *s,
437 const char * const *const_name,
438 const char * const *func1_name, double (* const *func1)(void *, double),
439 const char * const *func2_name, double (* const *func2)(void *, double, double),
440 int log_offset, void *log_ctx)
441 {
442 Parser p;
443 AVExpr *e = NULL;
444 char *w = av_malloc(strlen(s) + 1);
445 char *wp = w;
446 int ret = 0;
447
448 if (!w)
449 return AVERROR(ENOMEM);
450
451 while (*s)
452 if (!isspace(*s++)) *wp++ = s[-1];
453 *wp++ = 0;
454
455 p.class = &class;
456 p.stack_index=100;
457 p.s= w;
458 p.const_name = const_name;
459 p.func1 = func1;
460 p.func1_name = func1_name;
461 p.func2 = func2;
462 p.func2_name = func2_name;
463 p.log_offset = log_offset;
464 p.log_ctx = log_ctx;
465
466 if ((ret = parse_expr(&e, &p)) < 0)
467 goto end;
468 if (!verify_expr(e)) {
469 ff_free_expr(e);
470 ret = AVERROR(EINVAL);
471 goto end;
472 }
473 *expr = e;
474 end:
475 av_free(w);
476 return ret;
477 }
478
479 double ff_eval_expr(AVExpr * e, const double *const_value, void *opaque) {
480 Parser p;
481
482 p.const_value= const_value;
483 p.opaque = opaque;
484 return eval_expr(&p, e);
485 }
486
487 int ff_parse_and_eval_expr(double *d, const char *s,
488 const char * const *const_name, const double *const_value,
489 const char * const *func1_name, double (* const *func1)(void *, double),
490 const char * const *func2_name, double (* const *func2)(void *, double, double),
491 void *opaque, int log_offset, void *log_ctx)
492 {
493 AVExpr *e = NULL;
494 int ret = ff_parse_expr(&e, s, const_name, func1_name, func1, func2_name, func2, log_offset, log_ctx);
495
496 if (ret < 0) {
497 *d = NAN;
498 return ret;
499 }
500 *d = ff_eval_expr(e, const_value, opaque);
501 ff_free_expr(e);
502 return isnan(*d) ? AVERROR(EINVAL) : 0;
503 }
504
505 #ifdef TEST
506 #undef printf
507 static double const_values[]={
508 M_PI,
509 M_E,
510 0
511 };
512 static const char *const_names[]={
513 "PI",
514 "E",
515 0
516 };
517 int main(void){
518 int i;
519 double d;
520 ff_parse_and_eval_expr(&d, "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)", const_names, const_values, NULL, NULL, NULL, NULL, NULL, 0, NULL);
521 printf("%f == 12.7\n", d);
522 ff_parse_and_eval_expr(&d, "80G/80Gi", const_names, const_values, NULL, NULL, NULL, NULL, NULL, NULL);
523 printf("%f == 0.931322575\n", d);
524
525 for(i=0; i<1050; i++){
526 START_TIMER
527 ff_parse_and_eval_expr(&d, "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)", const_names, const_values, NULL, NULL, NULL, NULL, NULL, 0, NULL);
528 STOP_TIMER("ff_parse_and_eval_expr")
529 }
530 return 0;
531 }
532 #endif