vsrc_life.c 18 KB

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