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