eval.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. * @file libavcodec/eval.c
  25. * simple arithmetic expression evaluator.
  26. *
  27. * see http://joe.hotchkiss.com/programming/eval/eval.html
  28. */
  29. #include "avcodec.h"
  30. #include "eval.h"
  31. #include <stdio.h>
  32. #include <stdlib.h>
  33. #include <string.h>
  34. #include <math.h>
  35. #ifndef NAN
  36. #define NAN 0.0/0.0
  37. #endif
  38. #ifndef M_PI
  39. #define M_PI 3.14159265358979323846
  40. #endif
  41. typedef struct Parser{
  42. int stack_index;
  43. char *s;
  44. const double *const_value;
  45. const char * const *const_name; // NULL terminated
  46. double (**func1)(void *, double a); // NULL terminated
  47. const char **func1_name; // NULL terminated
  48. double (**func2)(void *, double a, double b); // NULL terminated
  49. const char **func2_name; // NULL terminated
  50. void *opaque;
  51. const char **error;
  52. #define VARS 10
  53. double var[VARS];
  54. } Parser;
  55. static const int8_t si_prefixes['z' - 'E' + 1]={
  56. ['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. /** strtod() function extended with 'k', 'M', 'G', 'ki', 'Mi', 'Gi' and 'B'
  78. * postfixes. This allows using f.e. kB, MiB, G and B as a postfix. This
  79. * function assumes that the unit of numbers is bits not bytes.
  80. */
  81. static double av_strtod(const char *name, char **tail) {
  82. double d;
  83. char *next;
  84. d = strtod(name, &next);
  85. /* if parsing succeeded, check for and interpret postfixes */
  86. if (next!=name) {
  87. if(*next >= 'E' && *next <= 'z'){
  88. int e= si_prefixes[*next - 'E'];
  89. if(e){
  90. if(next[1] == 'i'){
  91. d*= pow( 2, e/0.3);
  92. next+=2;
  93. }else{
  94. d*= pow(10, e);
  95. next++;
  96. }
  97. }
  98. }
  99. if(*next=='B') {
  100. d*=8;
  101. next++;
  102. }
  103. }
  104. /* if requested, fill in tail with the position after the last parsed
  105. character */
  106. if (tail)
  107. *tail = next;
  108. return d;
  109. }
  110. static int strmatch(const char *s, const char *prefix){
  111. int i;
  112. for(i=0; prefix[i]; i++){
  113. if(prefix[i] != s[i]) return 0;
  114. }
  115. return 1;
  116. }
  117. struct ff_expr_s {
  118. enum {
  119. e_value, e_const, e_func0, e_func1, e_func2,
  120. e_squish, e_gauss, e_ld,
  121. e_mod, e_max, e_min, e_eq, e_gt, e_gte,
  122. e_pow, e_mul, e_div, e_add,
  123. e_last, e_st, e_while,
  124. } type;
  125. double value; // is sign in other types
  126. union {
  127. int const_index;
  128. double (*func0)(double);
  129. double (*func1)(void *, double);
  130. double (*func2)(void *, double, double);
  131. } a;
  132. AVEvalExpr * param[2];
  133. };
  134. static double eval_expr(Parser * p, AVEvalExpr * e) {
  135. switch (e->type) {
  136. case e_value: return e->value;
  137. case e_const: return e->value * p->const_value[e->a.const_index];
  138. case e_func0: return e->value * e->a.func0(eval_expr(p, e->param[0]));
  139. case e_func1: return e->value * e->a.func1(p->opaque, eval_expr(p, e->param[0]));
  140. case e_func2: return e->value * e->a.func2(p->opaque, eval_expr(p, e->param[0]), eval_expr(p, e->param[1]));
  141. case e_squish: return 1/(1+exp(4*eval_expr(p, e->param[0])));
  142. case e_gauss: { double d = eval_expr(p, e->param[0]); return exp(-d*d/2)/sqrt(2*M_PI); }
  143. case e_ld: return e->value * p->var[av_clip(eval_expr(p, e->param[0]), 0, VARS-1)];
  144. case e_while: {
  145. double d = NAN;
  146. while(eval_expr(p, e->param[0]))
  147. d=eval_expr(p, e->param[1]);
  148. return d;
  149. }
  150. default: {
  151. double d = eval_expr(p, e->param[0]);
  152. double d2 = eval_expr(p, e->param[1]);
  153. switch (e->type) {
  154. case e_mod: return e->value * (d - floor(d/d2)*d2);
  155. case e_max: return e->value * (d > d2 ? d : d2);
  156. case e_min: return e->value * (d < d2 ? d : d2);
  157. case e_eq: return e->value * (d == d2 ? 1.0 : 0.0);
  158. case e_gt: return e->value * (d > d2 ? 1.0 : 0.0);
  159. case e_gte: return e->value * (d >= d2 ? 1.0 : 0.0);
  160. case e_pow: return e->value * pow(d, d2);
  161. case e_mul: return e->value * (d * d2);
  162. case e_div: return e->value * (d / d2);
  163. case e_add: return e->value * (d + d2);
  164. case e_last:return e->value * d2;
  165. case e_st : return e->value * (p->var[av_clip(d, 0, VARS-1)]= d2);
  166. }
  167. }
  168. }
  169. return NAN;
  170. }
  171. static AVEvalExpr * parse_expr(Parser *p);
  172. void ff_eval_free(AVEvalExpr * e) {
  173. if (!e) return;
  174. ff_eval_free(e->param[0]);
  175. ff_eval_free(e->param[1]);
  176. av_freep(&e);
  177. }
  178. static AVEvalExpr * parse_primary(Parser *p) {
  179. AVEvalExpr * d = av_mallocz(sizeof(AVEvalExpr));
  180. char *next= p->s;
  181. int i;
  182. /* number */
  183. d->value = av_strtod(p->s, &next);
  184. if(next != p->s){
  185. d->type = e_value;
  186. p->s= next;
  187. return d;
  188. }
  189. d->value = 1;
  190. /* named constants */
  191. for(i=0; p->const_name && p->const_name[i]; i++){
  192. if(strmatch(p->s, p->const_name[i])){
  193. p->s+= strlen(p->const_name[i]);
  194. d->type = e_const;
  195. d->a.const_index = i;
  196. return d;
  197. }
  198. }
  199. p->s= strchr(p->s, '(');
  200. if(p->s==NULL){
  201. *p->error = "undefined constant or missing (";
  202. p->s= next;
  203. ff_eval_free(d);
  204. return NULL;
  205. }
  206. p->s++; // "("
  207. if (*next == '(') { // special case do-nothing
  208. av_freep(&d);
  209. d = parse_expr(p);
  210. if(p->s[0] != ')'){
  211. *p->error = "missing )";
  212. ff_eval_free(d);
  213. return NULL;
  214. }
  215. p->s++; // ")"
  216. return d;
  217. }
  218. d->param[0] = parse_expr(p);
  219. if(p->s[0]== ','){
  220. p->s++; // ","
  221. d->param[1] = parse_expr(p);
  222. }
  223. if(p->s[0] != ')'){
  224. *p->error = "missing )";
  225. ff_eval_free(d);
  226. return NULL;
  227. }
  228. p->s++; // ")"
  229. d->type = e_func0;
  230. if( strmatch(next, "sinh" ) ) d->a.func0 = sinh;
  231. else if( strmatch(next, "cosh" ) ) d->a.func0 = cosh;
  232. else if( strmatch(next, "tanh" ) ) d->a.func0 = tanh;
  233. else if( strmatch(next, "sin" ) ) d->a.func0 = sin;
  234. else if( strmatch(next, "cos" ) ) d->a.func0 = cos;
  235. else if( strmatch(next, "tan" ) ) d->a.func0 = tan;
  236. else if( strmatch(next, "atan" ) ) d->a.func0 = atan;
  237. else if( strmatch(next, "asin" ) ) d->a.func0 = asin;
  238. else if( strmatch(next, "acos" ) ) d->a.func0 = acos;
  239. else if( strmatch(next, "exp" ) ) d->a.func0 = exp;
  240. else if( strmatch(next, "log" ) ) d->a.func0 = log;
  241. else if( strmatch(next, "abs" ) ) d->a.func0 = fabs;
  242. else if( strmatch(next, "squish") ) d->type = e_squish;
  243. else if( strmatch(next, "gauss" ) ) d->type = e_gauss;
  244. else if( strmatch(next, "mod" ) ) d->type = e_mod;
  245. else if( strmatch(next, "max" ) ) d->type = e_max;
  246. else if( strmatch(next, "min" ) ) d->type = e_min;
  247. else if( strmatch(next, "eq" ) ) d->type = e_eq;
  248. else if( strmatch(next, "gte" ) ) d->type = e_gte;
  249. else if( strmatch(next, "gt" ) ) d->type = e_gt;
  250. else if( strmatch(next, "lte" ) ) { AVEvalExpr * tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gt; }
  251. else if( strmatch(next, "lt" ) ) { AVEvalExpr * tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gte; }
  252. else if( strmatch(next, "ld" ) ) d->type = e_ld;
  253. else if( strmatch(next, "st" ) ) d->type = e_st;
  254. else if( strmatch(next, "while" ) ) d->type = e_while;
  255. else {
  256. for(i=0; p->func1_name && p->func1_name[i]; i++){
  257. if(strmatch(next, p->func1_name[i])){
  258. d->a.func1 = p->func1[i];
  259. d->type = e_func1;
  260. return d;
  261. }
  262. }
  263. for(i=0; p->func2_name && p->func2_name[i]; i++){
  264. if(strmatch(next, p->func2_name[i])){
  265. d->a.func2 = p->func2[i];
  266. d->type = e_func2;
  267. return d;
  268. }
  269. }
  270. *p->error = "unknown function";
  271. ff_eval_free(d);
  272. return NULL;
  273. }
  274. return d;
  275. }
  276. static AVEvalExpr * new_eval_expr(int type, int value, AVEvalExpr *p0, AVEvalExpr *p1){
  277. AVEvalExpr * e = av_mallocz(sizeof(AVEvalExpr));
  278. e->type =type ;
  279. e->value =value ;
  280. e->param[0] =p0 ;
  281. e->param[1] =p1 ;
  282. return e;
  283. }
  284. static AVEvalExpr * parse_pow(Parser *p, int *sign){
  285. *sign= (*p->s == '+') - (*p->s == '-');
  286. p->s += *sign&1;
  287. return parse_primary(p);
  288. }
  289. static AVEvalExpr * parse_factor(Parser *p){
  290. int sign, sign2;
  291. AVEvalExpr * e = parse_pow(p, &sign);
  292. while(p->s[0]=='^'){
  293. p->s++;
  294. e= new_eval_expr(e_pow, 1, e, parse_pow(p, &sign2));
  295. if (e->param[1]) e->param[1]->value *= (sign2|1);
  296. }
  297. if (e) e->value *= (sign|1);
  298. return e;
  299. }
  300. static AVEvalExpr * parse_term(Parser *p){
  301. AVEvalExpr * e = parse_factor(p);
  302. while(p->s[0]=='*' || p->s[0]=='/'){
  303. int c= *p->s++;
  304. e= new_eval_expr(c == '*' ? e_mul : e_div, 1, e, parse_factor(p));
  305. }
  306. return e;
  307. }
  308. static AVEvalExpr * parse_subexpr(Parser *p) {
  309. AVEvalExpr * e = parse_term(p);
  310. while(*p->s == '+' || *p->s == '-') {
  311. e= new_eval_expr(e_add, 1, e, parse_term(p));
  312. };
  313. return e;
  314. }
  315. static AVEvalExpr * parse_expr(Parser *p) {
  316. AVEvalExpr * e;
  317. if(p->stack_index <= 0) //protect against stack overflows
  318. return NULL;
  319. p->stack_index--;
  320. e = parse_subexpr(p);
  321. while(*p->s == ';') {
  322. p->s++;
  323. e= new_eval_expr(e_last, 1, e, parse_subexpr(p));
  324. };
  325. p->stack_index++;
  326. return e;
  327. }
  328. static int verify_expr(AVEvalExpr * e) {
  329. if (!e) return 0;
  330. switch (e->type) {
  331. case e_value:
  332. case e_const: return 1;
  333. case e_func0:
  334. case e_func1:
  335. case e_squish:
  336. case e_ld:
  337. case e_gauss: return verify_expr(e->param[0]);
  338. default: return verify_expr(e->param[0]) && verify_expr(e->param[1]);
  339. }
  340. }
  341. AVEvalExpr * ff_parse(const char *s, const char * const *const_name,
  342. double (**func1)(void *, double), const char **func1_name,
  343. double (**func2)(void *, double, double), const char **func2_name,
  344. const char **error){
  345. Parser p;
  346. AVEvalExpr * e;
  347. char w[strlen(s) + 1], * wp = w;
  348. while (*s)
  349. if (!isspace(*s++)) *wp++ = s[-1];
  350. *wp++ = 0;
  351. p.stack_index=100;
  352. p.s= w;
  353. p.const_name = const_name;
  354. p.func1 = func1;
  355. p.func1_name = func1_name;
  356. p.func2 = func2;
  357. p.func2_name = func2_name;
  358. p.error= error;
  359. e = parse_expr(&p);
  360. if (!verify_expr(e)) {
  361. ff_eval_free(e);
  362. return NULL;
  363. }
  364. return e;
  365. }
  366. double ff_parse_eval(AVEvalExpr * e, const double *const_value, void *opaque) {
  367. Parser p;
  368. p.const_value= const_value;
  369. p.opaque = opaque;
  370. return eval_expr(&p, e);
  371. }
  372. double ff_eval2(const char *s, const double *const_value, const char * const *const_name,
  373. double (**func1)(void *, double), const char **func1_name,
  374. double (**func2)(void *, double, double), const char **func2_name,
  375. void *opaque, const char **error){
  376. AVEvalExpr * e = ff_parse(s, const_name, func1, func1_name, func2, func2_name, error);
  377. double d;
  378. if (!e) return NAN;
  379. d = ff_parse_eval(e, const_value, opaque);
  380. ff_eval_free(e);
  381. return d;
  382. }
  383. #ifdef TEST
  384. #undef printf
  385. static double const_values[]={
  386. M_PI,
  387. M_E,
  388. 0
  389. };
  390. static const char *const_names[]={
  391. "PI",
  392. "E",
  393. 0
  394. };
  395. int main(void){
  396. int i;
  397. 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));
  398. printf("%f == 0.931322575\n", ff_eval2("80G/80Gi", const_values, const_names, NULL, NULL, NULL, NULL, NULL, NULL));
  399. for(i=0; i<1050; i++){
  400. START_TIMER
  401. 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);
  402. STOP_TIMER("ff_eval2")
  403. }
  404. return 0;
  405. }
  406. #endif