Statistics
| Branch: | Revision:

ffmpeg / libavcodec / eval.c @ e877eaac

History | View | Annotate | Download (13.2 KB)

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
 * @file libavcodec/eval.c
26
 * simple arithmetic expression evaluator.
27
 *
28
 * see http://joe.hotchkiss.com/programming/eval/eval.html
29
 */
30

    
31
#include "avcodec.h"
32
#include "eval.h"
33

    
34
#include <stdio.h>
35
#include <stdlib.h>
36
#include <string.h>
37
#include <math.h>
38

    
39
#ifndef NAN
40
  #define NAN 0.0/0.0
41
#endif
42

    
43
#ifndef M_PI
44
#define M_PI 3.14159265358979323846
45
#endif
46

    
47
typedef struct Parser{
48
    int stack_index;
49
    char *s;
50
    const double *const_value;
51
    const char * const *const_name;          // NULL terminated
52
    double (**func1)(void *, double a); // NULL terminated
53
    const char **func1_name;          // NULL terminated
54
    double (**func2)(void *, double a, double b); // NULL terminated
55
    const char **func2_name;          // NULL terminated
56
    void *opaque;
57
    const char **error;
58
#define VARS 10
59
    double var[VARS];
60
} Parser;
61

    
62
static const int8_t si_prefixes['z' - 'E' + 1]={
63
    ['y'-'E']= -24,
64
    ['z'-'E']= -21,
65
    ['a'-'E']= -18,
66
    ['f'-'E']= -15,
67
    ['p'-'E']= -12,
68
    ['n'-'E']= - 9,
69
    ['u'-'E']= - 6,
70
    ['m'-'E']= - 3,
71
    ['c'-'E']= - 2,
72
    ['d'-'E']= - 1,
73
    ['h'-'E']=   2,
74
    ['k'-'E']=   3,
75
    ['K'-'E']=   3,
76
    ['M'-'E']=   6,
77
    ['G'-'E']=   9,
78
    ['T'-'E']=  12,
79
    ['P'-'E']=  15,
80
    ['E'-'E']=  18,
81
    ['Z'-'E']=  21,
82
    ['Y'-'E']=  24,
83
};
84

    
85
/** strtod() function extended with 'k', 'M', 'G', 'ki', 'Mi', 'Gi' and 'B'
86
 * postfixes.  This allows using f.e. kB, MiB, G and B as a postfix. This
87
 * function assumes that the unit of numbers is bits not bytes.
88
 */
