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.

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