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