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.

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