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