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.

482 lines
18KB

  1. /*
  2. * Copyright (c) Stefano Sabatini 2010
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. /**
  21. * @file
  22. * life video source, based on John Conways' Life Game
  23. */
  24. /* #define DEBUG */
  25. #include "libavutil/file.h"
  26. #include "libavutil/intreadwrite.h"
  27. #include "libavutil/lfg.h"
  28. #include "libavutil/opt.h"
  29. #include "libavutil/parseutils.h"
  30. #include "libavutil/random_seed.h"
  31. #include "libavutil/avstring.h"
  32. #include "avfilter.h"
  33. #include "internal.h"
  34. #include "formats.h"
  35. #include "video.h"
  36. typedef struct {
  37. const AVClass *class;
  38. int w, h;
  39. char *filename;
  40. char *rule_str;
  41. uint8_t *file_buf;
  42. size_t file_bufsize;
  43. /**
  44. * The two grid state buffers.
  45. *
  46. * A 0xFF (ALIVE_CELL) value means the cell is alive (or new born), while
  47. * the decreasing values from 0xFE to 0 means the cell is dead; the range
  48. * of values is used for the slow death effect, or mold (0xFE means dead,
  49. * 0xFD means very dead, 0xFC means very very dead... and 0x00 means
  50. * definitely dead/mold).
  51. */
  52. uint8_t *buf[2];
  53. uint8_t buf_idx;
  54. uint16_t stay_rule; ///< encode the behavior for filled cells
  55. uint16_t born_rule; ///< encode the behavior for empty cells
  56. uint64_t pts;
  57. AVRational time_base;
  58. char *rate; ///< video frame rate
  59. double random_fill_ratio;
  60. uint32_t random_seed;
  61. int stitch;
  62. int mold;
  63. char *life_color_str;
  64. char *death_color_str;
  65. char *mold_color_str;
  66. uint8_t life_color[4];
  67. uint8_t death_color[4];
  68. uint8_t mold_color[4];
  69. AVLFG lfg;
  70. void (*draw)(AVFilterContext*, AVFrame*);
  71. } LifeContext;
  72. #define ALIVE_CELL 0xFF
  73. #define OFFSET(x) offsetof(LifeContext, x)
  74. #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
  75. static const AVOption life_options[] = {
  76. { "filename", "set source file", OFFSET(filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
  77. { "f", "set source file", OFFSET(filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
  78. { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, FLAGS },
  79. { "s", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, FLAGS },
  80. { "rate", "set video rate", OFFSET(rate), AV_OPT_TYPE_STRING, {.str = "25"}, 0, 0, FLAGS },
  81. { "r", "set video rate", OFFSET(rate), AV_OPT_TYPE_STRING, {.str = "25"}, 0, 0, FLAGS },
  82. { "rule", "set rule", OFFSET(rule_str), AV_OPT_TYPE_STRING, {.str = "B3/S23"}, CHAR_MIN, CHAR_MAX, FLAGS },
  83. { "random_fill_ratio", "set fill ratio for filling initial grid randomly", OFFSET(random_fill_ratio), AV_OPT_TYPE_DOUBLE, {.dbl=1/M_PHI}, 0, 1, FLAGS },
  84. { "ratio", "set fill ratio for filling initial grid randomly", OFFSET(random_fill_ratio), AV_OPT_TYPE_DOUBLE, {.dbl=1/M_PHI}, 0, 1, FLAGS },
  85. { "random_seed", "set the seed for filling the initial grid randomly", OFFSET(random_seed), AV_OPT_TYPE_INT, {.i64=-1}, -1, UINT32_MAX, FLAGS },
  86. { "seed", "set the seed for filling the initial grid randomly", OFFSET(random_seed), AV_OPT_TYPE_INT, {.i64=-1}, -1, UINT32_MAX, FLAGS },
  87. { "stitch", "stitch boundaries", OFFSET(stitch), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, FLAGS },
  88. { "mold", "set mold speed for dead cells", OFFSET(mold), AV_OPT_TYPE_INT, {.i64=0}, 0, 0xFF, FLAGS },
  89. { "life_color", "set life color", OFFSET( life_color_str), AV_OPT_TYPE_STRING, {.str="white"}, CHAR_MIN, CHAR_MAX, FLAGS },
  90. { "death_color", "set death color", OFFSET(death_color_str), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS },
  91. { "mold_color", "set mold color", OFFSET( mold_color_str), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS },
  92. { NULL },
  93. };
  94. AVFILTER_DEFINE_CLASS(life);
  95. static int parse_rule(uint16_t *born_rule, uint16_t *stay_rule,
  96. const char *rule_str, void *log_ctx)
  97. {
  98. char *tail;
  99. const char *p = rule_str;
  100. *born_rule = 0;
  101. *stay_rule = 0;
  102. if (strchr("bBsS", *p)) {
  103. /* parse rule as a Born / Stay Alive code, see
  104. * http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life */
  105. do {
  106. uint16_t *rule = (*p == 'b' || *p == 'B') ? born_rule : stay_rule;
  107. p++;
  108. while (*p >= '0' && *p <= '8') {
  109. *rule += 1<<(*p - '0');
  110. p++;
  111. }
  112. if (*p != '/')
  113. break;
  114. p++;
  115. } while (strchr("bBsS", *p));
  116. if (*p)
  117. goto error;
  118. } else {
  119. /* parse rule as a number, expressed in the form STAY|(BORN<<9),
  120. * where STAY and BORN encode the corresponding 9-bits rule */
  121. long int rule = strtol(rule_str, &tail, 10);
  122. if (*tail)
  123. goto error;
  124. *born_rule = ((1<<9)-1) & rule;
  125. *stay_rule = rule >> 9;
  126. }
  127. return 0;
  128. error:
  129. av_log(log_ctx, AV_LOG_ERROR, "Invalid rule code '%s' provided\n", rule_str);
  130. return AVERROR(EINVAL);
  131. }
  132. #ifdef DEBUG
  133. static void show_life_grid(AVFilterContext *ctx)
  134. {
  135. LifeContext *life = ctx->priv;
  136. int i, j;
  137. char *line = av_malloc(life->w + 1);
  138. if (!line)
  139. return;
  140. for (i = 0; i < life->h; i++) {
  141. for (j = 0; j < life->w; j++)
  142. line[j] = life->buf[life->buf_idx][i*life->w + j] == ALIVE_CELL ? '@' : ' ';
  143. line[j] = 0;
  144. av_log(ctx, AV_LOG_DEBUG, "%3d: %s\n", i, line);
  145. }
  146. av_free(line);
  147. }
  148. #endif
  149. static int init_pattern_from_file(AVFilterContext *ctx)
  150. {
  151. LifeContext *life = ctx->priv;
  152. char *p;
  153. int ret, i, i0, j, h = 0, w, max_w = 0;
  154. if ((ret = av_file_map(life->filename, &life->file_buf, &life->file_bufsize,
  155. 0, ctx)) < 0)
  156. return ret;
  157. av_freep(&life->filename);
  158. /* prescan file to get the number of lines and the maximum width */
  159. w = 0;
  160. for (i = 0; i < life->file_bufsize; i++) {
  161. if (life->file_buf[i] == '\n') {
  162. h++; max_w = FFMAX(w, max_w); w = 0;
  163. } else {
  164. w++;
  165. }
  166. }
  167. av_log(ctx, AV_LOG_DEBUG, "h:%d max_w:%d\n", h, max_w);
  168. if (life->w) {
  169. if (max_w > life->w || h > life->h) {
  170. av_log(ctx, AV_LOG_ERROR,
  171. "The specified size is %dx%d which cannot contain the provided file size of %dx%d\n",
  172. life->w, life->h, max_w, h);
  173. return AVERROR(EINVAL);
  174. }
  175. } else {
  176. /* size was not specified, set it to size of the grid */
  177. life->w = max_w;
  178. life->h = h;
  179. }
  180. if (!(life->buf[0] = av_mallocz(sizeof(char) * life->h * life->w)) ||
  181. !(life->buf[1] = av_mallocz(sizeof(char) * life->h * life->w))) {
  182. av_free(life->buf[0]);
  183. av_free(life->buf[1]);
  184. return AVERROR(ENOMEM);
  185. }
  186. /* fill buf[0] */
  187. p = life->file_buf;
  188. for (i0 = 0, i = (life->h - h)/2; i0 < h; i0++, i++) {
  189. for (j = (life->w - max_w)/2;; j++) {
  190. av_log(ctx, AV_LOG_DEBUG, "%d:%d %c\n", i, j, *p == '\n' ? 'N' : *p);
  191. if (*p == '\n') {
  192. p++; break;
  193. } else
  194. life->buf[0][i*life->w + j] = av_isgraph(*(p++)) ? ALIVE_CELL : 0;
  195. }
  196. }
  197. life->buf_idx = 0;
  198. return 0;
  199. }
  200. static int init(AVFilterContext *ctx, const char *args)
  201. {
  202. LifeContext *life = ctx->priv;
  203. AVRational frame_rate;
  204. int ret;
  205. life->class = &life_class;
  206. av_opt_set_defaults(life);
  207. if ((ret = av_set_options_string(life, args, "=", ":")) < 0)
  208. return ret;
  209. if ((ret = av_parse_video_rate(&frame_rate, life->rate)) < 0) {
  210. av_log(ctx, AV_LOG_ERROR, "Invalid frame rate: %s\n", life->rate);
  211. return AVERROR(EINVAL);
  212. }
  213. av_freep(&life->rate);
  214. if (!life->w && !life->filename)
  215. av_opt_set(life, "size", "320x240", 0);
  216. if ((ret = parse_rule(&life->born_rule, &life->stay_rule, life->rule_str, ctx)) < 0)
  217. return ret;
  218. #define PARSE_COLOR(name) do { \
  219. if ((ret = av_parse_color(life->name ## _color, life->name ## _color_str, -1, ctx))) { \
  220. av_log(ctx, AV_LOG_ERROR, "Invalid " #name " color '%s'\n", \
  221. life->name ## _color_str); \
  222. return ret; \
  223. } \
  224. av_freep(&life->name ## _color_str); \
  225. } while (0)
  226. PARSE_COLOR(life);
  227. PARSE_COLOR(death);
  228. PARSE_COLOR(mold);
  229. if (!life->mold && memcmp(life->mold_color, "\x00\x00\x00", 3))
  230. av_log(ctx, AV_LOG_WARNING,
  231. "Mold color is set while mold isn't, ignoring the color.\n");
  232. life->time_base.num = frame_rate.den;
  233. life->time_base.den = frame_rate.num;
  234. if (!life->filename) {
  235. /* fill the grid randomly */
  236. int i;
  237. if (!(life->buf[0] = av_mallocz(sizeof(char) * life->h * life->w)) ||
  238. !(life->buf[1] = av_mallocz(sizeof(char) * life->h * life->w))) {
  239. av_free(life->buf[0]);
  240. av_free(life->buf[1]);
  241. return AVERROR(ENOMEM);
  242. }
  243. if (life->random_seed == -1)
  244. life->random_seed = av_get_random_seed();
  245. av_lfg_init(&life->lfg, life->random_seed);
  246. for (i = 0; i < life->w * life->h; i++) {
  247. double r = (double)av_lfg_get(&life->lfg) / UINT32_MAX;
  248. if (r <= life->random_fill_ratio)
  249. life->buf[0][i] = ALIVE_CELL;
  250. }
  251. life->buf_idx = 0;
  252. } else {
  253. if ((ret = init_pattern_from_file(ctx)) < 0)
  254. return ret;
  255. }
  256. av_log(ctx, AV_LOG_VERBOSE,
  257. "s:%dx%d r:%d/%d rule:%s stay_rule:%d born_rule:%d stitch:%d seed:%u\n",
  258. life->w, life->h, frame_rate.num, frame_rate.den,
  259. life->rule_str, life->stay_rule, life->born_rule, life->stitch,
  260. life->random_seed);
  261. return 0;
  262. }
  263. static av_cold void uninit(AVFilterContext *ctx)
  264. {
  265. LifeContext *life = ctx->priv;
  266. av_file_unmap(life->file_buf, life->file_bufsize);
  267. av_freep(&life->rule_str);
  268. av_freep(&life->buf[0]);
  269. av_freep(&life->buf[1]);
  270. }
  271. static int config_props(AVFilterLink *outlink)
  272. {
  273. LifeContext *life = outlink->src->priv;
  274. outlink->w = life->w;
  275. outlink->h = life->h;
  276. outlink->time_base = life->time_base;
  277. return 0;
  278. }
  279. static void evolve(AVFilterContext *ctx)
  280. {
  281. LifeContext *life = ctx->priv;
  282. int i, j;
  283. uint8_t *oldbuf = life->buf[ life->buf_idx];
  284. uint8_t *newbuf = life->buf[!life->buf_idx];
  285. enum { NW, N, NE, W, E, SW, S, SE };
  286. /* evolve the grid */
  287. for (i = 0; i < life->h; i++) {
  288. for (j = 0; j < life->w; j++) {
  289. int pos[8][2], n, alive, cell;
  290. if (life->stitch) {
  291. pos[NW][0] = (i-1) < 0 ? life->h-1 : i-1; pos[NW][1] = (j-1) < 0 ? life->w-1 : j-1;
  292. pos[N ][0] = (i-1) < 0 ? life->h-1 : i-1; pos[N ][1] = j ;
  293. pos[NE][0] = (i-1) < 0 ? life->h-1 : i-1; pos[NE][1] = (j+1) == life->w ? 0 : j+1;
  294. pos[W ][0] = i ; pos[W ][1] = (j-1) < 0 ? life->w-1 : j-1;
  295. pos[E ][0] = i ; pos[E ][1] = (j+1) == life->w ? 0 : j+1;
  296. pos[SW][0] = (i+1) == life->h ? 0 : i+1; pos[SW][1] = (j-1) < 0 ? life->w-1 : j-1;
  297. pos[S ][0] = (i+1) == life->h ? 0 : i+1; pos[S ][1] = j ;
  298. pos[SE][0] = (i+1) == life->h ? 0 : i+1; pos[SE][1] = (j+1) == life->w ? 0 : j+1;
  299. } else {
  300. pos[NW][0] = (i-1) < 0 ? -1 : i-1; pos[NW][1] = (j-1) < 0 ? -1 : j-1;
  301. pos[N ][0] = (i-1) < 0 ? -1 : i-1; pos[N ][1] = j ;
  302. pos[NE][0] = (i-1) < 0 ? -1 : i-1; pos[NE][1] = (j+1) == life->w ? -1 : j+1;
  303. pos[W ][0] = i ; pos[W ][1] = (j-1) < 0 ? -1 : j-1;
  304. pos[E ][0] = i ; pos[E ][1] = (j+1) == life->w ? -1 : j+1;
  305. pos[SW][0] = (i+1) == life->h ? -1 : i+1; pos[SW][1] = (j-1) < 0 ? -1 : j-1;
  306. pos[S ][0] = (i+1) == life->h ? -1 : i+1; pos[S ][1] = j ;
  307. pos[SE][0] = (i+1) == life->h ? -1 : i+1; pos[SE][1] = (j+1) == life->w ? -1 : j+1;
  308. }
  309. /* compute the number of live neighbor cells */
  310. n = (pos[NW][0] == -1 || pos[NW][1] == -1 ? 0 : oldbuf[pos[NW][0]*life->w + pos[NW][1]] == ALIVE_CELL) +
  311. (pos[N ][0] == -1 || pos[N ][1] == -1 ? 0 : oldbuf[pos[N ][0]*life->w + pos[N ][1]] == ALIVE_CELL) +
  312. (pos[NE][0] == -1 || pos[NE][1] == -1 ? 0 : oldbuf[pos[NE][0]*life->w + pos[NE][1]] == ALIVE_CELL) +
  313. (pos[W ][0] == -1 || pos[W ][1] == -1 ? 0 : oldbuf[pos[W ][0]*life->w + pos[W ][1]] == ALIVE_CELL) +
  314. (pos[E ][0] == -1 || pos[E ][1] == -1 ? 0 : oldbuf[pos[E ][0]*life->w + pos[E ][1]] == ALIVE_CELL) +
  315. (pos[SW][0] == -1 || pos[SW][1] == -1 ? 0 : oldbuf[pos[SW][0]*life->w + pos[SW][1]] == ALIVE_CELL) +
  316. (pos[S ][0] == -1 || pos[S ][1] == -1 ? 0 : oldbuf[pos[S ][0]*life->w + pos[S ][1]] == ALIVE_CELL) +
  317. (pos[SE][0] == -1 || pos[SE][1] == -1 ? 0 : oldbuf[pos[SE][0]*life->w + pos[SE][1]] == ALIVE_CELL);
  318. cell = oldbuf[i*life->w + j];
  319. alive = 1<<n & (cell == ALIVE_CELL ? life->stay_rule : life->born_rule);
  320. if (alive) *newbuf = ALIVE_CELL; // new cell is alive
  321. else if (cell) *newbuf = cell - 1; // new cell is dead and in the process of mold
  322. else *newbuf = 0; // new cell is definitely dead
  323. av_dlog(ctx, "i:%d j:%d live_neighbors:%d cell:%d -> cell:%d\n", i, j, n, cell, *newbuf);
  324. newbuf++;
  325. }
  326. }
  327. life->buf_idx = !life->buf_idx;
  328. }
  329. static void fill_picture_monoblack(AVFilterContext *ctx, AVFrame *picref)
  330. {
  331. LifeContext *life = ctx->priv;
  332. uint8_t *buf = life->buf[life->buf_idx];
  333. int i, j, k;
  334. /* fill the output picture with the old grid buffer */
  335. for (i = 0; i < life->h; i++) {
  336. uint8_t byte = 0;
  337. uint8_t *p = picref->data[0] + i * picref->linesize[0];
  338. for (k = 0, j = 0; j < life->w; j++) {
  339. byte |= (buf[i*life->w+j] == ALIVE_CELL)<<(7-k++);
  340. if (k==8 || j == life->w-1) {
  341. k = 0;
  342. *p++ = byte;
  343. byte = 0;
  344. }
  345. }
  346. }
  347. }
  348. // divide by 255 and round to nearest
  349. // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
  350. #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
  351. static void fill_picture_rgb(AVFilterContext *ctx, AVFrame *picref)
  352. {
  353. LifeContext *life = ctx->priv;
  354. uint8_t *buf = life->buf[life->buf_idx];
  355. int i, j;
  356. /* fill the output picture with the old grid buffer */
  357. for (i = 0; i < life->h; i++) {
  358. uint8_t *p = picref->data[0] + i * picref->linesize[0];
  359. for (j = 0; j < life->w; j++) {
  360. uint8_t v = buf[i*life->w + j];
  361. if (life->mold && v != ALIVE_CELL) {
  362. const uint8_t *c1 = life-> mold_color;
  363. const uint8_t *c2 = life->death_color;
  364. int death_age = FFMIN((0xff - v) * life->mold, 0xff);
  365. *p++ = FAST_DIV255((c2[0] << 8) + ((int)c1[0] - (int)c2[0]) * death_age);
  366. *p++ = FAST_DIV255((c2[1] << 8) + ((int)c1[1] - (int)c2[1]) * death_age);
  367. *p++ = FAST_DIV255((c2[2] << 8) + ((int)c1[2] - (int)c2[2]) * death_age);
  368. } else {
  369. const uint8_t *c = v == ALIVE_CELL ? life->life_color : life->death_color;
  370. AV_WB24(p, c[0]<<16 | c[1]<<8 | c[2]);
  371. p += 3;
  372. }
  373. }
  374. }
  375. }
  376. static int request_frame(AVFilterLink *outlink)
  377. {
  378. LifeContext *life = outlink->src->priv;
  379. AVFrame *picref = ff_get_video_buffer(outlink, life->w, life->h);
  380. picref->sample_aspect_ratio = (AVRational) {1, 1};
  381. picref->pts = life->pts++;
  382. life->draw(outlink->src, picref);
  383. evolve(outlink->src);
  384. #ifdef DEBUG
  385. show_life_grid(outlink->src);
  386. #endif
  387. return ff_filter_frame(outlink, picref);
  388. }
  389. static int query_formats(AVFilterContext *ctx)
  390. {
  391. LifeContext *life = ctx->priv;
  392. enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_NONE, AV_PIX_FMT_NONE };
  393. if (life->mold || memcmp(life-> life_color, "\xff\xff\xff", 3)
  394. || memcmp(life->death_color, "\x00\x00\x00", 3)) {
  395. pix_fmts[0] = AV_PIX_FMT_RGB24;
  396. life->draw = fill_picture_rgb;
  397. } else {
  398. pix_fmts[0] = AV_PIX_FMT_MONOBLACK;
  399. life->draw = fill_picture_monoblack;
  400. }
  401. ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
  402. return 0;
  403. }
  404. static const AVFilterPad life_outputs[] = {
  405. {
  406. .name = "default",
  407. .type = AVMEDIA_TYPE_VIDEO,
  408. .request_frame = request_frame,
  409. .config_props = config_props,
  410. },
  411. { NULL}
  412. };
  413. AVFilter avfilter_vsrc_life = {
  414. .name = "life",
  415. .description = NULL_IF_CONFIG_SMALL("Create life."),
  416. .priv_size = sizeof(LifeContext),
  417. .init = init,
  418. .uninit = uninit,
  419. .query_formats = query_formats,
  420. .inputs = NULL,
  421. .outputs = life_outputs,
  422. .priv_class = &life_class,
  423. };