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