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