eval.c 24 KB
Newer Older
1
/*
2
 * Copyright (c) 2002-2006 Michael Niedermayer <michaelni@gmx.at>
3
 * Copyright (c) 2006 Oded Shimon <ods15@ods15.dyndns.org>
4
 *
5 6 7
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
8 9
 * modify it under the terms of the GNU Lesser General Public
 * 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 14 15 16 17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * 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
 */

Michael Niedermayer's avatar
Michael Niedermayer committed
22
/**
23
 * @file
Michael Niedermayer's avatar
Michael Niedermayer committed
24 25
 * simple arithmetic expression evaluator.
 *
26 27 28
 * see http://joe.hotchkiss.com/programming/eval/eval.html
 */

29
#include <float.h>
30
#include "avutil.h"
31
#include "common.h"
32
#include "eval.h"
33
#include "log.h"
34
#include "mathematics.h"
35

36
typedef struct Parser {
37
    const AVClass *class;
38 39
    int stack_index;
    char *s;
40 41 42 43 44 45
    const double *const_values;
    const char * const *const_names;          // NULL terminated
    double (* const *funcs1)(void *, double a);           // NULL terminated
    const char * const *func1_names;          // NULL terminated
    double (* const *funcs2)(void *, double a, double b); // NULL terminated
    const char * const *func2_names;          // NULL terminated
46
    void *opaque;
47 48
    int log_offset;
    void *log_ctx;
49
#define VARS 10
50
    double *var;
51 52
} Parser;

53 54
static const AVClass class = { "Eval", av_default_item_name, NULL, LIBAVUTIL_VERSION_INT, offsetof(Parser,log_offset), offsetof(Parser,log_ctx) };

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

78 79 80 81 82 83 84 85 86
static const struct {
    const char *name;
    double value;
} constants[] = {
    { "E",   M_E   },
    { "PI",  M_PI  },
    { "PHI", M_PHI },
};

