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