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.

607 lines
17KB

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