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.

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