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