]> 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         av_log(ctx, AV_LOG_ERROR, "Invalid frame rate: %s\n", mb->rate);
136         return AVERROR(EINVAL);
137     }
138     mb->time_base.num = rate_q.den;
139     mb->time_base.den = rate_q.num;
140
141     mb->cache_allocated = mb->w * mb->h * 3;
142     mb->cache_used = 0;
143     mb->point_cache= av_malloc(sizeof(*mb->point_cache)*mb->cache_allocated);
144     mb-> next_cache= av_malloc(sizeof(*mb-> next_cache)*mb->cache_allocated);
145     mb-> zyklus    = av_malloc(sizeof(*mb->zyklus) * (mb->maxiter+16));
146
147     return 0;
148 }
149
150 static av_cold void uninit(AVFilterContext *ctx)
151 {
152     MBContext *mb = ctx->priv;
153
154     av_freep(&mb->rate);
155     av_freep(&mb->point_cache);
156     av_freep(&mb-> next_cache);
157     av_freep(&mb->zyklus);
158 }
159
160 static int query_formats(AVFilterContext *ctx)
161 {
162     static const enum PixelFormat pix_fmts[] = {
163         PIX_FMT_BGR32,
164         PIX_FMT_NONE
165     };
166
167     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
168     return 0;
169 }
170
171 static int config_props(AVFilterLink *inlink)
172 {
173     AVFilterContext *ctx = inlink->src;
174     MBContext *mb = ctx->priv;
175
176     if (av_image_check_size(mb->w, mb->h, 0, ctx) < 0)
177         return AVERROR(EINVAL);
178
179     inlink->w = mb->w;
180     inlink->h = mb->h;
181     inlink->time_base = mb->time_base;
182
183     return 0;
184 }
185
186 static void fill_from_cache(AVFilterContext *ctx, uint32_t *color, int *in_cidx, int *out_cidx, double py, double scale){
187     MBContext *mb = ctx->priv;
188     for(; *in_cidx < mb->cache_used; (*in_cidx)++){
189         Point *p= &mb->point_cache[*in_cidx];
190         int x;
191         if(p->p[1] > py)
192             break;
193         x= round((p->p[0] - mb->start_x) / scale + mb->w/2);
194         if(x<0 || x >= mb->w)
195             continue;
196         if(color) color[x] = p->val;
197         if(out_cidx && *out_cidx < mb->cache_allocated)
198             mb->next_cache[(*out_cidx)++]= *p;
199     }
200 }
201
202 static int interpol(MBContext *mb, uint32_t *color, int x, int y, int linesize)
203 {
204     uint32_t a,b,c,d, i;
205     uint32_t ipol=0xFF000000;
206     int dist;
207
208     if(!x || !y || x+1==mb->w || y+1==mb->h)
209         return 0;
210
211     dist= FFMAX(FFABS(x-(mb->w>>1))*mb->h, FFABS(y-(mb->h>>1))*mb->w);
212
213     if(dist<(mb->w*mb->h>>3))
214         return 0;
215
216     a=color[(x+1) + (y+0)*linesize];
217     b=color[(x-1) + (y+1)*linesize];
218     c=color[(x+0) + (y+1)*linesize];
219     d=color[(x+1) + (y+1)*linesize];
220
221     if(a&&c){
222         b= color[(x-1) + (y+0)*linesize];
223         d= color[(x+0) + (y-1)*linesize];
224     }else if(b&&d){
225         a= color[(x+1) + (y-1)*linesize];
226         c= color[(x-1) + (y-1)*linesize];
227     }else if(c){
228         d= color[(x+0) + (y-1)*linesize];
229         a= color[(x-1) + (y+0)*linesize];
230         b= color[(x+1) + (y-1)*linesize];
231     }else if(d){
232         c= color[(x-1) + (y-1)*linesize];
233         a= color[(x-1) + (y+0)*linesize];
234         b= color[(x+1) + (y-1)*linesize];
235     }else
236         return 0;
237
238     for(i=0; i<3; i++){
239         int s= 8*i;
240         uint8_t ac= a>>s;
241         uint8_t bc= b>>s;
242         uint8_t cc= c>>s;
243         uint8_t dc= d>>s;
244         int ipolab= (ac + bc);
245         int ipolcd= (cc + dc);
246         if(FFABS(ipolab - ipolcd) > 5)
247             return 0;
248         if(FFABS(ac-bc)+FFABS(cc-dc) > 20)
249             return 0;
250         ipol |= ((ipolab + ipolcd + 2)/4)<<s;
251     }
252     color[x + y*linesize]= ipol;
253     return 1;
254 }
255
256 static void draw_mandelbrot(AVFilterContext *ctx, uint32_t *color, int linesize, int64_t pts)
257 {
258     MBContext *mb = ctx->priv;
259     int x,y,i, in_cidx=0, next_cidx=0, tmp_cidx;
260     double scale= mb->start_scale*pow(mb->end_scale/mb->start_scale, pts/mb->end_pts);
261     int use_zyklus=0;
262     fill_from_cache(ctx, NULL, &in_cidx, NULL, mb->start_y+scale*(-mb->h/2-0.5), scale);
263     tmp_cidx= in_cidx;
264     memset(color, 0, sizeof(*color)*mb->w);
265     for(y=0; y<mb->h; y++){
266         int y1= y+1;
267         const double ci=mb->start_y+scale*(y-mb->h/2);
268         fill_from_cache(ctx, NULL, &in_cidx, &next_cidx, ci, scale);
269         if(y1<mb->h){
270             memset(color+linesize*y1, 0, sizeof(*color)*mb->w);
271             fill_from_cache(ctx, color+linesize*y1, &tmp_cidx, NULL, ci + 3*scale/2, scale);
272         }
273
274         for(x=0; x<mb->w; x++){
275             float av_uninit(epsilon);
276             const double cr=mb->start_x+scale*(x-mb->w/2);
277             double zr=cr;
278             double zi=ci;
279             uint32_t c=0;
280             double dv= mb->dither / (double)(1LL<<32);
281             mb->dither= mb->dither*1664525+1013904223;
282
283             if(color[x + y*linesize] & 0xFF000000)
284                 continue;
285             if(interpol(mb, color, x, y, linesize)){
286                 if(next_cidx < mb->cache_allocated){
287                     mb->next_cache[next_cidx  ].p[0]= cr;
288                     mb->next_cache[next_cidx  ].p[1]= ci;
289                     mb->next_cache[next_cidx++].val = color[x + y*linesize];
290                 }
291                 continue;
292             }
293
294             use_zyklus= (x==0 || mb->inner!=BLACK ||color[x-1 + y*linesize] == 0xFF000000);
295             if(use_zyklus)
296                 epsilon= scale*1*sqrt(SQR(x-mb->w/2) + SQR(y-mb->h/2))/mb->w;
297
298 #define Z_Z2_C(outr,outi,inr,ini)\
299             outr= inr*inr - ini*ini + cr;\
300             outi= 2*inr*ini + ci;
301
302 #define Z_Z2_C_ZYKLUS(outr,outi,inr,ini, Z)\
303             Z_Z2_C(outr,outi,inr,ini)\
304             if(use_zyklus){\
305                 if(Z && fabs(mb->zyklus[i>>1][0]-outr)+fabs(mb->zyklus[i>>1][1]-outi) <= epsilon)\
306                     break;\
307             }\
308             mb->zyklus[i][0]= outr;\
309             mb->zyklus[i][1]= outi;\
310
311
312
313             for(i=0; i<mb->maxiter-8; i++){
314                 double t;
315                 Z_Z2_C_ZYKLUS(t, zi, zr, zi, 0)
316                 i++;
317                 Z_Z2_C_ZYKLUS(zr, zi, t, zi, 1)
318                 i++;
319                 Z_Z2_C_ZYKLUS(t, zi, zr, zi, 0)
320                 i++;
321                 Z_Z2_C_ZYKLUS(zr, zi, t, zi, 1)
322                 i++;
323                 Z_Z2_C_ZYKLUS(t, zi, zr, zi, 0)
324                 i++;
325                 Z_Z2_C_ZYKLUS(zr, zi, t, zi, 1)
326                 i++;
327                 Z_Z2_C_ZYKLUS(t, zi, zr, zi, 0)
328                 i++;
329                 Z_Z2_C_ZYKLUS(zr, zi, t, zi, 1)
330                 if(zr*zr + zi*zi > mb->bailout){
331                     i-= FFMIN(7, i);
332                     for(; i<mb->maxiter; i++){
333                         zr= mb->zyklus[i][0];
334                         zi= mb->zyklus[i][1];
335                         if(zr*zr + zi*zi > mb->bailout){
336                             switch(mb->outer){
337                             case            ITERATION_COUNT: zr = i; break;
338                             case NORMALIZED_ITERATION_COUNT: zr= i + log2(log(mb->bailout) / log(zr*zr + zi*zi)); break;
339                             }
340                             c= lrintf((sin(zr)+1)*127) + lrintf((sin(zr/1.234)+1)*127)*256*256 + lrintf((sin(zr/100)+1)*127)*256;
341                             break;
342                         }
343                     }
344                     break;
345                 }
346             }
347             if(!c){
348                 if(mb->inner==PERIOD){
349                 int j;
350                 for(j=i-1; j; j--)
351                     if(SQR(mb->zyklus[j][0]-zr) + SQR(mb->zyklus[j][1]-zi) < epsilon*epsilon*10)
352                         break;
353                 if(j){
354                     c= i-j;
355                     c= ((c<<5)&0xE0) + ((c<<16)&0xE000) + ((c<<27)&0xE00000);
356                 }
357                 }else if(mb->inner==CONVTIME){
358                     c= floor(i*255.0/mb->maxiter+dv)*0x010101;
359                 } else if(mb->inner==MINCOL){
360                     int j;
361                     double closest=9999;
362                     int closest_index=0;
363                     for(j=i-1; j>=0; j--)
364                         if(SQR(mb->zyklus[j][0]) + SQR(mb->zyklus[j][1]) < closest){
365                             closest= SQR(mb->zyklus[j][0]) + SQR(mb->zyklus[j][1]);
366                             closest_index= j;
367                         }
368                     closest = sqrt(closest);
369                     c= lrintf((mb->zyklus[closest_index][0]/closest+1)*127+dv) + lrintf((mb->zyklus[closest_index][1]/closest+1)*127+dv)*256;
370                 }
371             }
372             c |= 0xFF000000;
373             color[x + y*linesize]= c;
374             if(next_cidx < mb->cache_allocated){
375                 mb->next_cache[next_cidx  ].p[0]= cr;
376                 mb->next_cache[next_cidx  ].p[1]= ci;
377                 mb->next_cache[next_cidx++].val = c;
378             }
379         }
380         fill_from_cache(ctx, NULL, &in_cidx, &next_cidx, ci + scale/2, scale);
381     }
382     FFSWAP(void*, mb->next_cache, mb->point_cache);
383     mb->cache_used = next_cidx;
384     if(mb->cache_used == mb->cache_allocated)
385         av_log(0, AV_LOG_INFO, "Mandelbrot cache is too small!\n");
386 }
387
388 static int request_frame(AVFilterLink *link)
389 {
390     MBContext *mb = link->src->priv;
391     AVFilterBufferRef *picref = ff_get_video_buffer(link, AV_PERM_WRITE, mb->w, mb->h);
392     picref->video->sample_aspect_ratio = (AVRational) {1, 1};
393     picref->pts = mb->pts++;
394     picref->pos = -1;
395
396     ff_start_frame(link, avfilter_ref_buffer(picref, ~0));
397     draw_mandelbrot(link->src, (uint32_t*)picref->data[0], picref->linesize[0]/4, picref->pts);
398     ff_draw_slice(link, 0, mb->h, 1);
399     ff_end_frame(link);
400     avfilter_unref_buffer(picref);
401
402     return 0;
403 }
404
405 AVFilter avfilter_vsrc_mandelbrot = {
406     .name        = "mandelbrot",
407     .description = NULL_IF_CONFIG_SMALL("Render a Mandelbrot fractal."),
408
409     .priv_size = sizeof(MBContext),
410     .init      = init,
411     .uninit    = uninit,
412
413     .query_formats = query_formats,
414
415     .inputs    = (const AVFilterPad[]) {{ .name = NULL}},
416
417     .outputs   = (const AVFilterPad[]) {{ .name      = "default",
418                                     .type            = AVMEDIA_TYPE_VIDEO,
419                                     .request_frame   = request_frame,
420                                     .config_props    = config_props },
421                                   { .name = NULL}},
422 };