vsrc_life.c 17 KB

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