You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

648 lines
19KB

  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 Libav.
  6. *
  7. * Libav 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. * Libav 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 Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * simple arithmetic expression evaluator.
  24. *
  25. * see http://joe.hotchkiss.com/programming/eval/eval.html
  26. */
  27. #include "avutil.h"
  28. #include "eval.h"
  29. #include "log.h"
  30. typedef struct Parser {
  31. const AVClass *class;
  32. int stack_index;
  33. char *s;
  34. const double *const_values;
  35. const char * const *const_names; // NULL terminated
  36. double (* const *funcs1)(void *, double a); // NULL terminated
  37. const char * const *func1_names; // NULL terminated
  38. double (* const *funcs2)(void *, double a, double b); // NULL terminated
  39. const char * const *func2_names; // NULL terminated
  40. void *opaque;
  41. int log_offset;
  42. void *log_ctx;
  43. #define VARS 10
  44. double var[VARS];
  45. } Parser;
  46. static const AVClass class = { "Eval", av_default_item_name, NULL, LIBAVUTIL_VERSION_INT, offsetof(Parser,log_offset), offsetof(Parser,log_ctx) };
  47. static const int8_t si_prefixes['z' - 'E' + 1] = {
  48. ['y'-'E']= -24,
  49. ['z'-'E']= -21,
  50. ['a'-'E']= -18,
  51. ['f'-'E']= -15,
  52. ['p'-'E']= -12,
  53. ['n'-'E']= - 9,
  54. ['u'-'E']= - 6,
  55. ['m'-'E']= - 3,
  56. ['c'-'E']= - 2,
  57. ['d'-'E']= - 1,
  58. ['h'-'E']= 2,
  59. ['k'-'E']= 3,
  60. ['K'-'E']= 3,
  61. ['M'-'E']= 6,
  62. ['G'-'E']= 9,
  63. ['T'-'E']= 12,
  64. ['P'-'E']= 15,
  65. ['E'-'E']= 18,
  66. ['Z'-'E']= 21,
  67. ['Y'-'E']= 24,
  68. };
  69. double av_strtod(const char *numstr, char **tail)
  70. {
  71. double d;
  72. char *next;
  73. d = strtod(numstr, &next);
  74. /* if parsing succeeded, check for and interpret postfixes */
  75. if (next!=numstr) {
  76. if (*next >= 'E' && *next <= 'z') {
  77. int e= si_prefixes[*next - 'E'];
  78. if (e) {
  79. if (next[1] == 'i') {
  80. d*= pow( 2, e/0.3);
  81. next+=2;
  82. } else {
  83. d*= pow(10, e);
  84. next++;
  85. }
  86. }
  87. }
  88. if (*next=='B') {
  89. d*=8;
  90. next++;
  91. }
  92. }
  93. /* if requested, fill in tail with the position after the last parsed
  94. character */
  95. if (tail)
  96. *tail = next;
  97. return d;
  98. }
  99. #define IS_IDENTIFIER_CHAR(c) ((c) - '0' <= 9U || (c) - 'a' <= 25U || (c) - 'A' <= 25U || (c) == '_')
  100. static int strmatch(const char *s, const char *prefix)
  101. {
  102. int i;
  103. for (i=0; prefix[i]; i++) {
  104. if (prefix[i] != s[i]) return 0;
  105. }
  106. /* return 1 only if the s identifier is terminated */
  107. return !IS_IDENTIFIER_CHAR(s[i]);
  108. }
  109. struct AVExpr {
  110. enum {
  111. e_value, e_const, e_func0, e_func1, e_func2,
  112. e_squish, e_gauss, e_ld, e_isnan,
  113. e_mod, e_max, e_min, e_eq, e_gt, e_gte,
  114. e_pow, e_mul, e_div, e_add,
  115. e_last, e_st, e_while, e_floor, e_ceil, e_trunc,
  116. e_sqrt, e_not,
  117. } type;
  118. double value; // is sign in other types
  119. union {
  120. int const_index;
  121. double (*func0)(double);
  122. double (*func1)(void *, double);
  123. double (*func2)(void *, double, double);
  124. } a;
  125. struct AVExpr *param[2];
  126. };
  127. static double eval_expr(Parser *p, AVExpr *e)
  128. {
  129. switch (e->type) {
  130. case e_value: return e->value;
  131. case e_const: return e->value * p->const_values[e->a.const_index];
  132. case e_func0: return e->value * e->a.func0(eval_expr(p, e->param[0]));
  133. case e_func1: return e->value * e->a.func1(p->opaque, eval_expr(p, e->param[0]));
  134. case e_func2: return e->value * e->a.func2(p->opaque, eval_expr(p, e->param[0]), eval_expr(p, e->param[1]));
  135. case e_squish: return 1/(1+exp(4*eval_expr(p, e->param[0])));
  136. case e_gauss: { double d = eval_expr(p, e->param[0]); return exp(-d*d/2)/sqrt(2*M_PI); }
  137. case e_ld: return e->value * p->var[av_clip(eval_expr(p, e->param[0]), 0, VARS-1)];
  138. case e_isnan: return e->value * !!isnan(eval_expr(p, e->param[0]));
  139. case e_floor: return e->value * floor(eval_expr(p, e->param[0]));
  140. case e_ceil : return e->value * ceil (eval_expr(p, e->param[0]));
  141. case e_trunc: return e->value * trunc(eval_expr(p, e->param[0]));
  142. case e_sqrt: return e->value * sqrt (eval_expr(p, e->param[0]));
  143. case e_not: return e->value * eval_expr(p, e->param[0]) == 0;
  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 int parse_expr(AVExpr **e, Parser *p);
  172. void av_expr_free(AVExpr *e)
  173. {
  174. if (!e) return;
  175. av_expr_free(e->param[0]);
  176. av_expr_free(e->param[1]);
  177. av_freep(&e);
  178. }
  179. static int parse_primary(AVExpr **e, Parser *p)
  180. {
  181. AVExpr *d = av_mallocz(sizeof(AVExpr));
  182. char *next = p->s, *s0 = p->s;
  183. int ret, i;
  184. if (!d)
  185. return AVERROR(ENOMEM);
  186. /* number */
  187. d->value = av_strtod(p->s, &next);
  188. if (next != p->s) {
  189. d->type = e_value;
  190. p->s= next;
  191. *e = d;
  192. return 0;
  193. }
  194. d->value = 1;
  195. /* named constants */
  196. for (i=0; p->const_names && p->const_names[i]; i++) {
  197. if (strmatch(p->s, p->const_names[i])) {
  198. p->s+= strlen(p->const_names[i]);
  199. d->type = e_const;
  200. d->a.const_index = i;
  201. *e = d;
  202. return 0;
  203. }
  204. }
  205. p->s= strchr(p->s, '(');
  206. if (p->s==NULL) {
  207. av_log(p, AV_LOG_ERROR, "Undefined constant or missing '(' in '%s'\n", s0);
  208. p->s= next;
  209. av_expr_free(d);
  210. return AVERROR(EINVAL);
  211. }
  212. p->s++; // "("
  213. if (*next == '(') { // special case do-nothing
  214. av_freep(&d);
  215. if ((ret = parse_expr(&d, p)) < 0)
  216. return ret;
  217. if (p->s[0] != ')') {
  218. av_log(p, AV_LOG_ERROR, "Missing ')' in '%s'\n", s0);
  219. av_expr_free(d);
  220. return AVERROR(EINVAL);
  221. }
  222. p->s++; // ")"
  223. *e = d;
  224. return 0;
  225. }
  226. if ((ret = parse_expr(&(d->param[0]), p)) < 0) {
  227. av_expr_free(d);
  228. return ret;
  229. }
  230. if (p->s[0]== ',') {
  231. p->s++; // ","
  232. parse_expr(&d->param[1], p);
  233. }
  234. if (p->s[0] != ')') {
  235. av_log(p, AV_LOG_ERROR, "Missing ')' or too many args in '%s'\n", s0);
  236. av_expr_free(d);
  237. return AVERROR(EINVAL);
  238. }
  239. p->s++; // ")"
  240. d->type = e_func0;
  241. if (strmatch(next, "sinh" )) d->a.func0 = sinh;
  242. else if (strmatch(next, "cosh" )) d->a.func0 = cosh;
  243. else if (strmatch(next, "tanh" )) d->a.func0 = tanh;
  244. else if (strmatch(next, "sin" )) d->a.func0 = sin;
  245. else if (strmatch(next, "cos" )) d->a.func0 = cos;
  246. else if (strmatch(next, "tan" )) d->a.func0 = tan;
  247. else if (strmatch(next, "atan" )) d->a.func0 = atan;
  248. else if (strmatch(next, "asin" )) d->a.func0 = asin;
  249. else if (strmatch(next, "acos" )) d->a.func0 = acos;
  250. else if (strmatch(next, "exp" )) d->a.func0 = exp;
  251. else if (strmatch(next, "log" )) d->a.func0 = log;
  252. else if (strmatch(next, "abs" )) d->a.func0 = fabs;
  253. else if (strmatch(next, "squish")) d->type = e_squish;
  254. else if (strmatch(next, "gauss" )) d->type = e_gauss;
  255. else if (strmatch(next, "mod" )) d->type = e_mod;
  256. else if (strmatch(next, "max" )) d->type = e_max;
  257. else if (strmatch(next, "min" )) d->type = e_min;
  258. else if (strmatch(next, "eq" )) d->type = e_eq;
  259. else if (strmatch(next, "gte" )) d->type = e_gte;
  260. else if (strmatch(next, "gt" )) d->type = e_gt;
  261. else if (strmatch(next, "lte" )) { AVExpr *tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gt; }
  262. else if (strmatch(next, "lt" )) { AVExpr *tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gte; }
  263. else if (strmatch(next, "ld" )) d->type = e_ld;
  264. else if (strmatch(next, "isnan" )) d->type = e_isnan;
  265. else if (strmatch(next, "st" )) d->type = e_st;
  266. else if (strmatch(next, "while" )) d->type = e_while;
  267. else if (strmatch(next, "floor" )) d->type = e_floor;
  268. else if (strmatch(next, "ceil" )) d->type = e_ceil;
  269. else if (strmatch(next, "trunc" )) d->type = e_trunc;
  270. else if (strmatch(next, "sqrt" )) d->type = e_sqrt;
  271. else if (strmatch(next, "not" )) d->type = e_not;
  272. else {
  273. for (i=0; p->func1_names && p->func1_names[i]; i++) {
  274. if (strmatch(next, p->func1_names[i])) {
  275. d->a.func1 = p->funcs1[i];
  276. d->type = e_func1;
  277. *e = d;
  278. return 0;
  279. }
  280. }
  281. for (i=0; p->func2_names && p->func2_names[i]; i++) {
  282. if (strmatch(next, p->func2_names[i])) {
  283. d->a.func2 = p->funcs2[i];
  284. d->type = e_func2;
  285. *e = d;
  286. return 0;
  287. }
  288. }
  289. av_log(p, AV_LOG_ERROR, "Unknown function in '%s'\n", s0);
  290. av_expr_free(d);
  291. return AVERROR(EINVAL);
  292. }
  293. *e = d;
  294. return 0;
  295. }
  296. static AVExpr *new_eval_expr(int type, int value, AVExpr *p0, AVExpr *p1)
  297. {
  298. AVExpr *e = av_mallocz(sizeof(AVExpr));
  299. if (!e)
  300. return NULL;
  301. e->type =type ;
  302. e->value =value ;
  303. e->param[0] =p0 ;
  304. e->param[1] =p1 ;
  305. return e;
  306. }
  307. static int parse_pow(AVExpr **e, Parser *p, int *sign)
  308. {
  309. *sign= (*p->s == '+') - (*p->s == '-');
  310. p->s += *sign&1;
  311. return parse_primary(e, p);
  312. }
  313. static int parse_factor(AVExpr **e, Parser *p)
  314. {
  315. int sign, sign2, ret;
  316. AVExpr *e0, *e1, *e2;
  317. if ((ret = parse_pow(&e0, p, &sign)) < 0)
  318. return ret;
  319. while(p->s[0]=='^'){
  320. e1 = e0;
  321. p->s++;
  322. if ((ret = parse_pow(&e2, p, &sign2)) < 0) {
  323. av_expr_free(e1);
  324. return ret;
  325. }
  326. e0 = new_eval_expr(e_pow, 1, e1, e2);
  327. if (!e0) {
  328. av_expr_free(e1);
  329. av_expr_free(e2);
  330. return AVERROR(ENOMEM);
  331. }
  332. if (e0->param[1]) e0->param[1]->value *= (sign2|1);
  333. }
  334. if (e0) e0->value *= (sign|1);
  335. *e = e0;
  336. return 0;
  337. }
  338. static int parse_term(AVExpr **e, Parser *p)
  339. {
  340. int ret;
  341. AVExpr *e0, *e1, *e2;
  342. if ((ret = parse_factor(&e0, p)) < 0)
  343. return ret;
  344. while (p->s[0]=='*' || p->s[0]=='/') {
  345. int c= *p->s++;
  346. e1 = e0;
  347. if ((ret = parse_factor(&e2, p)) < 0) {
  348. av_expr_free(e1);
  349. return ret;
  350. }
  351. e0 = new_eval_expr(c == '*' ? e_mul : e_div, 1, e1, e2);
  352. if (!e0) {
  353. av_expr_free(e1);
  354. av_expr_free(e2);
  355. return AVERROR(ENOMEM);
  356. }
  357. }
  358. *e = e0;
  359. return 0;
  360. }
  361. static int parse_subexpr(AVExpr **e, Parser *p)
  362. {
  363. int ret;
  364. AVExpr *e0, *e1, *e2;
  365. if ((ret = parse_term(&e0, p)) < 0)
  366. return ret;
  367. while (*p->s == '+' || *p->s == '-') {
  368. e1 = e0;
  369. if ((ret = parse_term(&e2, p)) < 0) {
  370. av_expr_free(e1);
  371. return ret;
  372. }
  373. e0 = new_eval_expr(e_add, 1, e1, e2);
  374. if (!e0) {
  375. av_expr_free(e1);
  376. av_expr_free(e2);
  377. return AVERROR(ENOMEM);
  378. }
  379. };
  380. *e = e0;
  381. return 0;
  382. }
  383. static int parse_expr(AVExpr **e, Parser *p)
  384. {
  385. int ret;
  386. AVExpr *e0, *e1, *e2;
  387. if (p->stack_index <= 0) //protect against stack overflows
  388. return AVERROR(EINVAL);
  389. p->stack_index--;
  390. if ((ret = parse_subexpr(&e0, p)) < 0)
  391. return ret;
  392. while (*p->s == ';') {
  393. p->s++;
  394. e1 = e0;
  395. if ((ret = parse_subexpr(&e2, p)) < 0) {
  396. av_expr_free(e1);
  397. return ret;
  398. }
  399. e0 = new_eval_expr(e_last, 1, e1, e2);
  400. if (!e0) {
  401. av_expr_free(e1);
  402. av_expr_free(e2);
  403. return AVERROR(ENOMEM);
  404. }
  405. };
  406. p->stack_index++;
  407. *e = e0;
  408. return 0;
  409. }
  410. static int verify_expr(AVExpr *e)
  411. {
  412. if (!e) return 0;
  413. switch (e->type) {
  414. case e_value:
  415. case e_const: return 1;
  416. case e_func0:
  417. case e_func1:
  418. case e_squish:
  419. case e_ld:
  420. case e_gauss:
  421. case e_isnan:
  422. case e_floor:
  423. case e_ceil:
  424. case e_trunc:
  425. case e_sqrt:
  426. case e_not:
  427. return verify_expr(e->param[0]);
  428. default: return verify_expr(e->param[0]) && verify_expr(e->param[1]);
  429. }
  430. }
  431. int av_expr_parse(AVExpr **expr, const char *s,
  432. const char * const *const_names,
  433. const char * const *func1_names, double (* const *funcs1)(void *, double),
  434. const char * const *func2_names, double (* const *funcs2)(void *, double, double),
  435. int log_offset, void *log_ctx)
  436. {
  437. Parser p = { 0 };
  438. AVExpr *e = NULL;
  439. char *w = av_malloc(strlen(s) + 1);
  440. char *wp = w;
  441. const char *s0 = s;
  442. int ret = 0;
  443. if (!w)
  444. return AVERROR(ENOMEM);
  445. while (*s)
  446. if (!isspace(*s++)) *wp++ = s[-1];
  447. *wp++ = 0;
  448. p.class = &class;
  449. p.stack_index=100;
  450. p.s= w;
  451. p.const_names = const_names;
  452. p.funcs1 = funcs1;
  453. p.func1_names = func1_names;
  454. p.funcs2 = funcs2;
  455. p.func2_names = func2_names;
  456. p.log_offset = log_offset;
  457. p.log_ctx = log_ctx;
  458. if ((ret = parse_expr(&e, &p)) < 0)
  459. goto end;
  460. if (*p.s) {
  461. av_expr_free(e);
  462. av_log(&p, AV_LOG_ERROR, "Invalid chars '%s' at the end of expression '%s'\n", p.s, s0);
  463. ret = AVERROR(EINVAL);
  464. goto end;
  465. }
  466. if (!verify_expr(e)) {
  467. av_expr_free(e);
  468. ret = AVERROR(EINVAL);
  469. goto end;
  470. }
  471. *expr = e;
  472. end:
  473. av_free(w);
  474. return ret;
  475. }
  476. double av_expr_eval(AVExpr *e, const double *const_values, void *opaque)
  477. {
  478. Parser p = { 0 };
  479. p.const_values = const_values;
  480. p.opaque = opaque;
  481. return eval_expr(&p, e);
  482. }
  483. int av_expr_parse_and_eval(double *d, const char *s,
  484. const char * const *const_names, const double *const_values,
  485. const char * const *func1_names, double (* const *funcs1)(void *, double),
  486. const char * const *func2_names, double (* const *funcs2)(void *, double, double),
  487. void *opaque, int log_offset, void *log_ctx)
  488. {
  489. AVExpr *e = NULL;
  490. int ret = av_expr_parse(&e, s, const_names, func1_names, funcs1, func2_names, funcs2, log_offset, log_ctx);
  491. if (ret < 0) {
  492. *d = NAN;
  493. return ret;
  494. }
  495. *d = av_expr_eval(e, const_values, opaque);
  496. av_expr_free(e);
  497. return isnan(*d) ? AVERROR(EINVAL) : 0;
  498. }
  499. #ifdef TEST
  500. #undef printf
  501. #include <string.h>
  502. static const double const_values[] = {
  503. M_PI,
  504. M_E,
  505. 0
  506. };
  507. static const char *const const_names[] = {
  508. "PI",
  509. "E",
  510. 0
  511. };
  512. int main(int argc, char **argv)
  513. {
  514. int i;
  515. double d;
  516. const char **expr, *exprs[] = {
  517. "",
  518. "1;2",
  519. "-20",
  520. "-PI",
  521. "+PI",
  522. "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)",
  523. "80G/80Gi",
  524. "1k",
  525. "1Gi",
  526. "1gi",
  527. "1GiFoo",
  528. "1k+1k",
  529. "1Gi*3foo",
  530. "foo",
  531. "foo(",
  532. "foo()",
  533. "foo)",
  534. "sin",
  535. "sin(",
  536. "sin()",
  537. "sin)",
  538. "sin 10",
  539. "sin(1,2,3)",
  540. "sin(1 )",
  541. "1",
  542. "1foo",
  543. "bar + PI + E + 100f*2 + foo",
  544. "13k + 12f - foo(1, 2)",
  545. "1gi",
  546. "1Gi",
  547. "st(0, 123)",
  548. "st(1, 123); ld(1)",
  549. /* compute 1+2+...+N */
  550. "st(0, 1); while(lte(ld(0), 100), st(1, ld(1)+ld(0));st(0, ld(0)+1)); ld(1)",
  551. /* compute Fib(N) */
  552. "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)",
  553. "while(0, 10)",
  554. "st(0, 1); while(lte(ld(0),100), st(1, ld(1)+ld(0)); st(0, ld(0)+1))",
  555. "isnan(1)",
  556. "isnan(NAN)",
  557. "floor(NAN)",
  558. "floor(123.123)",
  559. "floor(-123.123)",
  560. "trunc(123.123)",
  561. "trunc(-123.123)",
  562. "ceil(123.123)",
  563. "ceil(-123.123)",
  564. "sqrt(1764)",
  565. "isnan(sqrt(-1))",
  566. "not(1)",
  567. "not(NAN)",
  568. "not(0)",
  569. NULL
  570. };
  571. for (expr = exprs; *expr; expr++) {
  572. printf("Evaluating '%s'\n", *expr);
  573. av_expr_parse_and_eval(&d, *expr,
  574. const_names, const_values,
  575. NULL, NULL, NULL, NULL, NULL, 0, NULL);
  576. printf("'%s' -> %f\n\n", *expr, d);
  577. }
  578. av_expr_parse_and_eval(&d, "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)",
  579. const_names, const_values,
  580. NULL, NULL, NULL, NULL, NULL, 0, NULL);
  581. printf("%f == 12.7\n", d);
  582. av_expr_parse_and_eval(&d, "80G/80Gi",
  583. const_names, const_values,
  584. NULL, NULL, NULL, NULL, NULL, 0, NULL);
  585. printf("%f == 0.931322575\n", d);
  586. if (argc > 1 && !strcmp(argv[1], "-t")) {
  587. for (i = 0; i < 1050; i++) {
  588. START_TIMER;
  589. av_expr_parse_and_eval(&d, "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)",
  590. const_names, const_values,
  591. NULL, NULL, NULL, NULL, NULL, 0, NULL);
  592. STOP_TIMER("av_expr_parse_and_eval");
  593. }
  594. }
  595. return 0;
  596. }
  597. #endif