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