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