]> git.sesse.net Git - ffmpeg/blob - libavfilter/vsrc_mandelbrot.c
amovie: avoid crash in amovie_request_frame() if no samplesref is available
[ffmpeg] / libavfilter / vsrc_mandelbrot.c
1 /*
2  * Copyright (c) 2011 Michael Niedermayer
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  * The vsrc_color filter from Stefano Sabatini was used as template to create
21  * this
22  */
23
24 /**
25  * @file
26  * Mandelbrot fraktal renderer
27  */
28
29 #include "avfilter.h"
30 #include "libavutil/imgutils.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/parseutils.h"
33 #include <float.h>
34 #include <math.h>
35
36 #define SQR(a) ((a)*(a))
37
38 enum Outer{
39     ITERATION_COUNT,
40     NORMALIZED_ITERATION_COUNT,
41 };
42
43 enum Inner{
44     BLACK,
45     PERIOD,
46 };
47
48 typedef struct Point {
49     double p[2];
50     uint32_t val;
51 } Point;
52
53 typedef struct {
54     const AVClass *class;
55     int w, h;
56     AVRational time_base;
57     uint64_t pts;
58     char *size, *rate;
59     int maxiter;
60     double start_x;
61     double start_y;
62     double start_scale;
63     double end_scale;
64     double end_pts;
65     double bailout;
66     enum Outer outer;
67     enum Inner inner;
68     int cache_allocated;
69     int cache_used;
70     Point *point_cache;
71     Point *next_cache;
72     double (*zyklus)[2];
73 } MBContext;
74
75 #define OFFSET(x) offsetof(MBContext, x)
76
77 static const AVOption mandelbrot_options[] = {
78     {"size",        "set frame size",                OFFSET(size),    AV_OPT_TYPE_STRING,     {.str="640x480"},  CHAR_MIN, CHAR_MAX },
79     {"s",           "set frame size",                OFFSET(size),    AV_OPT_TYPE_STRING,     {.str="640x480"},  CHAR_MIN, CHAR_MAX },
80     {"rate",        "set frame rate",                OFFSET(rate),    AV_OPT_TYPE_STRING,     {.str="25"},  CHAR_MIN, CHAR_MAX },
81     {"r",           "set frame rate",                OFFSET(rate),    AV_OPT_TYPE_STRING,     {.str="25"},  CHAR_MIN, CHAR_MAX },
82     {"maxiter",     "set max iterations number",     OFFSET(maxiter), AV_OPT_TYPE_INT,        {.dbl=4096},  1,        INT_MAX  },
83     {"start_x",     "set the initial x position",    OFFSET(start_x), AV_OPT_TYPE_DOUBLE,     {.dbl=-0.743643887037158704752191506114774}, -100, 100  },
84     {"start_y",     "set the initial y position",    OFFSET(start_y), AV_OPT_TYPE_DOUBLE,     {.dbl=-0.131825904205311970493132056385139}, -100, 100  },
85     {"start_scale", "set the initial scale value",   OFFSET(start_scale), AV_OPT_TYPE_DOUBLE, {.dbl=3.0},  0, FLT_MAX },
86     {"end_scale",   "set the terminal scale value",  OFFSET(end_scale), AV_OPT_TYPE_DOUBLE,   {.dbl=0.3},  0, FLT_MAX },
87     {"end_pts",     "set the terminal pts value",    OFFSET(end_pts), AV_OPT_TYPE_DOUBLE,     {.dbl=800},  0, INT64_MAX },
88     {"bailout",     "set the bailout value",         OFFSET(bailout), AV_OPT_TYPE_DOUBLE,     {.dbl=10},   0, FLT_MAX },
89
90     {"outer",       "set outer coloring mode",       OFFSET(outer), AV_OPT_TYPE_INT, {.dbl=NORMALIZED_ITERATION_COUNT}, 0, INT_MAX, 0, "outer"},
91     {"iteration_count", "set iteration count mode",  0, AV_OPT_TYPE_CONST, {.dbl=ITERATION_COUNT}, INT_MIN, INT_MAX, 0, "outer" },
92     {"normalized_iteration_count", "set normalized iteration count mode",   0, AV_OPT_TYPE_CONST, {.dbl=NORMALIZED_ITERATION_COUNT}, INT_MIN, INT_MAX, 0, "outer" },
93
94     {"inner",       "set inner coloring mode",       OFFSET(inner), AV_OPT_TYPE_INT, {.dbl=BLACK}, 0, INT_MAX, 0, "inner"},
95     {"black",       "set black mode",                0, AV_OPT_TYPE_CONST, {.dbl=BLACK}, INT_MIN, INT_MAX, 0, "inner" },
96     {"period",      "set period mode",               0, AV_OPT_TYPE_CONST, {.dbl=PERIOD}, INT_MIN, INT_MAX, 0, "inner" },
97
98     {NULL},
99 };
100
101 static const char *mandelbrot_get_name(void *ctx)
102 {
103     return "mandelbrot";
104 }
105
106 static const AVClass mandelbrot_class = {
107     "MBContext",
108     mandelbrot_get_name,
109     mandelbrot_options
110 };
111
112 static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
113 {
114     MBContext *mb = ctx->priv;
115     AVRational rate_q;
116     int err;
117
118     mb->class = &mandelbrot_class;
119     av_opt_set_defaults(mb);
120
121     if ((err = (av_set_options_string(mb, args, "=", ":"))) < 0) {
122         av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
123         return err;
124     }
125     mb->bailout *= mb->bailout;
126
127     if (av_parse_video_size(&mb->w, &mb->h, mb->size) < 0) {
128         av_log(ctx, AV_LOG_ERROR, "Invalid frame size: %s\n", mb->size);
129         return AVERROR(EINVAL);
130     }
131     mb->start_scale /=mb->h;
132     mb->end_scale /=mb->h;
133
134     if (av_parse_video_rate(&rate_q, mb->rate) < 0 ||
135         rate_q.den <= 0 || rate_q.num <= 0) {
136         av_log(ctx, AV_LOG_ERROR, "Invalid frame rate: %s\n", mb->rate);
137         return AVERROR(EINVAL);
138     }
139     mb->time_base.num = rate_q.den;
140     mb->time_base.den = rate_q.num;
141
142     mb->cache_allocated = mb->w * mb->h * 3;
143     mb->cache_used = 0;
144     mb->point_cache= av_malloc(sizeof(*mb->point_cache)*mb->cache_allocated);
145     mb-> next_cache= av_malloc(sizeof(*mb-> next_cache)*mb->cache_allocated);
146     mb-> zyklus    = av_malloc(sizeof(*mb->zyklus) * mb->maxiter);
147
148     return 0;
149 }
150
151 static av_cold void uninit(AVFilterContext *ctx)
152 {
153     MBContext *mb = ctx->priv;
154
155     av_freep(&mb->size);
156     av_freep(&mb->rate);
157     av_freep(&mb->point_cache);
158     av_freep(&mb-> next_cache);
159     av_freep(&mb->zyklus);
160 }
161
162 static int query_formats(AVFilterContext *ctx)
163 {
164     static const enum PixelFormat pix_fmts[] = {
165         PIX_FMT_BGR32,
166         PIX_FMT_NONE
167     };
168
169     avfilter_set_common_pixel_formats(ctx, avfilter_make_format_list(pix_fmts));
170     return 0;
171 }
172
173 static int config_props(AVFilterLink *inlink)
174 {
175     AVFilterContext *ctx = inlink->src;
176     MBContext *mb = ctx->priv;
177
178     if (av_image_check_size(mb->w, mb->h, 0, ctx) < 0)
179         return AVERROR(EINVAL);
180
181     inlink->w = mb->w;
182     inlink->h = mb->h;
183     inlink->time_base = mb->time_base;
184
185     return 0;
186 }
187
188 static void fill_from_cache(AVFilterContext *ctx, uint32_t *color, int *in_cidx, int *out_cidx, double py, double scale){
189     MBContext *mb = ctx->priv;
190     for(; *in_cidx < mb->cache_used; (*in_cidx)++){
191         Point *p= &mb->point_cache[*in_cidx];
192         int x;
193         if(p->p[1] > py)
194             break;
195         x= round((p->p[0] - mb->start_x) / scale + mb->w/2);
196         if(x<0 || x >= mb->w)
197             continue;
198         if(color) color[x] = p->val;
199         if(out_cidx && *out_cidx < mb->cache_allocated)
200             mb->next_cache[(*out_cidx)++]= *p;
201     }
202 }
203
204 static void draw_mandelbrot(AVFilterContext *ctx, uint32_t *color, int linesize, int64_t pts)
205 {
206     MBContext *mb = ctx->priv;
207     int x,y,i, in_cidx=0, next_cidx=0, tmp_cidx;
208     double scale= mb->start_scale*pow(mb->end_scale/mb->start_scale, pts/mb->end_pts);
209     int use_zyklus=0;
210     fill_from_cache(ctx, NULL, &in_cidx, NULL, mb->start_y+scale*(-mb->h/2-0.5), scale);
211     for(y=0; y<mb->h; y++){
212         const double ci=mb->start_y+scale*(y-mb->h/2);
213         memset(color+linesize*y, 0, sizeof(*color)*mb->w);
214         fill_from_cache(ctx, color+linesize*y, &in_cidx, &next_cidx, ci, scale);
215         tmp_cidx= in_cidx;
216         fill_from_cache(ctx, color+linesize*y, &tmp_cidx, NULL, ci + scale/2, scale);
217
218         for(x=0; x<mb->w; x++){
219             const double cr=mb->start_x+scale*(x-mb->w/2);
220             double zr=cr;
221             double zi=ci;
222             uint32_t c=0;
223
224             if(color[x + y*linesize] & 0xFF000000)
225                 continue;
226
227             use_zyklus= (x==0 || mb->inner!=BLACK ||color[x-1 + y*linesize] == 0xFF000000);
228
229             for(i=0; i<mb->maxiter; i++){
230                 double t;
231                 if(zr*zr + zi*zi > mb->bailout){
232                     switch(mb->outer){
233                     case            ITERATION_COUNT: zr = i - (SQR(zr-cr)+SQR(zi-ci) > SQR(mb->bailout)); break;
234                     case NORMALIZED_ITERATION_COUNT: zr= i + log2(log(mb->bailout) / log(zr*zr + zi*zi)); break;
235                     }
236                     c= lrintf((sin(zr)+1)*127) + lrintf((sin(zr/1.234)+1)*127)*256*256 + lrintf((sin(zr/100)+1)*127)*256;
237                     break;
238                 }
239                 t= zr*zr - zi*zi + cr;
240                 zi= 2*zr*zi + ci;
241                 if(use_zyklus){
242                     mb->zyklus[i][0]= t;
243                     mb->zyklus[i][1]= zi;
244                 }
245                 i++;
246                 zr= t*t - zi*zi+cr;
247                 zi= 2*t*zi + ci;
248                 if(use_zyklus){
249                     if(mb->zyklus[i>>1][0]==zr && mb->zyklus[i>>1][1]==zi)
250                         break;
251                     mb->zyklus[i][0]= zr;
252                     mb->zyklus[i][1]= zi;
253                 }
254             }
255             if(!c && mb->inner==PERIOD){
256                 int j;
257                 for(j=i-1; j; j--)
258                     if(SQR(mb->zyklus[j][0]-zr) + SQR(mb->zyklus[j][1]-zi) < 0.0000000000000001)
259                         break;
260                 if(j){
261                     c= i-j;
262                     c= ((c<<5)&0xE0) + ((c<<16)&0xE000) + ((c<<27)&0xE00000);
263                 }
264             }
265             c |= 0xFF000000;
266             color[x + y*linesize]= c;
267             if(next_cidx < mb->cache_allocated){
268                 mb->next_cache[next_cidx  ].p[0]= cr;
269                 mb->next_cache[next_cidx  ].p[1]= ci;
270                 mb->next_cache[next_cidx++].val = c;
271             }
272         }
273         fill_from_cache(ctx, NULL, &in_cidx, &next_cidx, ci + scale/2, scale);
274     }
275     FFSWAP(void*, mb->next_cache, mb->point_cache);
276     mb->cache_used = next_cidx;
277     if(mb->cache_used == mb->cache_allocated)
278         av_log(0, AV_LOG_INFO, "Mandelbrot cache is too small!\n");
279 }
280
281 static int request_frame(AVFilterLink *link)
282 {
283     MBContext *mb = link->src->priv;
284     AVFilterBufferRef *picref = avfilter_get_video_buffer(link, AV_PERM_WRITE, mb->w, mb->h);
285     picref->video->sample_aspect_ratio = (AVRational) {1, 1};
286     picref->pts = mb->pts++;
287     picref->pos = -1;
288
289     avfilter_start_frame(link, avfilter_ref_buffer(picref, ~0));
290     draw_mandelbrot(link->src, picref->data[0], picref->linesize[0]/4, picref->pts);
291     avfilter_draw_slice(link, 0, mb->h, 1);
292     avfilter_end_frame(link);
293     avfilter_unref_buffer(picref);
294
295     return 0;
296 }
297
298 AVFilter avfilter_vsrc_mandelbrot = {
299     .name        = "mandelbrot",
300     .description = NULL_IF_CONFIG_SMALL("Mandelbrot renderer"),
301
302     .priv_size = sizeof(MBContext),
303     .init      = init,
304     .uninit    = uninit,
305
306     .query_formats = query_formats,
307
308     .inputs    = (const AVFilterPad[]) {{ .name = NULL}},
309
310     .outputs   = (const AVFilterPad[]) {{ .name      = "default",
311                                     .type            = AVMEDIA_TYPE_VIDEO,
312                                     .request_frame   = request_frame,
313                                     .config_props    = config_props },
314                                   { .name = NULL}},
315 };