]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_lenscorrection.c
avfilter/vf_lenscorrection: allow to change colors of unmapped pixels
[ffmpeg] / libavfilter / vf_lenscorrection.c
1 /*
2  * Copyright (C) 2007 Richard Spindler (author of frei0r plugin from which this was derived)
3  * Copyright (C) 2014 Daniel Oberhoff
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * Lenscorrection filter, algorithm from the frei0r plugin with the same name
25 */
26 #include <stdlib.h>
27 #include <math.h>
28
29 #include "libavutil/colorspace.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/intreadwrite.h"
32 #include "libavutil/pixdesc.h"
33
34 #include "avfilter.h"
35 #include "drawutils.h"
36 #include "internal.h"
37 #include "video.h"
38
39 typedef struct LenscorrectionCtx {
40     const AVClass *av_class;
41     int width;
42     int height;
43     int hsub, vsub;
44     int depth;
45     int nb_planes;
46     double cx, cy, k1, k2;
47     int interpolation;
48     uint8_t fill_rgba[4];
49     int fill_color[4];
50
51     int32_t *correction[4];
52
53     int (*filter_slice)(AVFilterContext *ctx, void *arg, int job, int nb_jobs);
54 } LenscorrectionCtx;
55
56 #define OFFSET(x) offsetof(LenscorrectionCtx, x)
57 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
58 static const AVOption lenscorrection_options[] = {
59     { "cx", "set relative center x", OFFSET(cx), AV_OPT_TYPE_DOUBLE, {.dbl=0.5}, 0, 1, .flags=FLAGS },
60     { "cy", "set relative center y", OFFSET(cy), AV_OPT_TYPE_DOUBLE, {.dbl=0.5}, 0, 1, .flags=FLAGS },
61     { "k1", "set quadratic distortion factor", OFFSET(k1), AV_OPT_TYPE_DOUBLE, {.dbl=0.0}, -1, 1, .flags=FLAGS },
62     { "k2", "set double quadratic distortion factor", OFFSET(k2), AV_OPT_TYPE_DOUBLE, {.dbl=0.0}, -1, 1, .flags=FLAGS },
63     { "i",  "set interpolation type", OFFSET(interpolation), AV_OPT_TYPE_INT, {.i64=0}, 0, 64, .flags=FLAGS, "i" },
64     {  "nearest",  "nearest neighbour", 0,                   AV_OPT_TYPE_CONST, {.i64=0},0, 0, .flags=FLAGS, "i" },
65     {  "bilinear", "bilinear",          0,                   AV_OPT_TYPE_CONST, {.i64=1},0, 0, .flags=FLAGS, "i" },
66     { "fc", "set the color of the unmapped pixels", OFFSET(fill_rgba), AV_OPT_TYPE_COLOR, {.str="black@0"}, .flags = FLAGS },
67     { NULL }
68 };
69
70 AVFILTER_DEFINE_CLASS(lenscorrection);
71
72 typedef struct ThreadData {
73     AVFrame *in, *out;
74     int w, h;
75     int depth;
76     int plane;
77     int fill_color;
78     int xcenter, ycenter;
79     int32_t *correction;
80 } ThreadData;
81
82 #define NEAREST(type, name)                                                    \
83 static int filter##name##_slice(AVFilterContext *ctx, void *arg, int job,      \
84                                 int nb_jobs)                                   \
85 {                                                                              \
86     ThreadData *td = arg;                                                      \
87     AVFrame *in = td->in;                                                      \
88     AVFrame *out = td->out;                                                    \
89                                                                                \
90     const int fill_color = td->fill_color;                                     \
91     const int w = td->w, h = td->h;                                            \
92     const int xcenter = td->xcenter;                                           \
93     const int ycenter = td->ycenter;                                           \
94     const int start = (h *  job   ) / nb_jobs;                                 \
95     const int end   = (h * (job+1)) / nb_jobs;                                 \
96     const int plane = td->plane;                                               \
97     const int inlinesize = in->linesize[plane] / sizeof(type);                 \
98     const int outlinesize = out->linesize[plane] / sizeof(type);               \
99     const type *indata = (const type *)in->data[plane];                        \
100     type *outrow = (type *)out->data[plane] + start * outlinesize;             \
101     for (int i = start; i < end; i++, outrow += outlinesize) {                 \
102         const int off_y = i - ycenter;                                         \
103         type *out = outrow;                                                    \
104         for (int j = 0; j < w; j++) {                                          \
105             const int off_x = j - xcenter;                                     \
106             const int64_t radius_mult = td->correction[j + i*w];               \
107             const int x = xcenter + ((radius_mult * off_x + (1<<23))>>24);     \
108             const int y = ycenter + ((radius_mult * off_y + (1<<23))>>24);     \
109             const char isvalid = x >= 0 && x < w && y >= 0 && y < h;           \
110             *out++ =  isvalid ? indata[y * inlinesize + x] : fill_color;       \
111         }                                                                      \
112     }                                                                          \
113     return 0;                                                                  \
114 }
115
116
117 NEAREST(uint8_t, 8)
118 NEAREST(uint16_t, 16)
119
120 #define BILINEAR(type, name)                                                   \
121 static int filter##name##_slice_bilinear(AVFilterContext *ctx, void *arg,      \
122                                          int job, int nb_jobs)                 \
123 {                                                                              \
124     ThreadData *td = arg;                                                      \
125     AVFrame *in = td->in;                                                      \
126     AVFrame *out = td->out;                                                    \
127                                                                                \
128     const int fill_color = td->fill_color;                                     \
129     const int depth = td->depth;                                               \
130     const uint64_t max = (1 << 24) - 1;                                        \
131     const uint64_t add = (1 << 23);                                            \
132     const int w = td->w, h = td->h;                                            \
133     const int xcenter = td->xcenter;                                           \
134     const int ycenter = td->ycenter;                                           \
135     const int start = (h *  job   ) / nb_jobs;                                 \
136     const int end   = (h * (job+1)) / nb_jobs;                                 \
137     const int plane = td->plane;                                               \
138     const int inlinesize = in->linesize[plane] / sizeof(type);                 \
139     const int outlinesize = out->linesize[plane] / sizeof(type);               \
140     const type *indata = (const type *)in->data[plane];                        \
141     type *outrow = (type *)out->data[plane] + start * outlinesize;             \
142                                                                                \
143     for (int i = start; i < end; i++, outrow += outlinesize) {                 \
144         const int off_y = i - ycenter;                                         \
145         type *out = outrow;                                                    \
146                                                                                \
147         for (int j = 0; j < w; j++) {                                          \
148             const int off_x = j - xcenter;                                     \
149             const int64_t radius_mult = td->correction[j + i*w];               \
150             const int x = xcenter + ((radius_mult * off_x + (1<<23)) >> 24);   \
151             const int y = ycenter + ((radius_mult * off_y + (1<<23)) >> 24);   \
152             const char isvalid = x >= 0 && x <= w - 1 && y >= 0 && y <= h - 1; \
153                                                                                \
154             if (isvalid) {                                                     \
155                 const int nx = FFMIN(x + 1, w - 1);                            \
156                 const int ny = FFMIN(y + 1, h - 1);                            \
157                 const uint64_t du = off_x >= 0 ? (radius_mult * off_x + add) & max : max - ((radius_mult * -off_x + add) & max); \
158                 const uint64_t dv = off_y >= 0 ? (radius_mult * off_y + add) & max : max - ((radius_mult * -off_y + add) & max); \
159                 const uint64_t p0 = indata[ y * inlinesize +  x];              \
160                 const uint64_t p1 = indata[ y * inlinesize + nx];              \
161                 const uint64_t p2 = indata[ny * inlinesize +  x];              \
162                 const uint64_t p3 = indata[ny * inlinesize + nx];              \
163                 uint64_t sum = 0;                                              \
164                                                                                \
165                 sum += (max - du) * (max - dv) * p0;                           \
166                 sum += (      du) * (max - dv) * p1;                           \
167                 sum += (max - du) * (      dv) * p2;                           \
168                 sum += (      du) * (      dv) * p3;                           \
169                                                                                \
170                 out[j] = av_clip_uintp2_c((sum + (1ULL << 47)) >> 48, depth);  \
171             } else {                                                           \
172                 out[j] = fill_color;                                           \
173             }                                                                  \
174         }                                                                      \
175     }                                                                          \
176                                                                                \
177     return 0;                                                                  \
178 }
179
180 BILINEAR(uint8_t, 8)
181 BILINEAR(uint16_t, 16)
182
183 static int query_formats(AVFilterContext *ctx)
184 {
185     static const enum AVPixelFormat pix_fmts[] = {
186         AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY9,
187         AV_PIX_FMT_GRAY10, AV_PIX_FMT_GRAY12, AV_PIX_FMT_GRAY14,
188         AV_PIX_FMT_GRAY16,
189         AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
190         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
191         AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P,
192         AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P,
193         AV_PIX_FMT_YUVJ440P, AV_PIX_FMT_YUVJ444P,
194         AV_PIX_FMT_YUVJ411P,
195         AV_PIX_FMT_YUV420P9, AV_PIX_FMT_YUV422P9, AV_PIX_FMT_YUV444P9,
196         AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV444P10,
197         AV_PIX_FMT_YUV440P10,
198         AV_PIX_FMT_YUV444P12, AV_PIX_FMT_YUV422P12, AV_PIX_FMT_YUV420P12,
199         AV_PIX_FMT_YUV440P12,
200         AV_PIX_FMT_YUV444P14, AV_PIX_FMT_YUV422P14, AV_PIX_FMT_YUV420P14,
201         AV_PIX_FMT_YUV420P16, AV_PIX_FMT_YUV422P16, AV_PIX_FMT_YUV444P16,
202         AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRP9, AV_PIX_FMT_GBRP10,
203         AV_PIX_FMT_GBRP12, AV_PIX_FMT_GBRP14, AV_PIX_FMT_GBRP16,
204         AV_PIX_FMT_YUVA420P,  AV_PIX_FMT_YUVA422P,   AV_PIX_FMT_YUVA444P,
205         AV_PIX_FMT_YUVA444P9, AV_PIX_FMT_YUVA444P10, AV_PIX_FMT_YUVA444P12, AV_PIX_FMT_YUVA444P16,
206         AV_PIX_FMT_YUVA422P9, AV_PIX_FMT_YUVA422P10, AV_PIX_FMT_YUVA422P12, AV_PIX_FMT_YUVA422P16,
207         AV_PIX_FMT_YUVA420P9, AV_PIX_FMT_YUVA420P10, AV_PIX_FMT_YUVA420P16,
208         AV_PIX_FMT_GBRAP,     AV_PIX_FMT_GBRAP10,    AV_PIX_FMT_GBRAP12,    AV_PIX_FMT_GBRAP16,
209         AV_PIX_FMT_NONE
210     };
211     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
212     if (!fmts_list)
213         return AVERROR(ENOMEM);
214     return ff_set_common_formats(ctx, fmts_list);
215 }
216
217 static av_cold void uninit(AVFilterContext *ctx)
218 {
219     LenscorrectionCtx *rect = ctx->priv;
220     int i;
221
222     for (i = 0; i < FF_ARRAY_ELEMS(rect->correction); i++) {
223         av_freep(&rect->correction[i]);
224     }
225 }
226
227 static int config_props(AVFilterLink *outlink)
228 {
229     AVFilterContext *ctx = outlink->src;
230     LenscorrectionCtx *rect = ctx->priv;
231     AVFilterLink *inlink = ctx->inputs[0];
232     const AVPixFmtDescriptor *pixdesc = av_pix_fmt_desc_get(inlink->format);
233     int is_rgb = !!(pixdesc->flags & AV_PIX_FMT_FLAG_RGB);
234     uint8_t rgba_map[4];
235     int factor;
236
237     ff_fill_rgba_map(rgba_map, inlink->format);
238     rect->depth = pixdesc->comp[0].depth;
239     factor = 1 << (rect->depth - 8);
240     rect->hsub = pixdesc->log2_chroma_w;
241     rect->vsub = pixdesc->log2_chroma_h;
242     outlink->w = rect->width = inlink->w;
243     outlink->h = rect->height = inlink->h;
244     rect->nb_planes = av_pix_fmt_count_planes(inlink->format);
245     rect->filter_slice = rect->depth <= 8 ? filter8_slice : filter16_slice;
246     if (rect->interpolation)
247         rect->filter_slice = rect->depth <= 8 ? filter8_slice_bilinear : filter16_slice_bilinear;
248
249     if (is_rgb) {
250         rect->fill_color[rgba_map[0]] = rect->fill_rgba[0] * factor;
251         rect->fill_color[rgba_map[1]] = rect->fill_rgba[1] * factor;
252         rect->fill_color[rgba_map[2]] = rect->fill_rgba[2] * factor;
253         rect->fill_color[rgba_map[3]] = rect->fill_rgba[3] * factor;
254     } else {
255         rect->fill_color[0] = RGB_TO_Y_BT709(rect->fill_rgba[0], rect->fill_rgba[1], rect->fill_rgba[2]) * factor;
256         rect->fill_color[1] = RGB_TO_U_BT709(rect->fill_rgba[0], rect->fill_rgba[1], rect->fill_rgba[2], 0) * factor;
257         rect->fill_color[2] = RGB_TO_V_BT709(rect->fill_rgba[0], rect->fill_rgba[1], rect->fill_rgba[2], 0) * factor;
258         rect->fill_color[3] = rect->fill_rgba[3] * factor;
259     }
260      return 0;
261 }
262
263 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
264 {
265     AVFilterContext *ctx = inlink->dst;
266     AVFilterLink *outlink = ctx->outputs[0];
267     LenscorrectionCtx *rect = (LenscorrectionCtx*)ctx->priv;
268     AVFrame *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
269     int plane;
270
271     if (!out) {
272         av_frame_free(&in);
273         return AVERROR(ENOMEM);
274     }
275
276     av_frame_copy_props(out, in);
277
278     for (plane = 0; plane < rect->nb_planes; ++plane) {
279         int hsub = plane == 1 || plane == 2 ? rect->hsub : 0;
280         int vsub = plane == 1 || plane == 2 ? rect->vsub : 0;
281         int w = AV_CEIL_RSHIFT(rect->width, hsub);
282         int h = AV_CEIL_RSHIFT(rect->height, vsub);
283         int xcenter = rect->cx * w;
284         int ycenter = rect->cy * h;
285         int k1 = rect->k1 * (1<<24);
286         int k2 = rect->k2 * (1<<24);
287         ThreadData td = {
288             .in = in,
289             .out  = out,
290             .w  = w,
291             .h  = h,
292             .xcenter = xcenter,
293             .ycenter = ycenter,
294             .plane = plane,
295             .depth = rect->depth,
296             .fill_color = rect->fill_color[plane],
297         };
298
299         if (!rect->correction[plane]) {
300             int i,j;
301             const int64_t r2inv = (4LL<<60) / (w * w + h * h);
302
303             rect->correction[plane] = av_malloc_array(w, h * sizeof(**rect->correction));
304             if (!rect->correction[plane])
305                 return AVERROR(ENOMEM);
306             for (j = 0; j < h; j++) {
307                 const int off_y = j - ycenter;
308                 const int off_y2 = off_y * off_y;
309                 for (i = 0; i < w; i++) {
310                     const int off_x = i - xcenter;
311                     const int64_t r2 = ((off_x * off_x + off_y2) * r2inv + (1LL<<31)) >> 32;
312                     const int64_t r4 = (r2 * r2 + (1<<27)) >> 28;
313                     const int radius_mult = (r2 * k1 + r4 * k2 + (1LL<<27) + (1LL<<52))>>28;
314                     rect->correction[plane][j * w + i] = radius_mult;
315                 }
316             }
317         }
318
319         td.correction = rect->correction[plane];
320         ctx->internal->execute(ctx, rect->filter_slice, &td, NULL, FFMIN(h, ff_filter_get_nb_threads(ctx)));
321     }
322
323     av_frame_free(&in);
324     return ff_filter_frame(outlink, out);
325 }
326
327 static const AVFilterPad lenscorrection_inputs[] = {
328     {
329         .name         = "default",
330         .type         = AVMEDIA_TYPE_VIDEO,
331         .filter_frame = filter_frame,
332     },
333     { NULL }
334 };
335
336 static const AVFilterPad lenscorrection_outputs[] = {
337     {
338         .name         = "default",
339         .type         = AVMEDIA_TYPE_VIDEO,
340         .config_props = config_props,
341     },
342     { NULL }
343 };
344
345 AVFilter ff_vf_lenscorrection = {
346     .name          = "lenscorrection",
347     .description   = NULL_IF_CONFIG_SMALL("Rectify the image by correcting for lens distortion."),
348     .priv_size     = sizeof(LenscorrectionCtx),
349     .query_formats = query_formats,
350     .inputs        = lenscorrection_inputs,
351     .outputs       = lenscorrection_outputs,
352     .priv_class    = &lenscorrection_class,
353     .uninit        = uninit,
354     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SLICE_THREADS,
355 };