Statistics
| Branch: | Revision:

ffmpeg / libavcodec / eval.c @ 6881b8e5

History | View | Annotate | Download (13.6 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 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 "mpegvideo.h"
33
#include "eval.h"
34

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
298
    return d;
299
}
300

    
301
static AVEvalExpr * new_eval_expr(int type, int value, AVEvalExpr *p0, AVEvalExpr *p1){
302
    AVEvalExpr * e = av_mallocz(sizeof(AVEvalExpr));
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 AVEvalExpr * parse_pow(Parser *p, int *sign){
311
    *sign= (*p->s == '+') - (*p->s == '-');
312
    p->s += *sign&1;
313
    return parse_primary(p);
314
}
315

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

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

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

    
343
    return e;
344
}
345

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

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

    
353
    e = parse_subexpr(p);
354

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

    
360
    p->stack_index++;
361

    
362
    return e;
363
}
364

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

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

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

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

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

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

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

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

    
428
#if LIBAVCODEC_VERSION_INT < ((52<<16)+(0<<8)+0)
429
attribute_deprecated double ff_eval(char *s, double *const_value, const char **const_name,
430
               double (**func1)(void *, double), const char **func1_name,
431
               double (**func2)(void *, double, double), char **func2_name,
432
               void *opaque){
433
    const char *error=NULL;
434
    double ret;
435
    ret = ff_eval2(s, const_value, const_name, func1, func1_name, func2, func2_name, opaque, &error);
436
    if (error)
437
        av_log(NULL, AV_LOG_ERROR, "Error evaluating \"%s\": %s\n", s, error);
438
    return ret;
439
}
440
#endif
441

    
442
#ifdef TEST
443
#undef printf
444
static double const_values[]={
445
    M_PI,
446
    M_E,
447
    0
448
};
449
static const char *const_names[]={
450
    "PI",
451
    "E",
452
    0
453
};
454
int main(void){
455
    int i;
456
    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));
457
    printf("%f == 0.931322575\n", ff_eval("80G/80Gi", const_values, const_names, NULL, NULL, NULL, NULL, NULL));
458

    
459
    for(i=0; i<1050; i++){
460
        START_TIMER
461
            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);
462
        STOP_TIMER("ff_eval")
463
    }
464
    return 0;
465
}
466
#endif