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