]> git.sesse.net Git - ffmpeg/blob - libavfilter/vsrc_cellauto.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavfilter / vsrc_cellauto.c
1 /*
2  * Copyright (c) Stefano Sabatini 2011
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  * cellular automaton video source, based on Stephen Wolfram "experimentus crucis"
24  */
25
26 /* #define DEBUG */
27
28 #include "libavutil/file.h"
29 #include "libavutil/lfg.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/parseutils.h"
32 #include "libavutil/random_seed.h"
33 #include "avfilter.h"
34
35 typedef struct {
36     const AVClass *class;
37     int w, h;
38     char *filename;
39     char *rule_str;
40     uint8_t *file_buf;
41     size_t file_bufsize;
42     uint8_t *buf;
43     int buf_prev_row_idx, buf_row_idx;
44     uint8_t rule;
45     uint64_t pts;
46     AVRational time_base;
47     char *size;                 ///< video frame size
48     char *rate;                 ///< video frame rate
49     double   random_fill_ratio;
50     uint32_t random_seed;
51     int stitch, scroll, start_full;
52     int64_t generation;         ///< the generation number, starting from 0
53     AVLFG lfg;
54     char *pattern;
55 } CellAutoContext;
56
57 #define OFFSET(x) offsetof(CellAutoContext, x)
58
59 static const AVOption cellauto_options[] = {
60     { "filename", "read initial pattern from file", OFFSET(filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0 },
61     { "f",        "read initial pattern from file", OFFSET(filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0 },
62     { "pattern",  "set initial pattern", OFFSET(pattern), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0 },
63     { "p",        "set initial pattern", OFFSET(pattern), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0 },
64     { "rate",     "set video rate", OFFSET(rate), AV_OPT_TYPE_STRING, {.str = "25"}, 0, 0 },
65     { "r",        "set video rate", OFFSET(rate), AV_OPT_TYPE_STRING, {.str = "25"}, 0, 0 },
66     { "size",     "set video size", OFFSET(size), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0 },
67     { "s",        "set video size", OFFSET(size), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0 },
68     { "rule",     "set rule",       OFFSET(rule), AV_OPT_TYPE_INT,    {.dbl = 110},  0, 255 },
69     { "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 },
70     { "ratio",             "set fill ratio for filling initial grid randomly", OFFSET(random_fill_ratio), AV_OPT_TYPE_DOUBLE, {.dbl = 1/M_PHI}, 0, 1 },
71     { "random_seed", "set the seed for filling the initial grid randomly", OFFSET(random_seed), AV_OPT_TYPE_INT, {.dbl = -1}, -1, UINT32_MAX },
72     { "seed",        "set the seed for filling the initial grid randomly", OFFSET(random_seed), AV_OPT_TYPE_INT, {.dbl = -1}, -1, UINT32_MAX },
73     { "scroll",      "scroll pattern downward", OFFSET(scroll), AV_OPT_TYPE_INT, {.dbl = 1}, 0, 1 },
74     { "start_full",  "start filling the whole video", OFFSET(start_full), AV_OPT_TYPE_INT, {.dbl = 0}, 0, 1 },
75     { "full",        "start filling the whole video", OFFSET(start_full), AV_OPT_TYPE_INT, {.dbl = 1}, 0, 1 },
76     { "stitch",      "stitch boundaries", OFFSET(stitch), AV_OPT_TYPE_INT,    {.dbl = 1},   0, 1 },
77     { NULL },
78 };
79
80 static const char *cellauto_get_name(void *ctx)
81 {
82     return "cellauto";
83 }
84
85 static const AVClass cellauto_class = {
86     "CellAutoContext",
87     cellauto_get_name,
88     cellauto_options
89 };
90
91 #ifdef DEBUG
92 static void show_cellauto_row(AVFilterContext *ctx)
93 {
94     CellAutoContext *cellauto = ctx->priv;
95     int i;
96     uint8_t *row = cellauto->buf + cellauto->w * cellauto->buf_row_idx;
97     char *line = av_malloc(cellauto->w + 1);
98     if (!line)
99         return;
100
101     for (i = 0; i < cellauto->w; i++)
102         line[i] = row[i] ? '@' : ' ';
103     line[i] = 0;
104     av_log(ctx, AV_LOG_DEBUG, "generation:%"PRId64" row:%s|\n", cellauto->generation, line);
105     av_free(line);
106 }
107 #endif
108
109 static int init_pattern_from_string(AVFilterContext *ctx)
110 {
111     CellAutoContext *cellauto = ctx->priv;
112     char *p;
113     int i, w = 0;
114
115     w = strlen(cellauto->pattern);
116     av_log(ctx, AV_LOG_DEBUG, "w:%d\n", w);
117
118     if (cellauto->size) {
119         if (w > cellauto->w) {
120             av_log(ctx, AV_LOG_ERROR,
121                    "The specified width is %d which cannot contain the provided string width of %d\n",
122                    cellauto->w, w);
123             return AVERROR(EINVAL);
124         }
125     } else {
126         /* width was not specified, set it to width of the provided row */
127         cellauto->w = w;
128         cellauto->h = (double)cellauto->w * M_PHI;
129     }
130
131     cellauto->buf = av_mallocz(sizeof(uint8_t) * cellauto->w * cellauto->h);
132     if (!cellauto->buf)
133         return AVERROR(ENOMEM);
134
135     /* fill buf */
136     p = cellauto->pattern;
137     for (i = (cellauto->w - w)/2;; i++) {
138         av_log(ctx, AV_LOG_DEBUG, "%d %c\n", i, *p == '\n' ? 'N' : *p);
139         if (*p == '\n' || !*p)
140             break;
141         else
142             cellauto->buf[i] = !!isgraph(*(p++));
143     }
144
145     return 0;
146 }
147
148 static int init_pattern_from_file(AVFilterContext *ctx)
149 {
150     CellAutoContext *cellauto = ctx->priv;
151     int ret;
152
153     ret = av_file_map(cellauto->filename,
154                       &cellauto->file_buf, &cellauto->file_bufsize, 0, ctx);
155     if (ret < 0)
156         return ret;
157
158     /* create a string based on the read file */
159     cellauto->pattern = av_malloc(cellauto->file_bufsize + 1);
160     if (!cellauto->pattern)
161         return AVERROR(ENOMEM);
162     memcpy(cellauto->pattern, cellauto->file_buf, cellauto->file_bufsize);
163     cellauto->pattern[cellauto->file_bufsize] = 0;
164
165     return init_pattern_from_string(ctx);
166 }
167
168 static int init(AVFilterContext *ctx, const char *args, void *opaque)
169 {
170     CellAutoContext *cellauto = ctx->priv;
171     AVRational frame_rate;
172     int ret;
173
174     cellauto->class = &cellauto_class;
175     av_opt_set_defaults(cellauto);
176
177     if ((ret = av_set_options_string(cellauto, args, "=", ":")) < 0) {
178         av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
179         return ret;
180     }
181
182     if ((ret = av_parse_video_rate(&frame_rate, cellauto->rate)) < 0) {
183         av_log(ctx, AV_LOG_ERROR, "Invalid frame rate: %s\n", cellauto->rate);
184         return AVERROR(EINVAL);
185     }
186
187     if (!cellauto->size && !cellauto->filename && !cellauto->pattern)
188         av_opt_set(cellauto, "size", "320x518", 0);
189
190     if (cellauto->size &&
191         (ret = av_parse_video_size(&cellauto->w, &cellauto->h, cellauto->size)) < 0) {
192         av_log(ctx, AV_LOG_ERROR, "Invalid frame size: %s\n", cellauto->size);
193         return ret;
194     }
195
196     cellauto->time_base.num = frame_rate.den;
197     cellauto->time_base.den = frame_rate.num;
198
199     if (cellauto->filename && cellauto->pattern) {
200         av_log(ctx, AV_LOG_ERROR, "Only one of the filename or pattern options can be used\n");
201         return AVERROR(EINVAL);
202     }
203
204     if (cellauto->filename) {
205         if ((ret = init_pattern_from_file(ctx)) < 0)
206             return ret;
207     } else if (cellauto->pattern) {
208         if ((ret = init_pattern_from_string(ctx)) < 0)
209             return ret;
210     } else {
211         /* fill the first row randomly */
212         int i;
213
214         cellauto->buf = av_mallocz(sizeof(uint8_t) * cellauto->w * cellauto->h);
215         if (!cellauto->buf)
216             return AVERROR(ENOMEM);
217         if (cellauto->random_seed == -1)
218             cellauto->random_seed = av_get_random_seed();
219
220         av_lfg_init(&cellauto->lfg, cellauto->random_seed);
221
222         for (i = 0; i < cellauto->w; i++) {
223             double r = (double)av_lfg_get(&cellauto->lfg) / UINT32_MAX;
224             if (r <= cellauto->random_fill_ratio)
225                 cellauto->buf[i] = 1;
226         }
227     }
228
229     av_log(ctx, AV_LOG_INFO,
230            "s:%dx%d r:%d/%d rule:%d stitch:%d scroll:%d full:%d seed:%u\n",
231            cellauto->w, cellauto->h, frame_rate.num, frame_rate.den,
232            cellauto->rule, cellauto->stitch, cellauto->scroll, cellauto->start_full,
233            cellauto->random_seed);
234     return 0;
235 }
236
237 static av_cold void uninit(AVFilterContext *ctx)
238 {
239     CellAutoContext *cellauto = ctx->priv;
240
241     av_file_unmap(cellauto->file_buf, cellauto->file_bufsize);
242     av_freep(&cellauto->buf);
243     av_freep(&cellauto->pattern);
244 }
245
246 static int config_props(AVFilterLink *outlink)
247 {
248     CellAutoContext *cellauto = outlink->src->priv;
249
250     outlink->w = cellauto->w;
251     outlink->h = cellauto->h;
252     outlink->time_base = cellauto->time_base;
253
254     return 0;
255 }
256
257 static void evolve(AVFilterContext *ctx)
258 {
259     CellAutoContext *cellauto = ctx->priv;
260     int i, v, pos[3];
261     uint8_t *row, *prev_row = cellauto->buf + cellauto->buf_row_idx * cellauto->w;
262     enum { NW, N, NE };
263
264     cellauto->buf_prev_row_idx = cellauto->buf_row_idx;
265     cellauto->buf_row_idx      = cellauto->buf_row_idx == cellauto->h-1 ? 0 : cellauto->buf_row_idx+1;
266     row = cellauto->buf + cellauto->w * cellauto->buf_row_idx;
267
268     for (i = 0; i < cellauto->w; i++) {
269         if (cellauto->stitch) {
270             pos[NW] = i-1 < 0 ? cellauto->w-1 : i-1;
271             pos[N]  = i;
272             pos[NE] = i+1 == cellauto->w ? 0  : i+1;
273             v = prev_row[pos[NW]]<<2 | prev_row[pos[N]]<<1 | prev_row[pos[NE]];
274         } else {
275             v = 0;
276             v|= i-1 >= 0          ? prev_row[i-1]<<2 : 0;
277             v|=                     prev_row[i  ]<<1    ;
278             v|= i+1 < cellauto->w ? prev_row[i+1]    : 0;
279         }
280         row[i] = !!(cellauto->rule & (1<<v));
281         av_dlog(ctx, "i:%d context:%c%c%c -> cell:%d\n", i,
282                 v&4?'@':' ', v&2?'@':' ', v&1?'@':' ', row[i]);
283     }
284
285     cellauto->generation++;
286 }
287
288 static void fill_picture(AVFilterContext *ctx, AVFilterBufferRef *picref)
289 {
290     CellAutoContext *cellauto = ctx->priv;
291     int i, j, k, row_idx = 0;
292     uint8_t *p0 = picref->data[0];
293
294     if (cellauto->scroll && cellauto->generation >= cellauto->h)
295         /* show on top the oldest row */
296         row_idx = (cellauto->buf_row_idx + 1) % cellauto->h;
297
298     /* fill the output picture with the whole buffer */
299     for (i = 0; i < cellauto->h; i++) {
300         uint8_t byte = 0;
301         uint8_t *row = cellauto->buf + row_idx*cellauto->w;
302         uint8_t *p = p0;
303         for (k = 0, j = 0; j < cellauto->w; j++) {
304             byte |= row[j]<<(7-k++);
305             if (k==8 || j == cellauto->w-1) {
306                 k = 0;
307                 *p++ = byte;
308                 byte = 0;
309             }
310         }
311         row_idx = (row_idx + 1) % cellauto->h;
312         p0 += picref->linesize[0];
313     }
314 }
315
316 static int request_frame(AVFilterLink *outlink)
317 {
318     CellAutoContext *cellauto = outlink->src->priv;
319     AVFilterBufferRef *picref =
320         avfilter_get_video_buffer(outlink, AV_PERM_WRITE, cellauto->w, cellauto->h);
321     picref->video->sample_aspect_ratio = (AVRational) {1, 1};
322     if (cellauto->generation == 0 && cellauto->start_full) {
323         int i;
324         for (i = 0; i < cellauto->h-1; i++)
325             evolve(outlink->src);
326     }
327     fill_picture(outlink->src, picref);
328     evolve(outlink->src);
329
330     picref->pts = cellauto->pts++;
331     picref->pos = -1;
332
333 #ifdef DEBUG
334     show_cellauto_row(outlink->src);
335 #endif
336
337     avfilter_start_frame(outlink, avfilter_ref_buffer(picref, ~0));
338     avfilter_draw_slice(outlink, 0, cellauto->h, 1);
339     avfilter_end_frame(outlink);
340     avfilter_unref_buffer(picref);
341
342     return 0;
343 }
344
345 static int query_formats(AVFilterContext *ctx)
346 {
347     static const enum PixelFormat pix_fmts[] = { PIX_FMT_MONOBLACK, PIX_FMT_NONE };
348     avfilter_set_common_pixel_formats(ctx, avfilter_make_format_list(pix_fmts));
349     return 0;
350 }
351
352 AVFilter avfilter_vsrc_cellauto = {
353     .name        = "cellauto",
354     .description = NULL_IF_CONFIG_SMALL("Create pattern generated by an elementary cellular automaton."),
355     .priv_size = sizeof(CellAutoContext),
356     .init      = init,
357     .uninit    = uninit,
358     .query_formats = query_formats,
359
360     .inputs    = (const AVFilterPad[]) {
361         { .name = NULL}
362     },
363     .outputs   = (const AVFilterPad[]) {
364         { .name            = "default",
365           .type            = AVMEDIA_TYPE_VIDEO,
366           .request_frame   = request_frame,
367           .config_props    = config_props },
368         { .name = NULL}
369     },
370 };