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.

487 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 "internal.h"
  33. #include "formats.h"
  34. #include "video.h"
  35. typedef struct {
  36. const AVClass *class;
  37. int w, h;
  38. char *filename;
  39. char *rule_str;
  40. uint8_t *file_buf;
  41. size_t file_bufsize;
  42. /**
  43. * The two grid state buffers.
  44. *
  45. * A 0xFF (ALIVE_CELL) value means the cell is alive (or new born), while
  46. * the decreasing values from 0xFE to 0 means the cell is dead; the range
  47. * of values is used for the slow death effect, or mold (0xFE means dead,
  48. * 0xFD means very dead, 0xFC means very very dead... and 0x00 means
  49. * definitely dead/mold).
  50. */
  51. uint8_t *buf[2];
  52. uint8_t buf_idx;
  53. uint16_t stay_rule; ///< encode the behavior for filled cells
  54. uint16_t born_rule; ///< encode the behavior for empty cells
  55. uint64_t pts;
  56. AVRational time_base;
  57. char *rate; ///< video frame rate
  58. double random_fill_ratio;
  59. uint32_t random_seed;
  60. int stitch;
  61. int mold;
  62. char *life_color_str;
  63. char *death_color_str;
  64. char *mold_color_str;
  65. uint8_t life_color[4];
  66. uint8_t death_color[4];
  67. uint8_t mold_color[4];
  68. AVLFG lfg;
  69. void (*draw)(AVFilterContext*, AVFilterBufferRef*);
  70. } LifeContext;
  71. #define ALIVE_CELL 0xFF
  72. #define OFFSET(x) offsetof(LifeContext, x)
  73. static const AVOption life_options[] = {
  74. { "filename", "set source file", OFFSET(filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0 },
  75. { "f", "set source file", OFFSET(filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0 },
  76. { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0 },
  77. { "s", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0 },
  78. { "rate", "set video rate", OFFSET(rate), AV_OPT_TYPE_STRING, {.str = "25"}, 0, 0 },
  79. { "r", "set video rate", OFFSET(rate), AV_OPT_TYPE_STRING, {.str = "25"}, 0, 0 },
  80. { "rule", "set rule", OFFSET(rule_str), AV_OPT_TYPE_STRING, {.str = "B3/S23"}, CHAR_MIN, CHAR_MAX },
  81. { "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 },
  82. { "ratio", "set fill ratio for filling initial grid randomly", OFFSET(random_fill_ratio), AV_OPT_TYPE_DOUBLE, {.dbl=1/M_PHI}, 0, 1 },
  83. { "random_seed", "set the seed for filling the initial grid randomly", OFFSET(random_seed), AV_OPT_TYPE_INT, {.dbl=-1}, -1, UINT32_MAX },
  84. { "seed", "set the seed for filling the initial grid randomly", OFFSET(random_seed), AV_OPT_TYPE_INT, {.dbl=-1}, -1, UINT32_MAX },
  85. { "stitch", "stitch boundaries", OFFSET(stitch), AV_OPT_TYPE_INT, {.dbl=1}, 0, 1 },
  86. { "mold", "set mold speed for dead cells", OFFSET(mold), AV_OPT_TYPE_INT, {.dbl=0}, 0, 0xFF },
  87. { "life_color", "set life color", OFFSET( life_color_str), AV_OPT_TYPE_STRING, {.str="white"}, CHAR_MIN, CHAR_MAX },
  88. { "death_color", "set death color", OFFSET(death_color_str), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX },
  89. { "mold_color", "set mold color", OFFSET( mold_color_str), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX },
  90. { NULL },
  91. };
  92. AVFILTER_DEFINE_CLASS(life);
  93. static int parse_rule(uint16_t *born_rule, uint16_t *stay_rule,
  94. const char *rule_str, void *log_ctx)
  95. {
  96. char *tail;
  97. const char *p = rule_str;
  98. *born_rule = 0;
  99. *stay_rule = 0;
  100. if (strchr("bBsS", *p)) {
  101. /* parse rule as a Born / Stay Alive code, see
  102. * http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life */
  103. do {
  104. uint16_t *rule = (*p == 'b' || *p == 'B') ? born_rule : stay_rule;
  105. p++;
  106. while (*p >= '0' && *p <= '8') {
  107. *rule += 1<<(*p - '0');
  108. p++;
  109. }
  110. if (*p != '/')
  111. break;
  112. p++;
  113. } while (strchr("bBsS", *p));
  114. if (*p)
  115. goto error;
  116. } else {
  117. /* parse rule as a number, expressed in the form STAY|(BORN<<9),
  118. * where STAY and BORN encode the corresponding 9-bits rule */
  119. long int rule = strtol(rule_str, &tail, 10);
  120. if (*tail)
  121. goto error;
  122. *born_rule = ((1<<9)-1) & rule;
  123. *stay_rule = rule >> 9;
  124. }
  125. return 0;
  126. error:
  127. av_log(log_ctx, AV_LOG_ERROR, "Invalid rule code '%s' provided\n", rule_str);
  128. return AVERROR(EINVAL);
  129. }
  130. #ifdef DEBUG
  131. static void show_life_grid(AVFilterContext *ctx)
  132. {
  133. LifeContext *life = ctx->priv;
  134. int i, j;
  135. char *line = av_malloc(life->w + 1);
  136. if (!line)
  137. return;
  138. for (i = 0; i < life->h; i++) {
  139. for (j = 0; j < life->w; j++)
  140. line[j] = life->buf[life->buf_idx][i*life->w + j] == ALIVE_CELL ? '@' : ' ';
  141. line[j] = 0;
  142. av_log(ctx, AV_LOG_DEBUG, "%3d: %s\n", i, line);
  143. }
  144. av_free(line);
  145. }
  146. #endif
  147. static int init_pattern_from_file(AVFilterContext *ctx)
  148. {
  149. LifeContext *life = ctx->priv;
  150. char *p;
  151. int ret, i, i0, j, h = 0, w, max_w = 0;
  152. if ((ret = av_file_map(life->filename, &life->file_buf, &life->file_bufsize,
  153. 0, ctx)) < 0)
  154. return ret;
  155. av_freep(&life->filename);
  156. /* prescan file to get the number of lines and the maximum width */
  157. w = 0;
  158. for (i = 0; i < life->file_bufsize; i++) {
  159. if (life->file_buf[i] == '\n') {
  160. h++; max_w = FFMAX(w, max_w); w = 0;
  161. } else {
  162. w++;
  163. }
  164. }
  165. av_log(ctx, AV_LOG_DEBUG, "h:%d max_w:%d\n", h, max_w);
  166. if (life->w) {
  167. if (max_w > life->w || h > life->h) {
  168. av_log(ctx, AV_LOG_ERROR,
  169. "The specified size is %dx%d which cannot contain the provided file size of %dx%d\n",
  170. life->w, life->h, max_w, h);
  171. return AVERROR(EINVAL);
  172. }
  173. } else {
  174. /* size was not specified, set it to size of the grid */
  175. life->w = max_w;
  176. life->h = h;
  177. }
  178. if (!(life->buf[0] = av_mallocz(sizeof(char) * life->h * life->w)) ||
  179. !(life->buf[1] = av_mallocz(sizeof(char) * life->h * life->w))) {
  180. av_free(life->buf[0]);
  181. av_free(life->buf[1]);
  182. return AVERROR(ENOMEM);
  183. }
  184. /* fill buf[0] */
  185. p = life->file_buf;
  186. for (i0 = 0, i = (life->h - h)/2; i0 < h; i0++, i++) {
  187. for (j = (life->w - max_w)/2;; j++) {
  188. av_log(ctx, AV_LOG_DEBUG, "%d:%d %c\n", i, j, *p == '\n' ? 'N' : *p);
  189. if (*p == '\n') {
  190. p++; break;
  191. } else
  192. life->buf[0][i*life->w + j] = isgraph(*(p++)) ? ALIVE_CELL : 0;
  193. }
  194. }
  195. life->buf_idx = 0;
  196. return 0;
  197. }
  198. static int init(AVFilterContext *ctx, const char *args)
  199. {
  200. LifeContext *life = ctx->priv;
  201. AVRational frame_rate;
  202. int ret;
  203. life->class = &life_class;
  204. av_opt_set_defaults(life);
  205. if ((ret = av_set_options_string(life, args, "=", ":")) < 0) {
  206. av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
  207. return ret;
  208. }
  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, AVFilterBufferRef *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, AVFilterBufferRef *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. AVFilterBufferRef *picref = ff_get_video_buffer(outlink, AV_PERM_WRITE, life->w, life->h);
  380. picref->video->sample_aspect_ratio = (AVRational) {1, 1};
  381. picref->pts = life->pts++;
  382. picref->pos = -1;
  383. life->draw(outlink->src, picref);
  384. evolve(outlink->src);
  385. #ifdef DEBUG
  386. show_life_grid(outlink->src);
  387. #endif
  388. ff_start_frame(outlink, avfilter_ref_buffer(picref, ~0));
  389. ff_draw_slice(outlink, 0, life->h, 1);
  390. ff_end_frame(outlink);
  391. avfilter_unref_buffer(picref);
  392. return 0;
  393. }
  394. static int query_formats(AVFilterContext *ctx)
  395. {
  396. LifeContext *life = ctx->priv;
  397. enum PixelFormat pix_fmts[] = { PIX_FMT_NONE, PIX_FMT_NONE };
  398. if (life->mold || memcmp(life-> life_color, "\xff\xff\xff", 3)
  399. || memcmp(life->death_color, "\x00\x00\x00", 3)) {
  400. pix_fmts[0] = PIX_FMT_RGB24;
  401. life->draw = fill_picture_rgb;
  402. } else {
  403. pix_fmts[0] = PIX_FMT_MONOBLACK;
  404. life->draw = fill_picture_monoblack;
  405. }
  406. ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
  407. return 0;
  408. }
  409. AVFilter avfilter_vsrc_life = {
  410. .name = "life",
  411. .description = NULL_IF_CONFIG_SMALL("Create life."),
  412. .priv_size = sizeof(LifeContext),
  413. .init = init,
  414. .uninit = uninit,
  415. .query_formats = query_formats,
  416. .inputs = (const AVFilterPad[]) {
  417. { .name = NULL}
  418. },
  419. .outputs = (const AVFilterPad[]) {
  420. { .name = "default",
  421. .type = AVMEDIA_TYPE_VIDEO,
  422. .request_frame = request_frame,
  423. .config_props = config_props },
  424. { .name = NULL}
  425. },
  426. };