89
static double av_strtod(const char *numstr, char **tail) {
90
    double d;
91
    char *next;
92
    d = strtod(numstr, &next);
93
    /* if parsing succeeded, check for and interpret postfixes */
94
    if (next!=numstr) {
95

    
96
        if(*next >= 'E' && *next <= 'z'){
97
            int e= si_prefixes[*next - 'E'];
98
            if(e){
99
                if(next[1] == 'i'){
100
                    d*= pow( 2, e/0.3);
101
                    next+=2;
102
                }else{
103
                    d*= pow(10, e);
104
                    next++;
105
                }
106
            }
107
        }
108

    
109
        if(*next=='B') {
110
            d*=8;
111
            next++;
112
        }
113
    }
114
    /* if requested, fill in tail with the position after the last parsed
115
       character */
116
    if (tail)
117
        *tail = next;
118
    return d;
119
}
120

    
121
static int strmatch(const char *s, const char *prefix){
122
    int i;
123
    for(i=0; prefix[i]; i++){
124
        if(prefix[i] != s[i]) return 0;
125
    }
126
    return 1;
127
}
128

    
129
struct ff_expr_s {
130
    enum {
131
        e_value, e_const, e_func0, e_func1, e_func2,
132
        e_squish, e_gauss, e_ld,
133
        e_mod, e_max, e_min, e_eq, e_gt, e_gte,
134
        e_pow, e_mul, e_div, e_add,
135
        e_last, e_st, e_while,
136
    } type;
137
    double value; // is sign in other types
138
    union {
139
        int const_index;
140
        double (*func0)(double);
141
        double (*func1)(void *, double);
142
        double (*func2)(void *, double, double);
143
    } a;
144
    AVEvalExpr * param[2];
145
};
146

    
147
static double eval_expr(Parser * p, AVEvalExpr * e) {
148
    switch (e->type) {
149
        case e_value:  return e->value;
150
        case e_const:  return e->value * p->const_value[e->a.const_index];
151
        case e_func0:  return e->value * e->a.func0(eval_expr(p, e->param[0]));
152
        case e_func1:  return e->value * e->a.func1(p->opaque, eval_expr(p, e->param[0]));
153
        case e_func2:  return e->value * e->a.func2(p->opaque, eval_expr(p, e->param[0]), eval_expr(p, e->param[1]));
154
        case e_squish: return 1/(1+exp(4*eval_expr(p, e->param[0])));
155
        case e_gauss: { double d = eval_expr(p, e->param[0]); return exp(-d*d/2)/sqrt(2*M_PI); }
156
        case e_ld:     return e->value * p->var[av_clip(eval_expr(p, e->param[0]), 0, VARS-1)];
157
        case e_while: {
158
            double d = NAN;
159
            while(eval_expr(p, e->param[0]))
160
                d=eval_expr(p, e->param[1]);
161
            return d;
162
        }
163
        default: {
164
            double d = eval_expr(p, e->param[0]);
165
            double d2 = eval_expr(p, e->param[1]);
166
            switch (e->type) {
167
                case e_mod: return e->value * (d - floor(d/d2)*d2);
168
                case e_max: return e->value * (d >  d2 ?   d : d2);
169
                case e_min: return e->value * (d <  d2 ?   d : d2);
170
                case e_eq:  return e->value * (d == d2 ? 1.0 : 0.0);
171
                case e_gt:  return e->value * (d >  d2 ? 1.0 : 0.0);
172
                case e_gte: return e->value * (d >= d2 ? 1.0 : 0.0);
173
                case e_pow: return e->value * pow(d, d2);
174
                case e_mul: return e->value * (d * d2);
175
                case e_div: return e->value * (d / d2);
176
                case e_add: return e->value * (d + d2);
177
                case e_last:return e->value * d2;
178
                case e_st : return e->value * (p->var[av_clip(d, 0, VARS-1)]= d2);
179
            }
180
        }
181
    }
182
    return NAN;
183
}
184

    
185
static AVEvalExpr * parse_expr(Parser *p);
186

    
187
void ff_eval_free(AVEvalExpr * e) {
188
    if (!e) return;
189
    ff_eval_free(e->param[0]);
190
    ff_eval_free(e->param[1]);
191
    av_freep(&e);
192
}
193

    
194
static AVEvalExpr * parse_primary(Parser *p) {
195
    AVEvalExpr * d = av_mallocz(sizeof(AVEvalExpr));
196
    char *next= p->s;
197
    int i;
198

    
199
    /* number */
200
    d->value = av_strtod(p->s, &next);
201
    if(next != p->s){
202
        d->type = e_value;
203
        p->s= next;
204
        return d;
205
    }
206
    d->value = 1;
207

    
208
    /* named constants */
209
    for(i=0; p->const_name && p->const_name[i]; i++){
210
        if(strmatch(p->s, p->const_name[i])){
211
            p->s+= strlen(p->const_name[i]);
212
            d->type = e_const;
213
            d->a.const_index = i;
214
            return d;
215
        }
216
    }
217

    
218
    p->s= strchr(p->s, '(');
219
    if(p->s==NULL){
220
        *p->error = "undefined constant or missing (";
221
        p->s= next;
222
        ff_eval_free(d);
223
        return NULL;
224
    }
225
    p->s++; // "("
226
    if (*next == '(') { // special case do-nothing
227
        av_freep(&d);
228
        d = parse_expr(p);
229
        if(p->s[0] != ')'){
230
            *p->error = "missing )";
231
            ff_eval_free(d);
232
            return NULL;
233
        }
234
        p->s++; // ")"
235
        return d;
236
    }
237
    d->param[0] = parse_expr(p);
238
    if(p->s[0]== ','){
239
        p->s++; // ","
240
        d->param[1] = parse_expr(p);
241
    }
242
    if(p->s[0] != ')'){
243
        *p->error = "missing )";
244
        ff_eval_free(d);
245
        return NULL;
246
    }
247
    p->s++; // ")"
248

    
249
    d->type = e_func0;
250
         if( strmatch(next, "sinh"  ) ) d->a.func0 = sinh;
251
    else if( strmatch(next, "cosh"  ) ) d->a.func0 = cosh;
252
    else if( strmatch(next, "tanh"  ) ) d->a.func0 = tanh;
253
    else if( strmatch(next, "sin"   ) ) d->a.func0 = sin;
254
    else if( strmatch(next, "cos"   ) ) d->a.func0 = cos;
255
    else if( strmatch(next, "tan"   ) ) d->a.func0 = tan;
256
    else if( strmatch(next, "atan"  ) ) d->a.func0 = atan;
257
    else if( strmatch(next, "asin"  ) ) d->a.func0 = asin;
258
    else if( strmatch(next, "acos"  ) ) d->a.func0 = acos;
259
    else if( strmatch(next, "exp"   ) ) d->a.func0 = exp;
260
    else if( strmatch(next, "log"   ) ) d->a.func0 = log;
261
    else if( strmatch(next, "abs"   ) ) d->a.func0 = fabs;
262
    else if( strmatch(next, "squish") ) d->type = e_squish;
263
    else if( strmatch(next, "gauss" ) ) d->type = e_gauss;
264
    else if( strmatch(next, "mod"   ) ) d->type = e_mod;
265
    else if( strmatch(next, "max"   ) ) d->type = e_max;
266
    else if( strmatch(next, "min"   ) ) d->type = e_min;
267
    else if( strmatch(next, "eq"    ) ) d->type = e_eq;
268
    else if( strmatch(next, "gte"   ) ) d->type = e_gte;
269
    else if( strmatch(next, "gt"    ) ) d->type = e_gt;
270
    else if( strmatch(next, "lte"   ) ) { AVEvalExpr * tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gt; }
271
    else if( strmatch(next, "lt"    ) ) { AVEvalExpr * tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gte; }
272
    else if( strmatch(next, "ld"    ) ) d->type = e_ld;
273
    else if( strmatch(next, "st"    ) ) d->type = e_st;
274
    else if( strmatch(next, "while" ) ) d->type = e_while;
275
    else {
276
        for(i=0; p->func1_name && p->func1_name[i]; i++){
277
            if(strmatch(next, p->func1_name[i])){
278
                d->a.func1 = p->func1[i];
279
                d->type = e_func1;
280
                return d;
281
            }
282
        }
283

    
284
        for(i=0; p->func2_name && p->func2_name[i]; i++){
285
            if(strmatch(next, p->func2_name[i])){
286
                d->a.func2 = p->func2[i];
287
                d->type = e_func2;
288
                return d;
289
            }
290
        }
291

    
292
        *p->error = "unknown function";
293
        ff_eval_free(d);
294
        return NULL;
295
    }
296

    
297
    return d;
298
}
299

    
300
static AVEvalExpr * new_eval_expr(int type, int value, AVEvalExpr *p0, AVEvalExpr *p1){
301
    AVEvalExpr * e = av_mallocz(sizeof(AVEvalExpr));
302
    e->type     =type   ;
303
    e->value    =value  ;
304
    e->param[0] =p0     ;
305
    e->param[1] =p1     ;
306
    return e;
307
}
308

    
309
static AVEvalExpr * parse_pow(Parser *p, int *sign){
310
    *sign= (*p->s == '+') - (*p->s == '-');
311
    p->s += *sign&1;
312
    return parse_primary(p);
313
}
314

    
315
static AVEvalExpr * parse_factor(Parser *p){
316
    int sign, sign2;
317
    AVEvalExpr * e = parse_pow(p, &sign);
318
    while(p->s[0]=='^'){
319
        p->s++;
320
        e= new_eval_expr(e_pow, 1, e, parse_pow(p, &sign2));
321
        if (e->param[1]) e->param[1]->value *= (sign2|1);
322
    }
323
    if (e) e->value *= (sign|1);
324
    return e;
325
}
326

    
327
static AVEvalExpr * parse_term(Parser *p){
328
    AVEvalExpr * e = parse_factor(p);
329
    while(p->s[0]=='*' || p->s[0]=='/'){
330
        int c= *p->s++;
331
        e= new_eval_expr(c == '*' ? e_mul : e_div, 1, e, parse_factor(p));
332
    }
333
    return e;
334
}
335

    
336
static AVEvalExpr * parse_subexpr(Parser *p) {
337
    AVEvalExpr * e = parse_term(p);
338
    while(*p->s == '+' || *p->s == '-') {
339
        e= new_eval_expr(e_add, 1, e, parse_term(p));
340
    };
341

    
342
    return e;
343
}
344

    
345
static AVEvalExpr * parse_expr(Parser *p) {
346
    AVEvalExpr * e;
347

    
348
    if(p->stack_index <= 0) //protect against stack overflows
349
        return NULL;
350
    p->stack_index--;
351

    
352
    e = parse_subexpr(p);
353

    
354
    while(*p->s == ';') {
355
        p->s++;
356
        e= new_eval_expr(e_last, 1, e, parse_subexpr(p));
357
    };
358

    
359
    p->stack_index++;
360

    
361
    return e;
362
}
363

    
364
static int verify_expr(AVEvalExpr * e) {
365
    if (!e) return 0;
366
    switch (e->type) {
367
        case e_value:
368
        case e_const: return 1;
369
        case e_func0:
370
        case e_func1:
371
        case e_squish:
372
        case e_ld:
373
        case e_gauss: return verify_expr(e->param[0]);
374
        default: return verify_expr(e->param[0]) && verify_expr(e->param[1]);
375
    }
376
}
377

    
378
AVEvalExpr * ff_parse(const char *s, const char * const *const_name,
379
               double (**func1)(void *, double), const char **func1_name,
380
               double (**func2)(void *, double, double), const char **func2_name,
381
               const char **error){
382
    Parser p;
383
    AVEvalExpr * e;
384
    char w[strlen(s) + 1], * wp = w;
385

    
386
    while (*s)
387
        if (!isspace(*s++)) *wp++ = s[-1];
388
    *wp++ = 0;
389

    
390
    p.stack_index=100;
391
    p.s= w;
392
    p.const_name = const_name;
393
    p.func1      = func1;
394
    p.func1_name = func1_name;
395
    p.func2      = func2;
396
    p.func2_name = func2_name;
397
    p.error= error;
398

    
399
    e = parse_expr(&p);
400
    if (!verify_expr(e)) {
401
        ff_eval_free(e);
402
        return NULL;
403
    }
404
    return e;
405
}
406

    
407
double ff_parse_eval(AVEvalExpr * e, const double *const_value, void *opaque) {
408
    Parser p;
409

    
410
    p.const_value= const_value;
411
    p.opaque     = opaque;
412
    return eval_expr(&p, e);
413
}
414

    
415
double ff_eval2(const char *s, const double *const_value, const char * const *const_name,
416
               double (**func1)(void *, double), const char **func1_name,
417
               double (**func2)(void *, double, double), const char **func2_name,
418
               void *opaque, const char **error){
419
    AVEvalExpr * e = ff_parse(s, const_name, func1, func1_name, func2, func2_name, error);
420
    double d;
421
    if (!e) return NAN;
422
    d = ff_parse_eval(e, const_value, opaque);
423
    ff_eval_free(e);
424
    return d;
425
}
426

    
427
#ifdef TEST
428
#undef printf
429
static double const_values[]={
430
    M_PI,
431
    M_E,
432
    0
433
};
434
static const char *const_names[]={
435
    "PI",
436
    "E",
437
    0
438
};
439
int main(void){
440
    int i;
441
    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));
442
    printf("%f == 0.931322575\n", ff_eval2("80G/80Gi", const_values, const_names, NULL, NULL, NULL, NULL, NULL, NULL));
443

    
444
    for(i=0; i<1050; i++){
445
        START_TIMER
446
            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);
447
        STOP_TIMER("ff_eval2")
448
    }
449
    return 0;
450
}
451
#endif