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