]> git.sesse.net Git - ffmpeg/blob - libavfilter/vsrc_mandelbrot.c
lavfi: add astreamsync audio filter.
[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     CONVTIME,
47     MINCOL,
48 };
49
50 typedef struct Point {
51     double p[2];
52     uint32_t val;
53 } Point;
54
55 typedef struct {
56     const AVClass *class;
57     int w, h;
58     AVRational time_base;
59     uint64_t pts;
60     char *size, *rate;
61     int maxiter;
62     double start_x;
63     double start_y;
64     double start_scale;
65     double end_scale;
66     double end_pts;
67     double bailout;
68     enum Outer outer;
69     enum Inner inner;
70     int cache_allocated;
71     int cache_used;
72     Point *point_cache;
73     Point *next_cache;
74     double (*zyklus)[2];
75     uint32_t dither;
76 } MBContext;
77
78 #define OFFSET(x) offsetof(MBContext, x)
79
80 static const AVOption mandelbrot_options[] = {
81     {"size",        "set frame size",                OFFSET(size),    AV_OPT_TYPE_STRING,     {.str="640x480"},  CHAR_MIN, CHAR_MAX },
82     {"s",           "set frame size",                OFFSET(size),    AV_OPT_TYPE_STRING,     {.str="640x480"},  CHAR_MIN, CHAR_MAX },
83     {"rate",        "set frame rate",                OFFSET(rate),    AV_OPT_TYPE_STRING,     {.str="25"},  CHAR_MIN, CHAR_MAX },
84     {"r",           "set frame rate",                OFFSET(rate),    AV_OPT_TYPE_STRING,     {.str="25"},  CHAR_MIN, CHAR_MAX },
85     {"maxiter",     "set max iterations number",     OFFSET(maxiter), AV_OPT_TYPE_INT,        {.dbl=7189},  1,        INT_MAX  },
86     {"start_x",     "set the initial x position",    OFFSET(start_x), AV_OPT_TYPE_DOUBLE,     {.dbl=-0.743643887037158704752191506114774}, -100, 100  },
87     {"start_y",     "set the initial y position",    OFFSET(start_y), AV_OPT_TYPE_DOUBLE,     {.dbl=-0.131825904205311970493132056385139}, -100, 100  },
88     {"start_scale", "set the initial scale value",   OFFSET(start_scale), AV_OPT_TYPE_DOUBLE, {.dbl=3.0},  0, FLT_MAX },
89     {"end_scale",   "set the terminal scale value",  OFFSET(end_scale), AV_OPT_TYPE_DOUBLE,   {.dbl=0.3},  0, FLT_MAX },
90     {"end_pts",     "set the terminal pts value",    OFFSET(end_pts), AV_OPT_TYPE_DOUBLE,     {.dbl=400},  0, INT64_MAX },
91     {"bailout",     "set the bailout value",         OFFSET(bailout), AV_OPT_TYPE_DOUBLE,     {.dbl=10},   0, FLT_MAX },
92
93     {"outer",       "set outer coloring mode",       OFFSET(outer), AV_OPT_TYPE_INT, {.dbl=NORMALIZED_ITERATION_COUNT}, 0, INT_MAX, 0, "outer"},
94     {"iteration_count", "set iteration count mode",  0, AV_OPT_TYPE_CONST, {.dbl=ITERATION_COUNT}, INT_MIN, INT_MAX, 0, "outer" },
95     {"normalized_iteration_count", "set normalized iteration count mode",   0, AV_OPT_TYPE_CONST, {.dbl=NORMALIZED_ITERATION_COUNT}, INT_MIN, INT_MAX, 0, "outer" },
96
97     {"inner",       "set inner coloring mode",       OFFSET(inner), AV_OPT_TYPE_INT, {.dbl=MINCOL}, 0, INT_MAX, 0, "inner"},
98     {"black",       "set black mode",                0, AV_OPT_TYPE_CONST, {.dbl=BLACK}, INT_MIN, INT_MAX, 0, "inner" },
99     {"period",      "set period mode",               0, AV_OPT_TYPE_CONST, {.dbl=PERIOD}, INT_MIN, INT_MAX, 0, "inner" },
100     {"convergence", "show time until convergence",   0, AV_OPT_TYPE_CONST, {.dbl=CONVTIME}, INT_MIN, INT_MAX, 0, "inner" },
101     {"mincol",      "color based on point closest to the origin of the iterations",   0, AV_OPT_TYPE_CONST, {.dbl=MINCOL}, INT_MIN, INT_MAX, 0, "inner" },
102
103     {NULL},
104 };
105
106 static const char *mandelbrot_get_name(void *ctx)
107 {
108     return "mandelbrot";
109 }
110
111 static const AVClass mandelbrot_class = {
112     "MBContext",
113     mandelbrot_get_name,
114     mandelbrot_options
115 };
116
117 static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
118 {
119     MBContext *mb = ctx->priv;
120     AVRational rate_q;
121     int err;
122
123     mb->class = &mandelbrot_class;
124     av_opt_set_defaults(mb);
125
126     if ((err = (av_set_options_string(mb, args, "=", ":"))) < 0) {
127         av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
128         return err;
129     }
130     mb->bailout *= mb->bailout;
131
132     if (av_parse_video_size(&mb->w, &mb->h, mb->size) < 0) {
133         av_log(ctx, AV_LOG_ERROR, "Invalid frame size: %s\n", mb->size);
134         return AVERROR(EINVAL);
135     }
136     mb->start_scale /=mb->h;
137     mb->end_scale /=mb->h;
138
139     if (av_parse_video_rate(&rate_q, mb->rate) < 0 ||
140         rate_q.den <= 0 || rate_q.num <= 0) {
141         av_log(ctx, AV_LOG_ERROR, "Invalid frame rate: %s\n", mb->rate);
142         return AVERROR(EINVAL);
143     }
144     mb->time_base.num = rate_q.den;
145     mb->time_base.den = rate_q.num;
146
147     mb->cache_allocated = mb->w * mb->h * 3;
148     mb->cache_used = 0;
149     mb->point_cache= av_malloc(sizeof(*mb->point_cache)*mb->cache_allocated);
150     mb-> next_cache= av_malloc(sizeof(*mb-> next_cache)*mb->cache_allocated);
151     mb-> zyklus    = av_malloc(sizeof(*mb->zyklus) * (mb->maxiter+16));
152
153     return 0;
154 }
155
156 static av_cold void uninit(AVFilterContext *ctx)
157 {
158     MBContext *mb = ctx->priv;
159
160     av_freep(&mb->size);
161     av_freep(&mb->rate);
162     av_freep(&mb->point_cache);
163     av_freep(&mb-> next_cache);
164     av_freep(&mb->zyklus);
165 }
166
167 static int query_formats(AVFilterContext *ctx)
168 {
169     static const enum PixelFormat pix_fmts[] = {
170         PIX_FMT_BGR32,
171         PIX_FMT_NONE
172     };
173
174     avfilter_set_common_pixel_formats(ctx, avfilter_make_format_list(pix_fmts));
175     return 0;
176 }
177
178 static int config_props(AVFilterLink *inlink)
179 {
180     AVFilterContext *ctx = inlink->src;
181     MBContext *mb = ctx->priv;
182
183     if (av_image_check_size(mb->w, mb->h, 0, ctx) < 0)
184         return AVERROR(EINVAL);
185
186     inlink->w = mb->w;
187     inlink->h = mb->h;
188     inlink->time_base = mb->time_base;
189
190     return 0;
191 }
192
193 static void fill_from_cache(AVFilterContext *ctx, uint32_t *color, int *in_cidx, int *out_cidx, double py, double scale){
194     MBContext *mb = ctx->priv;
195     for(; *in_cidx < mb->cache_used; (*in_cidx)++){
196         Point *p= &mb->point_cache[*in_cidx];
197         int x;
198         if(p->p[1] > py)
199             break;
200         x= round((p->p[0] - mb->start_x) / scale + mb->w/2);
201         if(x<0 || x >= mb->w)
202             continue;
203         if(color) color[x] = p->val;
204         if(out_cidx && *out_cidx < mb->cache_allocated)
205             mb->next_cache[(*out_cidx)++]= *p;
206     }
207 }
208
209 static int interpol(MBContext *mb, uint32_t *color, int x, int y, int linesize)
210 {
211     uint32_t a,b,c,d, i;
212     uint32_t ipol=0xFF000000;
213     int dist;
214
215     if(!x || !y || x+1==mb->w || y+1==mb->h)
216         return 0;
217
218     dist= FFMAX(FFABS(x-(mb->w>>1))*mb->h, FFABS(y-(mb->h>>1))*mb->w);
219
220     if(dist<(mb->w*mb->h>>3))
221         return 0;
222
223     a=color[(x+1) + (y+0)*linesize];
224     b=color[(x-1) + (y+1)*linesize];
225     c=color[(x+0) + (y+1)*linesize];
226     d=color[(x+1) + (y+1)*linesize];
227
228     if(a&&c){
229         b= color[(x-1) + (y+0)*linesize];
230         d= color[(x+0) + (y-1)*linesize];
231     }else if(b&&d){
232         a= color[(x+1) + (y-1)*linesize];
233         c= color[(x-1) + (y-1)*linesize];
234     }else if(c){
235         d= color[(x+0) + (y-1)*linesize];
236         a= color[(x-1) + (y+0)*linesize];
237         b= color[(x+1) + (y-1)*linesize];
238     }else if(d){
239         c= color[(x-1) + (y-1)*linesize];
240         a= color[(x-1) + (y+0)*linesize];
241         b= color[(x+1) + (y-1)*linesize];
242     }else
243         return 0;
244
245     for(i=0; i<3; i++){
246         int s= 8*i;
247         uint8_t ac= a>>s;
248         uint8_t bc= b>>s;
249         uint8_t cc= c>>s;
250         uint8_t dc= d>>s;
251         int ipolab= (ac + bc);
252         int ipolcd= (cc + dc);
253         if(FFABS(ipolab - ipolcd) > 5)
254             return 0;
255         if(FFABS(ac-bc)+FFABS(cc-dc) > 20)
256             return 0;
257         ipol |= ((ipolab + ipolcd + 2)/4)<<s;
258     }
259     color[x + y*linesize]= ipol;
260     return 1;
261 }
262
263 static void draw_mandelbrot(AVFilterContext *ctx, uint32_t *color, int linesize, int64_t pts)
264 {
265     MBContext *mb = ctx->priv;
266     int x,y,i, in_cidx=0, next_cidx=0, tmp_cidx;
267     double scale= mb->start_scale*pow(mb->end_scale/mb->start_scale, pts/mb->end_pts);
268     int use_zyklus=0;
269     fill_from_cache(ctx, NULL, &in_cidx, NULL, mb->start_y+scale*(-mb->h/2-0.5), scale);
270     tmp_cidx= in_cidx;
271     memset(color, 0, sizeof(*color)*mb->w);
272     for(y=0; y<mb->h; y++){
273         int y1= y+1;
274         const double ci=mb->start_y+scale*(y-mb->h/2);
275         fill_from_cache(ctx, NULL, &in_cidx, &next_cidx, ci, scale);
276         if(y1<mb->h){
277             memset(color+linesize*y1, 0, sizeof(*color)*mb->w);
278             fill_from_cache(ctx, color+linesize*y1, &tmp_cidx, NULL, ci + 3*scale/2, scale);
279         }
280
281         for(x=0; x<mb->w; x++){
282             float av_uninit(epsilon);
283             const double cr=mb->start_x+scale*(x-mb->w/2);
284             double zr=cr;
285             double zi=ci;
286             uint32_t c=0;
287             double dv= mb->dither / (double)(1LL<<32);
288             mb->dither= mb->dither*1664525+1013904223;
289
290             if(color[x + y*linesize] & 0xFF000000)
291                 continue;
292             if(interpol(mb, color, x, y, linesize)){
293                 if(next_cidx < mb->cache_allocated){
294                     mb->next_cache[next_cidx  ].p[0]= cr;
295                     mb->next_cache[next_cidx  ].p[1]= ci;
296                     mb->next_cache[next_cidx++].val = color[x + y*linesize];
297                 }
298                 continue;
299             }
300
301             use_zyklus= (x==0 || mb->inner!=BLACK ||color[x-1 + y*linesize] == 0xFF000000);
302             if(use_zyklus)
303                 epsilon= scale*1*sqrt(SQR(x-mb->w/2) + SQR(y-mb->h/2))/mb->w;
304
305 #define Z_Z2_C(outr,outi,inr,ini)\
306             outr= inr*inr - ini*ini + cr;\
307             outi= 2*inr*ini + ci;
308
309 #define Z_Z2_C_ZYKLUS(outr,outi,inr,ini, Z)\
310             Z_Z2_C(outr,outi,inr,ini)\
311             if(use_zyklus){\
312                 if(Z && fabs(mb->zyklus[i>>1][0]-outr)+fabs(mb->zyklus[i>>1][1]-outi) <= epsilon)\
313                     break;\
314             }\
315             mb->zyklus[i][0]= outr;\
316             mb->zyklus[i][1]= outi;\
317
318
319
320             for(i=0; i<mb->maxiter-8; i++){
321                 double t;
322                 Z_Z2_C_ZYKLUS(t, zi, zr, zi, 0)
323                 i++;
324                 Z_Z2_C_ZYKLUS(zr, zi, t, zi, 1)
325                 i++;
326                 Z_Z2_C_ZYKLUS(t, zi, zr, zi, 0)
327                 i++;
328                 Z_Z2_C_ZYKLUS(zr, zi, t, zi, 1)
329                 i++;
330                 Z_Z2_C_ZYKLUS(t, zi, zr, zi, 0)
331                 i++;
332                 Z_Z2_C_ZYKLUS(zr, zi, t, zi, 1)
333                 i++;
334                 Z_Z2_C_ZYKLUS(t, zi, zr, zi, 0)
335                 i++;
336                 Z_Z2_C_ZYKLUS(zr, zi, t, zi, 1)
337                 if(zr*zr + zi*zi > mb->bailout){
338                     i-= FFMIN(7, i);
339                     for(; i<mb->maxiter; i++){
340                         zr= mb->zyklus[i][0];
341                         zi= mb->zyklus[i][1];
342                         if(zr*zr + zi*zi > mb->bailout){
343                             switch(mb->outer){
344                             case            ITERATION_COUNT: zr = i; break;
345                             case NORMALIZED_ITERATION_COUNT: zr= i + log2(log(mb->bailout) / log(zr*zr + zi*zi)); break;
346                             }
347                             c= lrintf((sin(zr)+1)*127) + lrintf((sin(zr/1.234)+1)*127)*256*256 + lrintf((sin(zr/100)+1)*127)*256;
348                             break;
349                         }
350                     }
351                     break;
352                 }
353             }
354             if(!c){
355                 if(mb->inner==PERIOD){
356                 int j;
357                 for(j=i-1; j; j--)
358                     if(SQR(mb->zyklus[j][0]-zr) + SQR(mb->zyklus[j][1]-zi) < epsilon*epsilon*10)
359                         break;
360                 if(j){
361                     c= i-j;
362                     c= ((c<<5)&0xE0) + ((c<<16)&0xE000) + ((c<<27)&0xE00000);
363                 }
364                 }else if(mb->inner==CONVTIME){
365                     c= floor(i*255.0/mb->maxiter+dv)*0x010101;
366                 } else if(mb->inner==MINCOL){
367                     int j;
368                     double closest=9999;
369                     int closest_index=0;
370                     for(j=i-1; j>=0; j--)
371                         if(SQR(mb->zyklus[j][0]) + SQR(mb->zyklus[j][1]) < closest){
372                             closest= SQR(mb->zyklus[j][0]) + SQR(mb->zyklus[j][1]);
373                             closest_index= j;
374                         }
375                     closest = sqrt(closest);
376                     c= lrintf((mb->zyklus[closest_index][0]/closest+1)*127+dv) + lrintf((mb->zyklus[closest_index][1]/closest+1)*127+dv)*256;
377                 }
378             }
379             c |= 0xFF000000;
380             color[x + y*linesize]= c;
381             if(next_cidx < mb->cache_allocated){
382                 mb->next_cache[next_cidx  ].p[0]= cr;
383                 mb->next_cache[next_cidx  ].p[1]= ci;
384                 mb->next_cache[next_cidx++].val = c;
385             }
386         }
387         fill_from_cache(ctx, NULL, &in_cidx, &next_cidx, ci + scale/2, scale);
388     }
389     FFSWAP(void*, mb->next_cache, mb->point_cache);
390     mb->cache_used = next_cidx;
391     if(mb->cache_used == mb->cache_allocated)
392         av_log(0, AV_LOG_INFO, "Mandelbrot cache is too small!\n");
393 }
394
395 static int request_frame(AVFilterLink *link)
396 {
397     MBContext *mb = link->src->priv;
398     AVFilterBufferRef *picref = avfilter_get_video_buffer(link, AV_PERM_WRITE, mb->w, mb->h);
399     picref->video->sample_aspect_ratio = (AVRational) {1, 1};
400     picref->pts = mb->pts++;
401     picref->pos = -1;
402
403     avfilter_start_frame(link, avfilter_ref_buffer(picref, ~0));
404     draw_mandelbrot(link->src, (uint32_t*)picref->data[0], picref->linesize[0]/4, picref->pts);
405     avfilter_draw_slice(link, 0, mb->h, 1);
406     avfilter_end_frame(link);
407     avfilter_unref_buffer(picref);
408
409     return 0;
410 }
411
412 AVFilter avfilter_vsrc_mandelbrot = {
413     .name        = "mandelbrot",
414     .description = NULL_IF_CONFIG_SMALL("Mandelbrot fractal renderer"),
415
416     .priv_size = sizeof(MBContext),
417     .init      = init,
418     .uninit    = uninit,
419
420     .query_formats = query_formats,
421
422     .inputs    = (const AVFilterPad[]) {{ .name = NULL}},
423
424     .outputs   = (const AVFilterPad[]) {{ .name      = "default",
425                                     .type            = AVMEDIA_TYPE_VIDEO,
426                                     .request_frame   = request_frame,
427                                     .config_props    = config_props },
428                                   { .name = NULL}},
429 };