87 88
double av_strtod(const char *numstr, char **tail)
{
89 90
    double d;
    char *next;
91
    if(numstr[0]=='0' && (numstr[1]|0x20)=='x') {
92
        d = strtoul(numstr, &next, 16);
93 94
    } else
        d = strtod(numstr, &next);
95
    /* if parsing succeeded, check for and interpret postfixes */
96
    if (next!=numstr) {
97
        if (*next >= 'E' && *next <= 'z') {
98
            int e= si_prefixes[*next - 'E'];
99 100
            if (e) {
                if (next[1] == 'i') {
101 102
                    d*= pow( 2, e/0.3);
                    next+=2;
103
                } else {
104 105 106 107 108 109
                    d*= pow(10, e);
                    next++;
                }
            }
        }

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

122 123
#define IS_IDENTIFIER_CHAR(c) ((c) - '0' <= 9U || (c) - 'a' <= 25U || (c) - 'A' <= 25U || (c) == '_')

124 125
static int strmatch(const char *s, const char *prefix)
{
126
    int i;
127 128
    for (i=0; prefix[i]; i++) {
        if (prefix[i] != s[i]) return 0;
129
    }
130 131
    /* return 1 only if the s identifier is terminated */
    return !IS_IDENTIFIER_CHAR(s[i]);
132 133
}

134
struct AVExpr {
135 136
    enum {
        e_value, e_const, e_func0, e_func1, e_func2,
137
        e_squish, e_gauss, e_ld, e_isnan, e_isinf,
138 139
        e_mod, e_max, e_min, e_eq, e_gt, e_gte,
        e_pow, e_mul, e_div, e_add,
140
        e_last, e_st, e_while, e_taylor, e_root, e_floor, e_ceil, e_trunc,
Michael Niedermayer's avatar
Michael Niedermayer committed
141
        e_sqrt, e_not, e_random, e_hypot, e_gcd,
142
        e_if, e_ifnot,
143 144 145 146 147 148 149 150
    } type;
    double value; // is sign in other types
    union {
        int const_index;
        double (*func0)(double);
        double (*func1)(void *, double);
        double (*func2)(void *, double, double);
    } a;
151
    struct AVExpr *param[3];
152
    double *var;
153 154
};

155 156
static double eval_expr(Parser *p, AVExpr *e)
{
157 158
    switch (e->type) {
        case e_value:  return e->value;
159
        case e_const:  return e->value * p->const_values[e->a.const_index];
160 161 162 163 164
        case e_func0:  return e->value * e->a.func0(eval_expr(p, e->param[0]));
        case e_func1:  return e->value * e->a.func1(p->opaque, eval_expr(p, e->param[0]));
        case e_func2:  return e->value * e->a.func2(p->opaque, eval_expr(p, e->param[0]), eval_expr(p, e->param[1]));
        case e_squish: return 1/(1+exp(4*eval_expr(p, e->param[0])));
        case e_gauss: { double d = eval_expr(p, e->param[0]); return exp(-d*d/2)/sqrt(2*M_PI); }
165
        case e_ld:     return e->value * p->var[av_clip(eval_expr(p, e->param[0]), 0, VARS-1)];
166
        case e_isnan:  return e->value * !!isnan(eval_expr(p, e->param[0]));
167
        case e_isinf:  return e->value * !!isinf(eval_expr(p, e->param[0]));
168 169 170
        case e_floor:  return e->value * floor(eval_expr(p, e->param[0]));
        case e_ceil :  return e->value * ceil (eval_expr(p, e->param[0]));
        case e_trunc:  return e->value * trunc(eval_expr(p, e->param[0]));
171
        case e_sqrt:   return e->value * sqrt (eval_expr(p, e->param[0]));
172
        case e_not:    return e->value * (eval_expr(p, e->param[0]) == 0);
173 174
        case e_if:     return e->value * ( eval_expr(p, e->param[0]) ? eval_expr(p, e->param[1]) : 0);
        case e_ifnot:  return e->value * (!eval_expr(p, e->param[0]) ? eval_expr(p, e->param[1]) : 0);
Michael Niedermayer's avatar
Michael Niedermayer committed
175 176 177 178 179 180 181
        case e_random:{
            int idx= av_clip(eval_expr(p, e->param[0]), 0, VARS-1);
            uint64_t r= isnan(p->var[idx]) ? 0 : p->var[idx];
            r= r*1664525+1013904223;
            p->var[idx]= r;
            return e->value * (r * (1.0/UINT64_MAX));
        }
182
        case e_while: {
183
            double d = NAN;
184
            while (eval_expr(p, e->param[0]))
185 186 187
                d=eval_expr(p, e->param[1]);
            return d;
        }
188 189 190
        case e_taylor: {
            double t = 1, d = 0, v;
            double x = eval_expr(p, e->param[1]);
191
            int id = e->param[2] ? av_clip(eval_expr(p, e->param[2]), 0, VARS-1) : 0;
192
            int i;
193
            double var0 = p->var[id];
194 195
            for(i=0; i<1000; i++) {
                double ld = d;
196
                p->var[id] = i;
197 198 199 200 201 202
                v = eval_expr(p, e->param[0]);
                d += t*v;
                if(ld==d && v)
                    break;
                t *= x / (i+1);
            }
203
            p->var[id] = var0;
204 205
            return d;
        }
206
        case e_root: {
207
            int i, j;
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
            double low = -1, high = -1, v, low_v = -DBL_MAX, high_v = DBL_MAX;
            double var0 = p->var[0];
            double x_max = eval_expr(p, e->param[1]);
            for(i=-1; i<1024; i++) {
                if(i<255) {
                    p->var[0] = av_reverse[i&255]*x_max/255;
                } else {
                    p->var[0] = x_max*pow(0.9, i-255);
                    if (i&1) p->var[0] *= -1;
                    if (i&2) p->var[0] += low;
                    else     p->var[0] += high;
                }
                v = eval_expr(p, e->param[0]);
                if (v<=0 && v>low_v) {
                    low    = p->var[0];
                    low_v  = v;
                }
                if (v>=0 && v<high_v) {
                    high   = p->var[0];
                    high_v = v;
                }
                if (low>=0 && high>=0){
230
                    for (j=0; j<1000; j++) {
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
                        p->var[0] = (low+high)*0.5;
                        if (low == p->var[0] || high == p->var[0])
                            break;
                        v = eval_expr(p, e->param[0]);
                        if (v<=0) low = p->var[0];
                        if (v>=0) high= p->var[0];
                        if (isnan(v)) {
                            low = high = v;
                            break;
                        }
                    }
                    break;
                }
            }
            p->var[0] = var0;
            return -low_v<high_v ? low : high;
        }
248 249 250 251 252
        default: {
            double d = eval_expr(p, e->param[0]);
            double d2 = eval_expr(p, e->param[1]);
            switch (e->type) {
                case e_mod: return e->value * (d - floor(d/d2)*d2);
Michael Niedermayer's avatar
Michael Niedermayer committed
253
                case e_gcd: return e->value * av_gcd(d,d2);
254 255 256 257 258 259 260
                case e_max: return e->value * (d >  d2 ?   d : d2);
                case e_min: return e->value * (d <  d2 ?   d : d2);
                case e_eq:  return e->value * (d == d2 ? 1.0 : 0.0);
                case e_gt:  return e->value * (d >  d2 ? 1.0 : 0.0);
                case e_gte: return e->value * (d >= d2 ? 1.0 : 0.0);
                case e_pow: return e->value * pow(d, d2);
                case e_mul: return e->value * (d * d2);
261
                case e_div: return e->value * ((!CONFIG_FTRAPV || d2 ) ? (d / d2) : d * INFINITY);
262
                case e_add: return e->value * (d + d2);
Oded Shimon's avatar
Oded Shimon committed
263
                case e_last:return e->value * d2;
264
                case e_st : return e->value * (p->var[av_clip(d, 0, VARS-1)]= d2);
Michael Niedermayer's avatar
Michael Niedermayer committed
265
                case e_hypot:return e->value * (sqrt(d*d + d2*d2));
266 267 268 269 270 271
            }
        }
    }
    return NAN;
}

272
static int parse_expr(AVExpr **e, Parser *p);
273

274
void av_expr_free(AVExpr *e)
275
{
276
    if (!e) return;
277 278
    av_expr_free(e->param[0]);
    av_expr_free(e->param[1]);
279
    av_expr_free(e->param[2]);
280
    av_freep(&e->var);
281 282 283
    av_freep(&e);
}

284 285
static int parse_primary(AVExpr **e, Parser *p)
{
286
    AVExpr *d = av_mallocz(sizeof(AVExpr));
287
    char *next = p->s, *s0 = p->s;
288
    int ret, i;
289

290
    if (!d)
291
        return AVERROR(ENOMEM);
292

293
    /* number */
294
    d->value = av_strtod(p->s, &next);
295
    if (next != p->s) {
296
        d->type = e_value;
297
        p->s= next;
298 299
        *e = d;
        return 0;
300
    }
301
    d->value = 1;
302

303
    /* named constants */
304 305
    for (i=0; p->const_names && p->const_names[i]; i++) {
        if (strmatch(p->s, p->const_names[i])) {
306
            p->s+= strlen(p->const_names[i]);
307 308
            d->type = e_const;
            d->a.const_index = i;
309 310
            *e = d;
            return 0;
311 312
        }
    }
313 314 315 316 317 318 319 320 321
    for (i = 0; i < FF_ARRAY_ELEMS(constants); i++) {
        if (strmatch(p->s, constants[i].name)) {
            p->s += strlen(constants[i].name);
            d->type = e_value;
            d->value = constants[i].value;
            *e = d;
            return 0;
        }
    }
322

323
    p->s= strchr(p->s, '(');
324
    if (p->s==NULL) {
325
        av_log(p, AV_LOG_ERROR, "Undefined constant or missing '(' in '%s'\n", s0);
Michael Niedermayer's avatar
Michael Niedermayer committed
326
        p->s= next;
327
        av_expr_free(d);
328
        return AVERROR(EINVAL);
329 330
    }
    p->s++; // "("
331 332
    if (*next == '(') { // special case do-nothing
        av_freep(&d);
333 334
        if ((ret = parse_expr(&d, p)) < 0)
            return ret;
335
        if (p->s[0] != ')') {
336
            av_log(p, AV_LOG_ERROR, "Missing ')' in '%s'\n", s0);
337
            av_expr_free(d);
338
            return AVERROR(EINVAL);
339 340
        }
        p->s++; // ")"
341 342 343 344
        *e = d;
        return 0;
    }
    if ((ret = parse_expr(&(d->param[0]), p)) < 0) {
345
        av_expr_free(d);
346
        return ret;
347
    }
348
    if (p->s[0]== ',') {
349
        p->s++; // ","
350
        parse_expr(&d->param[1], p);
351
    }
352 353 354 355
    if (p->s[0]== ',') {
        p->s++; // ","
        parse_expr(&d->param[2], p);
    }
356
    if (p->s[0] != ')') {
357
        av_log(p, AV_LOG_ERROR, "Missing ')' or too many args in '%s'\n", s0);
358
        av_expr_free(d);
359
        return AVERROR(EINVAL);
360 361
    }
    p->s++; // ")"
362

363
    d->type = e_func0;
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
         if (strmatch(next, "sinh"  )) d->a.func0 = sinh;
    else if (strmatch(next, "cosh"  )) d->a.func0 = cosh;
    else if (strmatch(next, "tanh"  )) d->a.func0 = tanh;
    else if (strmatch(next, "sin"   )) d->a.func0 = sin;
    else if (strmatch(next, "cos"   )) d->a.func0 = cos;
    else if (strmatch(next, "tan"   )) d->a.func0 = tan;
    else if (strmatch(next, "atan"  )) d->a.func0 = atan;
    else if (strmatch(next, "asin"  )) d->a.func0 = asin;
    else if (strmatch(next, "acos"  )) d->a.func0 = acos;
    else if (strmatch(next, "exp"   )) d->a.func0 = exp;
    else if (strmatch(next, "log"   )) d->a.func0 = log;
    else if (strmatch(next, "abs"   )) d->a.func0 = fabs;
    else if (strmatch(next, "squish")) d->type = e_squish;
    else if (strmatch(next, "gauss" )) d->type = e_gauss;
    else if (strmatch(next, "mod"   )) d->type = e_mod;
    else if (strmatch(next, "max"   )) d->type = e_max;
    else if (strmatch(next, "min"   )) d->type = e_min;
    else if (strmatch(next, "eq"    )) d->type = e_eq;
    else if (strmatch(next, "gte"   )) d->type = e_gte;
    else if (strmatch(next, "gt"    )) d->type = e_gt;
384 385
    else if (strmatch(next, "lte"   )) { AVExpr *tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gte; }
    else if (strmatch(next, "lt"    )) { AVExpr *tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gt; }
386
    else if (strmatch(next, "ld"    )) d->type = e_ld;
387
    else if (strmatch(next, "isnan" )) d->type = e_isnan;
388
    else if (strmatch(next, "isinf" )) d->type = e_isinf;
389 390
    else if (strmatch(next, "st"    )) d->type = e_st;
    else if (strmatch(next, "while" )) d->type = e_while;
391
    else if (strmatch(next, "taylor")) d->type = e_taylor;
392
    else if (strmatch(next, "root"  )) d->type = e_root;
393 394 395
    else if (strmatch(next, "floor" )) d->type = e_floor;
    else if (strmatch(next, "ceil"  )) d->type = e_ceil;
    else if (strmatch(next, "trunc" )) d->type = e_trunc;
396
    else if (strmatch(next, "sqrt"  )) d->type = e_sqrt;
397
    else if (strmatch(next, "not"   )) d->type = e_not;
398
    else if (strmatch(next, "pow"   )) d->type = e_pow;
Michael Niedermayer's avatar
Michael Niedermayer committed
399
    else if (strmatch(next, "random")) d->type = e_random;
Michael Niedermayer's avatar
Michael Niedermayer committed
400
    else if (strmatch(next, "hypot" )) d->type = e_hypot;
Michael Niedermayer's avatar
Michael Niedermayer committed
401
    else if (strmatch(next, "gcd"   )) d->type = e_gcd;
402 403
    else if (strmatch(next, "if"    )) d->type = e_if;
    else if (strmatch(next, "ifnot" )) d->type = e_ifnot;
404
    else {
405 406
        for (i=0; p->func1_names && p->func1_names[i]; i++) {
            if (strmatch(next, p->func1_names[i])) {
407
                d->a.func1 = p->funcs1[i];
408
                d->type = e_func1;
409 410
                *e = d;
                return 0;
411 412 413
            }
        }

414 415
        for (i=0; p->func2_names && p->func2_names[i]; i++) {
            if (strmatch(next, p->func2_names[i])) {
416
                d->a.func2 = p->funcs2[i];
417
                d->type = e_func2;
418 419
                *e = d;
                return 0;
420 421 422
            }
        }

423
        av_log(p, AV_LOG_ERROR, "Unknown function in '%s'\n", s0);
424
        av_expr_free(d);
425
        return AVERROR(EINVAL);
426
    }
427

428 429
    *e = d;
    return 0;
430
}
Michael Niedermayer's avatar
Michael Niedermayer committed
431

432 433 434
static AVExpr *new_eval_expr(int type, int value, AVExpr *p0, AVExpr *p1)
{
    AVExpr *e = av_mallocz(sizeof(AVExpr));
435 436
    if (!e)
        return NULL;
437 438 439 440 441 442 443
    e->type     =type   ;
    e->value    =value  ;
    e->param[0] =p0     ;
    e->param[1] =p1     ;
    return e;
}

444 445
static int parse_pow(AVExpr **e, Parser *p, int *sign)
{
446 447
    *sign= (*p->s == '+') - (*p->s == '-');
    p->s += *sign&1;
448
    return parse_primary(e, p);
449 450
}

451 452 453 454 455 456
static int parse_factor(AVExpr **e, Parser *p)
{
    int sign, sign2, ret;
    AVExpr *e0, *e1, *e2;
    if ((ret = parse_pow(&e0, p, &sign)) < 0)
        return ret;
457
    while(p->s[0]=='^'){
458
        e1 = e0;
459
        p->s++;
460
        if ((ret = parse_pow(&e2, p, &sign2)) < 0) {
461
            av_expr_free(e1);
462 463 464 465
            return ret;
        }
        e0 = new_eval_expr(e_pow, 1, e1, e2);
        if (!e0) {
466 467
            av_expr_free(e1);
            av_expr_free(e2);
468 469 470
            return AVERROR(ENOMEM);
        }
        if (e0->param[1]) e0->param[1]->value *= (sign2|1);
471
    }
472 473 474 475
    if (e0) e0->value *= (sign|1);

    *e = e0;
    return 0;
476 477
}

478 479 480 481 482 483
static int parse_term(AVExpr **e, Parser *p)
{
    int ret;
    AVExpr *e0, *e1, *e2;
    if ((ret = parse_factor(&e0, p)) < 0)
        return ret;
484
    while (p->s[0]=='*' || p->s[0]=='/') {
485
        int c= *p->s++;
486 487
        e1 = e0;
        if ((ret = parse_factor(&e2, p)) < 0) {
488
            av_expr_free(e1);
489 490 491 492
            return ret;
        }
        e0 = new_eval_expr(c == '*' ? e_mul : e_div, 1, e1, e2);
        if (!e0) {
493 494
            av_expr_free(e1);
            av_expr_free(e2);
495 496
            return AVERROR(ENOMEM);
        }
497
    }
498 499
    *e = e0;
    return 0;
500 501
}

502 503 504 505 506 507
static int parse_subexpr(AVExpr **e, Parser *p)
{
    int ret;
    AVExpr *e0, *e1, *e2;
    if ((ret = parse_term(&e0, p)) < 0)
        return ret;
508
    while (*p->s == '+' || *p->s == '-') {
509 510
        e1 = e0;
        if ((ret = parse_term(&e2, p)) < 0) {
511
            av_expr_free(e1);
512 513 514 515
            return ret;
        }
        e0 = new_eval_expr(e_add, 1, e1, e2);
        if (!e0) {
516 517
            av_expr_free(e1);
            av_expr_free(e2);
518 519
            return AVERROR(ENOMEM);
        }
520 521
    };

522 523
    *e = e0;
    return 0;
524 525
}

526 527 528 529
static int parse_expr(AVExpr **e, Parser *p)
{
    int ret;
    AVExpr *e0, *e1, *e2;
530
    if (p->stack_index <= 0) //protect against stack overflows
531
        return AVERROR(EINVAL);
Michael Niedermayer's avatar
Michael Niedermayer committed
532 533
    p->stack_index--;

534 535
    if ((ret = parse_subexpr(&e0, p)) < 0)
        return ret;
536
    while (*p->s == ';') {
537
        p->s++;
538 539
        e1 = e0;
        if ((ret = parse_subexpr(&e2, p)) < 0) {
540
            av_expr_free(e1);
541 542 543 544
            return ret;
        }
        e0 = new_eval_expr(e_last, 1, e1, e2);
        if (!e0) {
545 546
            av_expr_free(e1);
            av_expr_free(e2);
547 548
            return AVERROR(ENOMEM);
        }
549
    };
Michael Niedermayer's avatar
Michael Niedermayer committed
550 551

    p->stack_index++;
552 553
    *e = e0;
    return 0;
554 555
}

556 557
static int verify_expr(AVExpr *e)
{
558 559 560 561 562 563 564
    if (!e) return 0;
    switch (e->type) {
        case e_value:
        case e_const: return 1;
        case e_func0:
        case e_func1:
        case e_squish:
565
        case e_ld:
566
        case e_gauss:
567
        case e_isnan:
568
        case e_isinf:
569 570 571
        case e_floor:
        case e_ceil:
        case e_trunc:
572
        case e_sqrt:
573
        case e_not:
Michael Niedermayer's avatar
Michael Niedermayer committed
574
        case e_random:
575
            return verify_expr(e->param[0]) && !e->param[1];
576 577 578
        case e_taylor:
            return verify_expr(e->param[0]) && verify_expr(e->param[1])
                   && (!e->param[2] || verify_expr(e->param[2]));
579
        default: return verify_expr(e->param[0]) && verify_expr(e->param[1]) && !e->param[2];
580 581 582
    }
}

583
int av_expr_parse(AVExpr **expr, const char *s,
584 585 586
                  const char * const *const_names,
                  const char * const *func1_names, double (* const *funcs1)(void *, double),
                  const char * const *func2_names, double (* const *funcs2)(void *, double, double),
587
                  int log_offset, void *log_ctx)
588
{
589
    Parser p = { 0 };
590
    AVExpr *e = NULL;
591 592
    char *w = av_malloc(strlen(s) + 1);
    char *wp = w;
593
    const char *s0 = s;
594
    int ret = 0;
595 596

    if (!w)
597
        return AVERROR(ENOMEM);
598 599 600 601

    while (*s)
        if (!isspace(*s++)) *wp++ = s[-1];
    *wp++ = 0;
602

603
    p.class      = &class;
Michael Niedermayer's avatar
Michael Niedermayer committed
604
    p.stack_index=100;
605
    p.s= w;
606 607 608 609 610
    p.const_names = const_names;
    p.funcs1      = funcs1;
    p.func1_names = func1_names;
    p.funcs2      = funcs2;
    p.func2_names = func2_names;
611 612
    p.log_offset = log_offset;
    p.log_ctx    = log_ctx;
613

614 615
    if ((ret = parse_expr(&e, &p)) < 0)
        goto end;
616
    if (*p.s) {
Ronald S. Bultje's avatar
Ronald S. Bultje committed
617
        av_expr_free(e);
618 619 620 621
        av_log(&p, AV_LOG_ERROR, "Invalid chars '%s' at the end of expression '%s'\n", p.s, s0);
        ret = AVERROR(EINVAL);
        goto end;
    }
622
    if (!verify_expr(e)) {
623
        av_expr_free(e);
624 625
        ret = AVERROR(EINVAL);
        goto end;
626
    }
627
    e->var= av_mallocz(sizeof(double) *VARS);
628
    *expr = e;
629 630
end:
    av_free(w);
631
    return ret;
632 633
}

634
double av_expr_eval(AVExpr *e, const double *const_values, void *opaque)
635
{
636
    Parser p = { 0 };
637
    p.var= e->var;
638

639
    p.const_values = const_values;
640 641 642 643
    p.opaque     = opaque;
    return eval_expr(&p, e);
}

644
int av_expr_parse_and_eval(double *d, const char *s,
645 646 647
                           const char * const *const_names, const double *const_values,
                           const char * const *func1_names, double (* const *funcs1)(void *, double),
                           const char * const *func2_names, double (* const *funcs2)(void *, double, double),
648
                           void *opaque, int log_offset, void *log_ctx)
649
{
650
    AVExpr *e = NULL;
651
    int ret = av_expr_parse(&e, s, const_names, func1_names, funcs1, func2_names, funcs2, log_offset, log_ctx);
652 653 654 655 656

    if (ret < 0) {
        *d = NAN;
        return ret;
    }
657 658
    *d = av_expr_eval(e, const_values, opaque);
    av_expr_free(e);
659
    return isnan(*d) ? AVERROR(EINVAL) : 0;
660
}
661 662

#ifdef TEST
663
// LCOV_EXCL_START
664
#undef printf
665 666
#include <string.h>

667
static const double const_values[] = {
668 669 670 671
    M_PI,
    M_E,
    0
};
672

673
static const char *const const_names[] = {
674 675 676 677
    "PI",
    "E",
    0
};
678

679
int main(int argc, char **argv)
680
{
Michael Niedermayer's avatar
Michael Niedermayer committed
681
    int i;
682
    double d;
683 684
    const char *const *expr;
    static const char *const exprs[] = {
685
        "",
686
        "1;2",
687 688 689
        "-20",
        "-PI",
        "+PI",
690
        "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)",
691
        "80G/80Gi",
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
        "1k",
        "1Gi",
        "1gi",
        "1GiFoo",
        "1k+1k",
        "1Gi*3foo",
        "foo",
        "foo(",
        "foo()",
        "foo)",
        "sin",
        "sin(",
        "sin()",
        "sin)",
        "sin 10",
        "sin(1,2,3)",
        "sin(1 )",
        "1",
        "1foo",
        "bar + PI + E + 100f*2 + foo",
        "13k + 12f - foo(1, 2)",
        "1gi",
        "1Gi",
715 716
        "st(0, 123)",
        "st(1, 123); ld(1)",
717 718 719 720 721 722 723 724
        "lte(0, 1)",
        "lte(1, 1)",
        "lte(1, 0)",
        "lt(0, 1)",
        "lt(1, 1)",
        "gt(1, 0)",
        "gt(2, 7)",
        "gte(122, 122)",
725 726 727 728 729 730
        /* compute 1+2+...+N */
        "st(0, 1); while(lte(ld(0), 100), st(1, ld(1)+ld(0));st(0, ld(0)+1)); ld(1)",
        /* compute Fib(N) */
        "st(1, 1); st(2, 2); st(0, 1); while(lte(ld(0),10), st(3, ld(1)+ld(2)); st(1, ld(2)); st(2, ld(3)); st(0, ld(0)+1)); ld(3)",
        "while(0, 10)",
        "st(0, 1); while(lte(ld(0),100), st(1, ld(1)+ld(0)); st(0, ld(0)+1))",
731 732
        "isnan(1)",
        "isnan(NAN)",
733 734 735 736
        "isnan(INF)",
        "isinf(1)",
        "isinf(NAN)",
        "isinf(INF)",
737 738 739 740 741 742 743
        "floor(NAN)",
        "floor(123.123)",
        "floor(-123.123)",
        "trunc(123.123)",
        "trunc(-123.123)",
        "ceil(123.123)",
        "ceil(-123.123)",
744
        "sqrt(1764)",
745
        "isnan(sqrt(-1))",
746 747 748
        "not(1)",
        "not(NAN)",
        "not(0)",
749 750 751 752
        "pow(0,1.23)",
        "pow(PI,1.23)",
        "PI^1.23",
        "pow(-1,1.23)",
753 754 755
        "if(1, 2)",
        "ifnot(0, 23)",
        "ifnot(1, NaN) + if(0, 1)",
756
        "taylor(1, 1)",
757
        "taylor(eq(mod(ld(1),4),1)-eq(mod(ld(1),4),3), PI/2, 1)",
758 759
        "root(sin(ld(0))-1, 2)",
        "root(sin(ld(0))+6+sin(ld(0)/12)-log(ld(0)), 100)",
760 761 762 763 764
        "7000000B*random(0)",
        "squish(2)",
        "gauss(0.1)",
        "hypot(4,3)",
        "gcd(30,55)*min(9,1)",
765 766 767 768 769
        NULL
    };

    for (expr = exprs; *expr; expr++) {
        printf("Evaluating '%s'\n", *expr);
770
        av_expr_parse_and_eval(&d, *expr,
771 772
                               const_names, const_values,
                               NULL, NULL, NULL, NULL, NULL, 0, NULL);
773
        if (isnan(d))
774
            printf("'%s' -> nan\n\n", *expr);
775
        else
776
            printf("'%s' -> %f\n\n", *expr, d);
777 778
    }

779
    av_expr_parse_and_eval(&d, "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)",
780 781
                           const_names, const_values,
                           NULL, NULL, NULL, NULL, NULL, 0, NULL);
782
    printf("%f == 12.7\n", d);
783
    av_expr_parse_and_eval(&d, "80G/80Gi",
784
                           const_names, const_values,
785
                           NULL, NULL, NULL, NULL, NULL, 0, NULL);
786
    printf("%f == 0.931322575\n", d);
787

788 789 790
    if (argc > 1 && !strcmp(argv[1], "-t")) {
        for (i = 0; i < 1050; i++) {
            START_TIMER;
791
            av_expr_parse_and_eval(&d, "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)",
792 793
                                   const_names, const_values,
                                   NULL, NULL, NULL, NULL, NULL, 0, NULL);
794 795
            STOP_TIMER("av_expr_parse_and_eval");
        }
Michael Niedermayer's avatar
Michael Niedermayer committed
796
    }
797

798
    return 0;
799
}
800
// LCOV_EXCL_STOP
801
#endif