Statistics
| Branch: | Revision:

ffmpeg / libavcodec / eval.c @ 0345f36b

History | View | Annotate | Download (13.2 KB)

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