]> rtime.felk.cvut.cz Git - frescor/ffmpeg.git/blob - libavcodec/eval.c
update copyright year, it looks odd otherwise :)
[frescor/ffmpeg.git] / libavcodec / eval.c
1 /*
2  * simple arithmetic expression evaluator
3  *
4  * Copyright (c) 2002-2006 Michael Niedermayer <michaelni@gmx.at>
5  * Copyright (c) 2006 Oded Shimon <ods15@ods15.dyndns.org>
6  *
7  * This file is part of FFmpeg.
8  *
9  * FFmpeg is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * FFmpeg is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with FFmpeg; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  *
23  */
24
25 /**
26  * @file eval.c
27  * simple arithmetic expression evaluator.
28  *
29  * see http://joe.hotchkiss.com/programming/eval/eval.html
30  */
31
32 #include "avcodec.h"
33 #include "mpegvideo.h"
34 #include "eval.h"
35
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <math.h>
40
41 #ifndef NAN
42   #define NAN 0.0/0.0
43 #endif
44
45 #ifndef M_PI
46 #define M_PI 3.14159265358979323846
47 #endif
48
49 typedef struct Parser{
50     int stack_index;
51     char *s;
52     double *const_value;
53     const char **const_name;          // NULL terminated
54     double (**func1)(void *, double a); // NULL terminated
55     const char **func1_name;          // NULL terminated
56     double (**func2)(void *, double a, double b); // NULL terminated
57     char **func2_name;          // NULL terminated
58     void *opaque;
59     char **error;
60 #define VARS 10
61     double var[VARS];
62 } Parser;
63
64 static int8_t si_prefixes['z' - 'E' + 1]={
65     ['y'-'E']= -24,
66     ['z'-'E']= -21,
67     ['a'-'E']= -18,
68     ['f'-'E']= -15,
69     ['p'-'E']= -12,
70     ['n'-'E']= - 9,
71     ['u'-'E']= - 6,
72     ['m'-'E']= - 3,
73     ['c'-'E']= - 2,
74     ['d'-'E']= - 1,
75     ['h'-'E']=   2,
76     ['k'-'E']=   3,
77     ['K'-'E']=   3,
78     ['M'-'E']=   6,
79     ['G'-'E']=   9,
80     ['T'-'E']=  12,
81     ['P'-'E']=  15,
82     ['E'-'E']=  18,
83     ['Z'-'E']=  21,
84     ['Y'-'E']=  24,
85 };
86
87 /** strtod() function extended with 'k', 'M', 'G', 'ki', 'Mi', 'Gi' and 'B'
88  * postfixes.  This allows using f.e. kB, MiB, G and B as a postfix. This
89  * function assumes that the unit of numbers is bits not bytes.
90  */
91 static double av_strtod(const char *name, char **tail) {
92     double d;
93     char *next;
94     d = strtod(name, &next);
95     /* if parsing succeeded, check for and interpret postfixes */
96     if (next!=name) {
97
98         if(*next >= 'E' && *next <= 'z'){
99             int e= si_prefixes[*next - 'E'];
100             if(e){
101                 if(next[1] == 'i'){
102                     d*= pow( 2, e/0.3);
103                     next+=2;
104                 }else{
105                     d*= pow(10, e);
106                     next++;
107                 }
108             }
109         }
110
111         if(*next=='B') {
112             d*=8;
113             *next++;
114         }
115     }
116     /* if requested, fill in tail with the position after the last parsed
117        character */
118     if (tail)
119         *tail = next;
120     return d;
121 }
122
123 static int strmatch(const char *s, const char *prefix){
124     int i;
125     for(i=0; prefix[i]; i++){
126         if(prefix[i] != s[i]) return 0;
127     }
128     return 1;
129 }
130
131 struct ff_expr_s {
132     enum {
133         e_value, e_const, e_func0, e_func1, e_func2,
134         e_squish, e_gauss, e_ld,
135         e_mod, e_max, e_min, e_eq, e_gt, e_gte,
136         e_pow, e_mul, e_div, e_add,
137         e_last, e_st, e_while,
138     } type;
139     double value; // is sign in other types
140     union {
141         int const_index;
142         double (*func0)(double);
143         double (*func1)(void *, double);
144         double (*func2)(void *, double, double);
145     } a;
146     AVEvalExpr * param[2];
147 };
148
149 static double eval_expr(Parser * p, AVEvalExpr * e) {
150     switch (e->type) {
151         case e_value:  return e->value;
152         case e_const:  return e->value * p->const_value[e->a.const_index];
153         case e_func0:  return e->value * e->a.func0(eval_expr(p, e->param[0]));
154         case e_func1:  return e->value * e->a.func1(p->opaque, eval_expr(p, e->param[0]));
155         case e_func2:  return e->value * e->a.func2(p->opaque, eval_expr(p, e->param[0]), eval_expr(p, e->param[1]));
156         case e_squish: return 1/(1+exp(4*eval_expr(p, e->param[0])));
157         case e_gauss: { double d = eval_expr(p, e->param[0]); return exp(-d*d/2)/sqrt(2*M_PI); }
158         case e_ld:     return e->value * p->var[clip(eval_expr(p, e->param[0]), 0, VARS-1)];
159         case e_while: {
160             double d = NAN;
161             while(eval_expr(p, e->param[0]))
162                 d=eval_expr(p, e->param[1]);
163             return d;
164         }
165         default: {
166             double d = eval_expr(p, e->param[0]);
167             double d2 = eval_expr(p, e->param[1]);
168             switch (e->type) {
169                 case e_mod: return e->value * (d - floor(d/d2)*d2);
170                 case e_max: return e->value * (d >  d2 ?   d : d2);
171                 case e_min: return e->value * (d <  d2 ?   d : d2);
172                 case e_eq:  return e->value * (d == d2 ? 1.0 : 0.0);
173                 case e_gt:  return e->value * (d >  d2 ? 1.0 : 0.0);
174                 case e_gte: return e->value * (d >= d2 ? 1.0 : 0.0);
175                 case e_pow: return e->value * pow(d, d2);
176                 case e_mul: return e->value * (d * d2);
177                 case e_div: return e->value * (d / d2);
178                 case e_add: return e->value * (d + d2);
179                 case e_last:return e->value * d2;
180                 case e_st : return e->value * (p->var[clip(d, 0, VARS-1)]= d2);
181             }
182         }
183     }
184     return NAN;
185 }
186
187 static AVEvalExpr * parse_expr(Parser *p);
188
189 void ff_eval_free(AVEvalExpr * e) {
190     if (!e) return;
191     ff_eval_free(e->param[0]);
192     ff_eval_free(e->param[1]);
193     av_freep(&e);
194 }
195
196 static AVEvalExpr * parse_primary(Parser *p) {
197     AVEvalExpr * d = av_mallocz(sizeof(AVEvalExpr));
198     char *next= p->s;
199     int i;
200
201     /* number */
202     d->value = av_strtod(p->s, &next);
203     if(next != p->s){
204         d->type = e_value;
205         p->s= next;
206         return d;
207     }
208     d->value = 1;
209
210     /* named constants */
211     for(i=0; p->const_name && p->const_name[i]; i++){
212         if(strmatch(p->s, p->const_name[i])){
213             p->s+= strlen(p->const_name[i]);
214             d->type = e_const;
215             d->a.const_index = i;
216             return d;
217         }
218     }
219
220     p->s= strchr(p->s, '(');
221     if(p->s==NULL){
222         *p->error = "missing (";
223         p->s= next;
224         ff_eval_free(d);
225         return NULL;
226     }
227     p->s++; // "("
228     if (*next == '(') { // special case do-nothing
229         av_freep(&d);
230         d = parse_expr(p);
231         if(p->s[0] != ')'){
232             *p->error = "missing )";
233             ff_eval_free(d);
234             return NULL;
235         }
236         p->s++; // ")"
237         return d;
238     }
239     d->param[0] = parse_expr(p);
240     if(p->s[0]== ','){
241         p->s++; // ","
242         d->param[1] = parse_expr(p);
243     }
244     if(p->s[0] != ')'){
245         *p->error = "missing )";
246         ff_eval_free(d);
247         return NULL;
248     }
249     p->s++; // ")"
250
251     d->type = e_func0;
252          if( strmatch(next, "sinh"  ) ) d->a.func0 = sinh;
253     else if( strmatch(next, "cosh"  ) ) d->a.func0 = cosh;
254     else if( strmatch(next, "tanh"  ) ) d->a.func0 = tanh;
255     else if( strmatch(next, "sin"   ) ) d->a.func0 = sin;
256     else if( strmatch(next, "cos"   ) ) d->a.func0 = cos;
257     else if( strmatch(next, "tan"   ) ) d->a.func0 = tan;
258     else if( strmatch(next, "atan"  ) ) d->a.func0 = atan;
259     else if( strmatch(next, "asin"  ) ) d->a.func0 = asin;
260     else if( strmatch(next, "acos"  ) ) d->a.func0 = acos;
261     else if( strmatch(next, "exp"   ) ) d->a.func0 = exp;
262     else if( strmatch(next, "log"   ) ) d->a.func0 = log;
263     else if( strmatch(next, "abs"   ) ) d->a.func0 = fabs;
264     else if( strmatch(next, "squish") ) d->type = e_squish;
265     else if( strmatch(next, "gauss" ) ) d->type = e_gauss;
266     else if( strmatch(next, "mod"   ) ) d->type = e_mod;
267     else if( strmatch(next, "max"   ) ) d->type = e_max;
268     else if( strmatch(next, "min"   ) ) d->type = e_min;
269     else if( strmatch(next, "eq"    ) ) d->type = e_eq;
270     else if( strmatch(next, "gte"   ) ) d->type = e_gte;
271     else if( strmatch(next, "gt"    ) ) d->type = e_gt;
272     else if( strmatch(next, "lte"   ) ) { AVEvalExpr * tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gt; }
273     else if( strmatch(next, "lt"    ) ) { AVEvalExpr * tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gte; }
274     else if( strmatch(next, "ld"    ) ) d->type = e_ld;
275     else if( strmatch(next, "st"    ) ) d->type = e_st;
276     else if( strmatch(next, "while" ) ) d->type = e_while;
277     else {
278         for(i=0; p->func1_name && p->func1_name[i]; i++){
279             if(strmatch(next, p->func1_name[i])){
280                 d->a.func1 = p->func1[i];
281                 d->type = e_func1;
282                 return d;
283             }
284         }
285
286         for(i=0; p->func2_name && p->func2_name[i]; i++){
287             if(strmatch(next, p->func2_name[i])){
288                 d->a.func2 = p->func2[i];
289                 d->type = e_func2;
290                 return d;
291             }
292         }
293
294         *p->error = "unknown function";
295         ff_eval_free(d);
296         return NULL;
297     }
298
299     return d;
300 }
301
302 static AVEvalExpr * new_eval_expr(int type, int value, AVEvalExpr *p0, AVEvalExpr *p1){
303     AVEvalExpr * e = av_mallocz(sizeof(AVEvalExpr));
304     e->type     =type   ;
305     e->value    =value  ;
306     e->param[0] =p0     ;
307     e->param[1] =p1     ;
308     return e;
309 }
310
311 static AVEvalExpr * parse_pow(Parser *p, int *sign){
312     *sign= (*p->s == '+') - (*p->s == '-');
313     p->s += *sign&1;
314     return parse_primary(p);
315 }
316
317 static AVEvalExpr * parse_factor(Parser *p){
318     int sign, sign2;
319     AVEvalExpr * e = parse_pow(p, &sign);
320     while(p->s[0]=='^'){
321         p->s++;
322         e= new_eval_expr(e_pow, 1, e, parse_pow(p, &sign2));
323         if (e->param[1]) e->param[1]->value *= (sign2|1);
324     }
325     if (e) e->value *= (sign|1);
326     return e;
327 }
328
329 static AVEvalExpr * parse_term(Parser *p){
330     AVEvalExpr * e = parse_factor(p);
331     while(p->s[0]=='*' || p->s[0]=='/'){
332         int c= *p->s++;
333         e= new_eval_expr(c == '*' ? e_mul : e_div, 1, e, parse_factor(p));
334     }
335     return e;
336 }
337
338 static AVEvalExpr * parse_subexpr(Parser *p) {
339     AVEvalExpr * e = parse_term(p);
340     while(*p->s == '+' || *p->s == '-') {
341         e= new_eval_expr(e_add, 1, e, parse_term(p));
342     };
343
344     return e;
345 }
346
347 static AVEvalExpr * parse_expr(Parser *p) {
348     AVEvalExpr * e;
349
350     if(p->stack_index <= 0) //protect against stack overflows
351         return NULL;
352     p->stack_index--;
353
354     e = parse_subexpr(p);
355
356     while(*p->s == ';') {
357         p->s++;
358         e= new_eval_expr(e_last, 1, e, parse_subexpr(p));
359     };
360
361     p->stack_index++;
362
363     return e;
364 }
365
366 static int verify_expr(AVEvalExpr * e) {
367     if (!e) return 0;
368     switch (e->type) {
369         case e_value:
370         case e_const: return 1;
371         case e_func0:
372         case e_func1:
373         case e_squish:
374         case e_ld:
375         case e_gauss: return verify_expr(e->param[0]);
376         default: return verify_expr(e->param[0]) && verify_expr(e->param[1]);
377     }
378 }
379
380 AVEvalExpr * ff_parse(char *s, const char **const_name,
381                double (**func1)(void *, double), const char **func1_name,
382                double (**func2)(void *, double, double), char **func2_name,
383                char **error){
384     Parser p;
385     AVEvalExpr * e;
386     char w[strlen(s) + 1], * wp = w;
387
388     while (*s)
389         if (!isspace(*s++)) *wp++ = s[-1];
390     *wp++ = 0;
391
392     p.stack_index=100;
393     p.s= w;
394     p.const_name = const_name;
395     p.func1      = func1;
396     p.func1_name = func1_name;
397     p.func2      = func2;
398     p.func2_name = func2_name;
399     p.error= error;
400
401     e = parse_expr(&p);
402     if (!verify_expr(e)) {
403         ff_eval_free(e);
404         return NULL;
405     }
406     return e;
407 }
408
409 double ff_parse_eval(AVEvalExpr * e, double *const_value, void *opaque) {
410     Parser p;
411
412     p.const_value= const_value;
413     p.opaque     = opaque;
414     return eval_expr(&p, e);
415 }
416
417 double ff_eval2(char *s, double *const_value, const char **const_name,
418                double (**func1)(void *, double), const char **func1_name,
419                double (**func2)(void *, double, double), char **func2_name,
420                void *opaque, char **error){
421     AVEvalExpr * e = ff_parse(s, const_name, func1, func1_name, func2, func2_name, error);
422     double d;
423     if (!e) return NAN;
424     d = ff_parse_eval(e, const_value, opaque);
425     ff_eval_free(e);
426     return d;
427 }
428
429 #if LIBAVCODEC_VERSION_INT < ((52<<16)+(0<<8)+0)
430 attribute_deprecated double ff_eval(char *s, double *const_value, const char **const_name,
431                double (**func1)(void *, double), const char **func1_name,
432                double (**func2)(void *, double, double), char **func2_name,
433                void *opaque){
434     char *error=NULL;
435     double ret;
436     ret = ff_eval2(s, const_value, const_name, func1, func1_name, func2, func2_name, opaque, &error);
437     if (error)
438         av_log(NULL, AV_LOG_ERROR, "Error evaluating \"%s\": %s\n", s, error);
439     return ret;
440 }
441 #endif
442
443 #ifdef TEST
444 #undef printf
445 static double const_values[]={
446     M_PI,
447     M_E,
448     0
449 };
450 static const char *const_names[]={
451     "PI",
452     "E",
453     0
454 };
455 main(){
456     int i;
457     printf("%f == 12.7\n", ff_eval("1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)", const_values, const_names, NULL, NULL, NULL, NULL, NULL));
458     printf("%f == 0.931322575\n", ff_eval("80G/80Gi", const_values, const_names, NULL, NULL, NULL, NULL, NULL));
459
460     for(i=0; i<1050; i++){
461         START_TIMER
462             ff_eval("1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)", const_values, const_names, NULL, NULL, NULL, NULL, NULL);
463         STOP_TIMER("ff_eval")
464     }
465 }
466 #endif