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.

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