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.

636 lines
18KB

  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. } type;
  117. double value; // is sign in other types
  118. union {
  119. int const_index;
  120. double (*func0)(double);
  121. double (*func1)(void *, double);
  122. double (*func2)(void *, double, double);
  123. } a;
  124. struct AVExpr *param[2];
  125. };
  126. static double eval_expr(Parser *p, AVExpr *e)
  127. {
  128. switch (e->type) {
  129. case e_value: return e->value;
  130. case e_const: return e->value * p->const_values[e->a.const_index];
  131. case e_func0: return e->value * e->a.func0(eval_expr(p, e->param[0]));
  132. case e_func1: return e->value * e->a.func1(p->opaque, eval_expr(p, e->param[0]));
  133. case e_func2: return e->value * e->a.func2(p->opaque, eval_expr(p, e->param[0]), eval_expr(p, e->param[1]));
  134. case e_squish: return 1/(1+exp(4*eval_expr(p, e->param[0])));
  135. case e_gauss: { double d = eval_expr(p, e->param[0]); return exp(-d*d/2)/sqrt(2*M_PI); }
  136. case e_ld: return e->value * p->var[av_clip(eval_expr(p, e->param[0]), 0, VARS-1)];
  137. case e_isnan: return e->value * !!isnan(eval_expr(p, e->param[0]));
  138. case e_floor: return e->value * floor(eval_expr(p, e->param[0]));
  139. case e_ceil : return e->value * ceil (eval_expr(p, e->param[0]));
  140. case e_trunc: return e->value * trunc(eval_expr(p, e->param[0]));
  141. case e_while: {
  142. double d = NAN;
  143. while (eval_expr(p, e->param[0]))
  144. d=eval_expr(p, e->param[1]);
  145. return d;
  146. }
  147. default: {
  148. double d = eval_expr(p, e->param[0]);
  149. double d2 = eval_expr(p, e->param[1]);
  150. switch (e->type) {
  151. case e_mod: return e->value * (d - floor(d/d2)*d2);
  152. case e_max: return e->value * (d > d2 ? d : d2);
  153. case e_min: return e->value * (d < d2 ? d : d2);
  154. case e_eq: return e->value * (d == d2 ? 1.0 : 0.0);
  155. case e_gt: return e->value * (d > d2 ? 1.0 : 0.0);
  156. case e_gte: return e->value * (d >= d2 ? 1.0 : 0.0);
  157. case e_pow: return e->value * pow(d, d2);
  158. case e_mul: return e->value * (d * d2);
  159. case e_div: return e->value * (d / d2);
  160. case e_add: return e->value * (d + d2);
  161. case e_last:return e->value * d2;
  162. case e_st : return e->value * (p->var[av_clip(d, 0, VARS-1)]= d2);
  163. }
  164. }
  165. }
  166. return NAN;
  167. }
  168. static int parse_expr(AVExpr **e, Parser *p);
  169. void av_expr_free(AVExpr *e)
  170. {
  171. if (!e) return;
  172. av_expr_free(e->param[0]);
  173. av_expr_free(e->param[1]);
  174. av_freep(&e);
  175. }
  176. static int parse_primary(AVExpr **e, Parser *p)
  177. {
  178. AVExpr *d = av_mallocz(sizeof(AVExpr));
  179. char *next = p->s, *s0 = p->s;
  180. int ret, i;
  181. if (!d)
  182. return AVERROR(ENOMEM);
  183. /* number */
  184. d->value = av_strtod(p->s, &next);
  185. if (next != p->s) {
  186. d->type = e_value;
  187. p->s= next;
  188. *e = d;
  189. return 0;
  190. }
  191. d->value = 1;
  192. /* named constants */
  193. for (i=0; p->const_names && p->const_names[i]; i++) {
  194. if (strmatch(p->s, p->const_names[i])) {
  195. p->s+= strlen(p->const_names[i]);
  196. d->type = e_const;
  197. d->a.const_index = i;
  198. *e = d;
  199. return 0;
  200. }
  201. }
  202. p->s= strchr(p->s, '(');
  203. if (p->s==NULL) {
  204. av_log(p, AV_LOG_ERROR, "Undefined constant or missing '(' in '%s'\n", s0);
  205. p->s= next;
  206. av_expr_free(d);
  207. return AVERROR(EINVAL);
  208. }
  209. p->s++; // "("
  210. if (*next == '(') { // special case do-nothing
  211. av_freep(&d);
  212. if ((ret = parse_expr(&d, p)) < 0)
  213. return ret;
  214. if (p->s[0] != ')') {
  215. av_log(p, AV_LOG_ERROR, "Missing ')' in '%s'\n", s0);
  216. av_expr_free(d);
  217. return AVERROR(EINVAL);
  218. }
  219. p->s++; // ")"
  220. *e = d;
  221. return 0;
  222. }
  223. if ((ret = parse_expr(&(d->param[0]), p)) < 0) {
  224. av_expr_free(d);
  225. return ret;
  226. }
  227. if (p->s[0]== ',') {
  228. p->s++; // ","
  229. parse_expr(&d->param[1], p);
  230. }
  231. if (p->s[0] != ')') {
  232. av_log(p, AV_LOG_ERROR, "Missing ')' or too many args in '%s'\n", s0);
  233. av_expr_free(d);
  234. return AVERROR(EINVAL);
  235. }
  236. p->s++; // ")"
  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, "isnan" )) d->type = e_isnan;
  262. else if (strmatch(next, "st" )) d->type = e_st;
  263. else if (strmatch(next, "while" )) d->type = e_while;
  264. else if (strmatch(next, "floor" )) d->type = e_floor;
  265. else if (strmatch(next, "ceil" )) d->type = e_ceil;
  266. else if (strmatch(next, "trunc" )) d->type = e_trunc;
  267. else {
  268. for (i=0; p->func1_names && p->func1_names[i]; i++) {
  269. if (strmatch(next, p->func1_names[i])) {
  270. d->a.func1 = p->funcs1[i];
  271. d->type = e_func1;
  272. *e = d;
  273. return 0;
  274. }
  275. }
  276. for (i=0; p->func2_names && p->func2_names[i]; i++) {
  277. if (strmatch(next, p->func2_names[i])) {
  278. d->a.func2 = p->funcs2[i];
  279. d->type = e_func2;
  280. *e = d;
  281. return 0;
  282. }
  283. }
  284. av_log(p, AV_LOG_ERROR, "Unknown function in '%s'\n", s0);
  285. av_expr_free(d);
  286. return AVERROR(EINVAL);
  287. }
  288. *e = d;
  289. return 0;
  290. }
  291. static AVExpr *new_eval_expr(int type, int value, AVExpr *p0, AVExpr *p1)
  292. {
  293. AVExpr *e = av_mallocz(sizeof(AVExpr));
  294. if (!e)
  295. return NULL;
  296. e->type =type ;
  297. e->value =value ;
  298. e->param[0] =p0 ;
  299. e->param[1] =p1 ;
  300. return e;
  301. }
  302. static int parse_pow(AVExpr **e, Parser *p, int *sign)
  303. {
  304. *sign= (*p->s == '+') - (*p->s == '-');
  305. p->s += *sign&1;
  306. return parse_primary(e, p);
  307. }
  308. static int parse_factor(AVExpr **e, Parser *p)
  309. {
  310. int sign, sign2, ret;
  311. AVExpr *e0, *e1, *e2;
  312. if ((ret = parse_pow(&e0, p, &sign)) < 0)
  313. return ret;
  314. while(p->s[0]=='^'){
  315. e1 = e0;
  316. p->s++;
  317. if ((ret = parse_pow(&e2, p, &sign2)) < 0) {
  318. av_expr_free(e1);
  319. return ret;
  320. }
  321. e0 = new_eval_expr(e_pow, 1, e1, e2);
  322. if (!e0) {
  323. av_expr_free(e1);
  324. av_expr_free(e2);
  325. return AVERROR(ENOMEM);
  326. }
  327. if (e0->param[1]) e0->param[1]->value *= (sign2|1);
  328. }
  329. if (e0) e0->value *= (sign|1);
  330. *e = e0;
  331. return 0;
  332. }
  333. static int parse_term(AVExpr **e, Parser *p)
  334. {
  335. int ret;
  336. AVExpr *e0, *e1, *e2;
  337. if ((ret = parse_factor(&e0, p)) < 0)
  338. return ret;
  339. while (p->s[0]=='*' || p->s[0]=='/') {
  340. int c= *p->s++;
  341. e1 = e0;
  342. if ((ret = parse_factor(&e2, p)) < 0) {
  343. av_expr_free(e1);
  344. return ret;
  345. }
  346. e0 = new_eval_expr(c == '*' ? e_mul : e_div, 1, e1, e2);
  347. if (!e0) {
  348. av_expr_free(e1);
  349. av_expr_free(e2);
  350. return AVERROR(ENOMEM);
  351. }
  352. }
  353. *e = e0;
  354. return 0;
  355. }
  356. static int parse_subexpr(AVExpr **e, Parser *p)
  357. {
  358. int ret;
  359. AVExpr *e0, *e1, *e2;
  360. if ((ret = parse_term(&e0, p)) < 0)
  361. return ret;
  362. while (*p->s == '+' || *p->s == '-') {
  363. e1 = e0;
  364. if ((ret = parse_term(&e2, p)) < 0) {
  365. av_expr_free(e1);
  366. return ret;
  367. }
  368. e0 = new_eval_expr(e_add, 1, e1, e2);
  369. if (!e0) {
  370. av_expr_free(e1);
  371. av_expr_free(e2);
  372. return AVERROR(ENOMEM);
  373. }
  374. };
  375. *e = e0;
  376. return 0;
  377. }
  378. static int parse_expr(AVExpr **e, Parser *p)
  379. {
  380. int ret;
  381. AVExpr *e0, *e1, *e2;
  382. if (p->stack_index <= 0) //protect against stack overflows
  383. return AVERROR(EINVAL);
  384. p->stack_index--;
  385. if ((ret = parse_subexpr(&e0, p)) < 0)
  386. return ret;
  387. while (*p->s == ';') {
  388. p->s++;
  389. e1 = e0;
  390. if ((ret = parse_subexpr(&e2, p)) < 0) {
  391. av_expr_free(e1);
  392. return ret;
  393. }
  394. e0 = new_eval_expr(e_last, 1, e1, e2);
  395. if (!e0) {
  396. av_expr_free(e1);
  397. av_expr_free(e2);
  398. return AVERROR(ENOMEM);
  399. }
  400. };
  401. p->stack_index++;
  402. *e = e0;
  403. return 0;
  404. }
  405. static int verify_expr(AVExpr *e)
  406. {
  407. if (!e) return 0;
  408. switch (e->type) {
  409. case e_value:
  410. case e_const: return 1;
  411. case e_func0:
  412. case e_func1:
  413. case e_squish:
  414. case e_ld:
  415. case e_gauss:
  416. case e_isnan:
  417. case e_floor:
  418. case e_ceil:
  419. case e_trunc:
  420. return verify_expr(e->param[0]);
  421. default: return verify_expr(e->param[0]) && verify_expr(e->param[1]);
  422. }
  423. }
  424. int av_expr_parse(AVExpr **expr, const char *s,
  425. const char * const *const_names,
  426. const char * const *func1_names, double (* const *funcs1)(void *, double),
  427. const char * const *func2_names, double (* const *funcs2)(void *, double, double),
  428. int log_offset, void *log_ctx)
  429. {
  430. Parser p = { 0 };
  431. AVExpr *e = NULL;
  432. char *w = av_malloc(strlen(s) + 1);
  433. char *wp = w;
  434. const char *s0 = s;
  435. int ret = 0;
  436. if (!w)
  437. return AVERROR(ENOMEM);
  438. while (*s)
  439. if (!isspace(*s++)) *wp++ = s[-1];
  440. *wp++ = 0;
  441. p.class = &class;
  442. p.stack_index=100;
  443. p.s= w;
  444. p.const_names = const_names;
  445. p.funcs1 = funcs1;
  446. p.func1_names = func1_names;
  447. p.funcs2 = funcs2;
  448. p.func2_names = func2_names;
  449. p.log_offset = log_offset;
  450. p.log_ctx = log_ctx;
  451. if ((ret = parse_expr(&e, &p)) < 0)
  452. goto end;
  453. if (*p.s) {
  454. av_expr_free(e);
  455. av_log(&p, AV_LOG_ERROR, "Invalid chars '%s' at the end of expression '%s'\n", p.s, s0);
  456. ret = AVERROR(EINVAL);
  457. goto end;
  458. }
  459. if (!verify_expr(e)) {
  460. av_expr_free(e);
  461. ret = AVERROR(EINVAL);
  462. goto end;
  463. }
  464. *expr = e;
  465. end:
  466. av_free(w);
  467. return ret;
  468. }
  469. double av_expr_eval(AVExpr *e, const double *const_values, void *opaque)
  470. {
  471. Parser p = { 0 };
  472. p.const_values = const_values;
  473. p.opaque = opaque;
  474. return eval_expr(&p, e);
  475. }
  476. int av_expr_parse_and_eval(double *d, const char *s,
  477. const char * const *const_names, const double *const_values,
  478. const char * const *func1_names, double (* const *funcs1)(void *, double),
  479. const char * const *func2_names, double (* const *funcs2)(void *, double, double),
  480. void *opaque, int log_offset, void *log_ctx)
  481. {
  482. AVExpr *e = NULL;
  483. int ret = av_expr_parse(&e, s, const_names, func1_names, funcs1, func2_names, funcs2, log_offset, log_ctx);
  484. if (ret < 0) {
  485. *d = NAN;
  486. return ret;
  487. }
  488. *d = av_expr_eval(e, const_values, opaque);
  489. av_expr_free(e);
  490. return isnan(*d) ? AVERROR(EINVAL) : 0;
  491. }
  492. #ifdef TEST
  493. #undef printf
  494. #include <string.h>
  495. static double const_values[] = {
  496. M_PI,
  497. M_E,
  498. 0
  499. };
  500. static const char *const_names[] = {
  501. "PI",
  502. "E",
  503. 0
  504. };
  505. int main(int argc, char **argv)
  506. {
  507. int i;
  508. double d;
  509. const char **expr, *exprs[] = {
  510. "",
  511. "1;2",
  512. "-20",
  513. "-PI",
  514. "+PI",
  515. "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)",
  516. "80G/80Gi",
  517. "1k",
  518. "1Gi",
  519. "1gi",
  520. "1GiFoo",
  521. "1k+1k",
  522. "1Gi*3foo",
  523. "foo",
  524. "foo(",
  525. "foo()",
  526. "foo)",
  527. "sin",
  528. "sin(",
  529. "sin()",
  530. "sin)",
  531. "sin 10",
  532. "sin(1,2,3)",
  533. "sin(1 )",
  534. "1",
  535. "1foo",
  536. "bar + PI + E + 100f*2 + foo",
  537. "13k + 12f - foo(1, 2)",
  538. "1gi",
  539. "1Gi",
  540. "st(0, 123)",
  541. "st(1, 123); ld(1)",
  542. /* compute 1+2+...+N */
  543. "st(0, 1); while(lte(ld(0), 100), st(1, ld(1)+ld(0));st(0, ld(0)+1)); ld(1)",
  544. /* compute Fib(N) */
  545. "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)",
  546. "while(0, 10)",
  547. "st(0, 1); while(lte(ld(0),100), st(1, ld(1)+ld(0)); st(0, ld(0)+1))",
  548. "isnan(1)",
  549. "isnan(NAN)",
  550. "floor(NAN)",
  551. "floor(123.123)",
  552. "floor(-123.123)",
  553. "trunc(123.123)",
  554. "trunc(-123.123)",
  555. "ceil(123.123)",
  556. "ceil(-123.123)",
  557. NULL
  558. };
  559. for (expr = exprs; *expr; expr++) {
  560. printf("Evaluating '%s'\n", *expr);
  561. av_expr_parse_and_eval(&d, *expr,
  562. const_names, const_values,
  563. NULL, NULL, NULL, NULL, NULL, 0, NULL);
  564. printf("'%s' -> %f\n\n", *expr, d);
  565. }
  566. av_expr_parse_and_eval(&d, "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)",
  567. const_names, const_values,
  568. NULL, NULL, NULL, NULL, NULL, 0, NULL);
  569. printf("%f == 12.7\n", d);
  570. av_expr_parse_and_eval(&d, "80G/80Gi",
  571. const_names, const_values,
  572. NULL, NULL, NULL, NULL, NULL, 0, NULL);
  573. printf("%f == 0.931322575\n", d);
  574. if (argc > 1 && !strcmp(argv[1], "-t")) {
  575. for (i = 0; i < 1050; i++) {
  576. START_TIMER;
  577. av_expr_parse_and_eval(&d, "1+(5-2)^(3-1)+1/2+sin(PI)-max(-2.2,-3.1)",
  578. const_names, const_values,
  579. NULL, NULL, NULL, NULL, NULL, 0, NULL);
  580. STOP_TIMER("av_expr_parse_and_eval");
  581. }
  582. }
  583. return 0;
  584. }
  585. #endif