]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_atadenoise.c
avfilter/vf_atadenoise: compensate for small overall brightness loss
[ffmpeg] / libavfilter / vf_atadenoise.c
1 /*
2  * Copyright (c) 2015 Paul B Mahol
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
21 /**
22  * @file
23  * Adaptive Temporal Averaging Denoiser,
24  * based on paper "Video Denoising Based on Adaptive Temporal Averaging" by
25  * David Bartovčak and Miroslav Vrankić
26  */
27
28 #include "libavutil/imgutils.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/pixdesc.h"
31 #include "avfilter.h"
32
33 #define FF_BUFQUEUE_SIZE 129
34 #include "bufferqueue.h"
35
36 #include "formats.h"
37 #include "internal.h"
38 #include "video.h"
39
40 #define SIZE FF_BUFQUEUE_SIZE
41
42 typedef struct ATADenoiseContext {
43     const AVClass *class;
44
45     float fthra[4], fthrb[4];
46     int thra[4], thrb[4];
47
48     int planes;
49     int nb_planes;
50     int planewidth[4];
51     int planeheight[4];
52
53     struct FFBufQueue q;
54     void *data[4][SIZE];
55     int linesize[4][SIZE];
56     int size, mid;
57     int available;
58
59     int (*filter_slice)(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs);
60     void (*filter_row)(const uint8_t *src, uint8_t *dst,
61                        const uint8_t *srcf[SIZE],
62                        int w, int mid, int size,
63                        int thra, int thrb);
64 } ATADenoiseContext;
65
66 #define OFFSET(x) offsetof(ATADenoiseContext, x)
67 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
68
69 static const AVOption atadenoise_options[] = {
70     { "0a", "set threshold A for 1st plane", OFFSET(fthra[0]), AV_OPT_TYPE_FLOAT, {.dbl=0.02}, 0, 0.3, FLAGS },
71     { "0b", "set threshold B for 1st plane", OFFSET(fthrb[0]), AV_OPT_TYPE_FLOAT, {.dbl=0.04}, 0, 5.0, FLAGS },
72     { "1a", "set threshold A for 2nd plane", OFFSET(fthra[1]), AV_OPT_TYPE_FLOAT, {.dbl=0.02}, 0, 0.3, FLAGS },
73     { "1b", "set threshold B for 2nd plane", OFFSET(fthrb[1]), AV_OPT_TYPE_FLOAT, {.dbl=0.04}, 0, 5.0, FLAGS },
74     { "2a", "set threshold A for 3rd plane", OFFSET(fthra[2]), AV_OPT_TYPE_FLOAT, {.dbl=0.02}, 0, 0.3, FLAGS },
75     { "2b", "set threshold B for 3rd plane", OFFSET(fthrb[2]), AV_OPT_TYPE_FLOAT, {.dbl=0.04}, 0, 5.0, FLAGS },
76     { "s",  "set how many frames to use",    OFFSET(size),     AV_OPT_TYPE_INT,   {.i64=9},   5, SIZE, FLAGS },
77     { "p",  "set what planes to filter",     OFFSET(planes),   AV_OPT_TYPE_FLAGS, {.i64=7},    0, 15,  FLAGS },
78     { NULL }
79 };
80
81 AVFILTER_DEFINE_CLASS(atadenoise);
82
83 static int query_formats(AVFilterContext *ctx)
84 {
85     static const enum AVPixelFormat pixel_fmts[] = {
86         AV_PIX_FMT_GRAY8,
87         AV_PIX_FMT_GRAY9,
88         AV_PIX_FMT_GRAY10,
89         AV_PIX_FMT_GRAY12,
90         AV_PIX_FMT_GRAY14,
91         AV_PIX_FMT_GRAY16,
92         AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
93         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
94         AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P,
95         AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P,
96         AV_PIX_FMT_YUVJ440P, AV_PIX_FMT_YUVJ444P,
97         AV_PIX_FMT_YUVJ411P,
98         AV_PIX_FMT_YUV420P9, AV_PIX_FMT_YUV422P9, AV_PIX_FMT_YUV444P9,
99         AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV444P10,
100         AV_PIX_FMT_YUV440P10,
101         AV_PIX_FMT_YUV444P12, AV_PIX_FMT_YUV422P12, AV_PIX_FMT_YUV420P12,
102         AV_PIX_FMT_YUV440P12,
103         AV_PIX_FMT_YUV444P14, AV_PIX_FMT_YUV422P14, AV_PIX_FMT_YUV420P14,
104         AV_PIX_FMT_YUV420P16, AV_PIX_FMT_YUV422P16, AV_PIX_FMT_YUV444P16,
105         AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRP9, AV_PIX_FMT_GBRP10,
106         AV_PIX_FMT_GBRP12, AV_PIX_FMT_GBRP14, AV_PIX_FMT_GBRP16,
107         AV_PIX_FMT_NONE
108     };
109     AVFilterFormats *formats = ff_make_format_list(pixel_fmts);
110     if (!formats)
111         return AVERROR(ENOMEM);
112     return ff_set_common_formats(ctx, formats);
113 }
114
115 static av_cold int init(AVFilterContext *ctx)
116 {
117     ATADenoiseContext *s = ctx->priv;
118
119     if (!(s->size & 1)) {
120         av_log(ctx, AV_LOG_WARNING, "size %d is invalid. Must be an odd value, setting it to %d.\n", s->size, s->size|1);
121         s->size |= 1;
122     }
123     s->mid = s->size / 2 + 1;
124
125     return 0;
126 }
127
128 typedef struct ThreadData {
129     AVFrame *in, *out;
130 } ThreadData;
131
132 #define FILTER_ROW(type, name)                                              \
133 static void filter_row##name(const uint8_t *ssrc, uint8_t *ddst,            \
134                              const uint8_t *ssrcf[SIZE],                    \
135                              int w, int mid, int size,                      \
136                              int thra, int thrb)                            \
137 {                                                                           \
138     const type *src = (const type *)ssrc;                                   \
139     const type **srcf = (const type **)ssrcf;                               \
140     type *dst = (type *)ddst;                                               \
141                                                                             \
142     for (int x = 0; x < w; x++) {                                           \
143        const int srcx = src[x];                                             \
144        unsigned lsumdiff = 0, rsumdiff = 0;                                 \
145        unsigned ldiff, rdiff;                                               \
146        unsigned sum = srcx;                                                 \
147        int l = 0, r = 0;                                                    \
148        int srcjx, srcix;                                                    \
149                                                                             \
150        for (int j = mid - 1, i = mid + 1; j >= 0 && i < size; j--, i++) {   \
151            srcjx = srcf[j][x];                                              \
152                                                                             \
153            ldiff = FFABS(srcx - srcjx);                                     \
154            lsumdiff += ldiff;                                               \
155            if (ldiff > thra ||                                              \
156                lsumdiff > thrb)                                             \
157                break;                                                       \
158            l++;                                                             \
159            sum += srcjx;                                                    \
160                                                                             \
161            srcix = srcf[i][x];                                              \
162                                                                             \
163            rdiff = FFABS(srcx - srcix);                                     \
164            rsumdiff += rdiff;                                               \
165            if (rdiff > thra ||                                              \
166                rsumdiff > thrb)                                             \
167                break;                                                       \
168            r++;                                                             \
169            sum += srcix;                                                    \
170        }                                                                    \
171                                                                             \
172        dst[x] = (sum + ((r + l + 1) >> 1)) / (r + l + 1);                   \
173    }                                                                        \
174 }
175
176 FILTER_ROW(uint8_t, 8)
177 FILTER_ROW(uint16_t, 16)
178
179 static int filter_slice(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
180 {
181     ATADenoiseContext *s = ctx->priv;
182     ThreadData *td = arg;
183     AVFrame *in = td->in;
184     AVFrame *out = td->out;
185     const int size = s->size;
186     const int mid = s->mid;
187     int p, y, i;
188
189     for (p = 0; p < s->nb_planes; p++) {
190         const int h = s->planeheight[p];
191         const int w = s->planewidth[p];
192         const int slice_start = (h * jobnr) / nb_jobs;
193         const int slice_end = (h * (jobnr+1)) / nb_jobs;
194         const uint8_t *src = in->data[p] + slice_start * in->linesize[p];
195         uint8_t *dst = out->data[p] + slice_start * out->linesize[p];
196         const int thra = s->thra[p];
197         const int thrb = s->thrb[p];
198         const uint8_t **data = (const uint8_t **)s->data[p];
199         const int *linesize = (const int *)s->linesize[p];
200         const uint8_t *srcf[SIZE];
201
202         if (!((1 << p) & s->planes)) {
203             av_image_copy_plane(dst, out->linesize[p], src, in->linesize[p],
204                                 w, slice_end - slice_start);
205             continue;
206         }
207
208         for (i = 0; i < size; i++)
209             srcf[i] = data[i] + slice_start * linesize[i];
210
211         for (y = slice_start; y < slice_end; y++) {
212             s->filter_row(src, dst, srcf, w, mid, size, thra, thrb);
213
214             dst += out->linesize[p];
215             src += in->linesize[p];
216
217             for (i = 0; i < size; i++)
218                 srcf[i] += linesize[i];
219         }
220     }
221
222     return 0;
223 }
224
225 static int config_input(AVFilterLink *inlink)
226 {
227     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
228     AVFilterContext *ctx = inlink->dst;
229     ATADenoiseContext *s = ctx->priv;
230     int depth;
231
232     s->nb_planes = desc->nb_components;
233
234     s->planeheight[1] = s->planeheight[2] = AV_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
235     s->planeheight[0] = s->planeheight[3] = inlink->h;
236     s->planewidth[1]  = s->planewidth[2]  = AV_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
237     s->planewidth[0]  = s->planewidth[3]  = inlink->w;
238
239     depth = desc->comp[0].depth;
240     s->filter_slice = filter_slice;
241     if (depth == 8)
242         s->filter_row = filter_row8;
243     else
244         s->filter_row = filter_row16;
245
246     s->thra[0] = s->fthra[0] * (1 << depth) - 1;
247     s->thra[1] = s->fthra[1] * (1 << depth) - 1;
248     s->thra[2] = s->fthra[2] * (1 << depth) - 1;
249     s->thrb[0] = s->fthrb[0] * (1 << depth) - 1;
250     s->thrb[1] = s->fthrb[1] * (1 << depth) - 1;
251     s->thrb[2] = s->fthrb[2] * (1 << depth) - 1;
252
253     return 0;
254 }
255
256 static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
257 {
258     AVFilterContext *ctx = inlink->dst;
259     AVFilterLink *outlink = ctx->outputs[0];
260     ATADenoiseContext *s = ctx->priv;
261     AVFrame *out, *in;
262     int i;
263
264     if (s->q.available != s->size) {
265         if (s->q.available < s->mid) {
266             for (i = 0; i < s->mid; i++) {
267                 out = av_frame_clone(buf);
268                 if (!out) {
269                     av_frame_free(&buf);
270                     return AVERROR(ENOMEM);
271                 }
272                 ff_bufqueue_add(ctx, &s->q, out);
273             }
274         }
275         if (s->q.available < s->size) {
276             ff_bufqueue_add(ctx, &s->q, buf);
277             s->available++;
278         }
279         return 0;
280     }
281
282     in = ff_bufqueue_peek(&s->q, s->mid);
283
284     if (!ctx->is_disabled) {
285         ThreadData td;
286
287         out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
288         if (!out) {
289             av_frame_free(&buf);
290             return AVERROR(ENOMEM);
291         }
292
293         for (i = 0; i < s->size; i++) {
294             AVFrame *frame = ff_bufqueue_peek(&s->q, i);
295
296             s->data[0][i] = frame->data[0];
297             s->data[1][i] = frame->data[1];
298             s->data[2][i] = frame->data[2];
299             s->linesize[0][i] = frame->linesize[0];
300             s->linesize[1][i] = frame->linesize[1];
301             s->linesize[2][i] = frame->linesize[2];
302         }
303
304         td.in = in; td.out = out;
305         ctx->internal->execute(ctx, s->filter_slice, &td, NULL,
306                                FFMIN3(s->planeheight[1],
307                                       s->planeheight[2],
308                                       ff_filter_get_nb_threads(ctx)));
309         av_frame_copy_props(out, in);
310     } else {
311         out = av_frame_clone(in);
312         if (!out) {
313             av_frame_free(&buf);
314             return AVERROR(ENOMEM);
315         }
316     }
317
318     in = ff_bufqueue_get(&s->q);
319     av_frame_free(&in);
320     ff_bufqueue_add(ctx, &s->q, buf);
321
322     return ff_filter_frame(outlink, out);
323 }
324
325 static int request_frame(AVFilterLink *outlink)
326 {
327     AVFilterContext *ctx = outlink->src;
328     ATADenoiseContext *s = ctx->priv;
329     int ret = 0;
330
331     ret = ff_request_frame(ctx->inputs[0]);
332
333     if (ret == AVERROR_EOF && !ctx->is_disabled && s->available) {
334         AVFrame *buf = av_frame_clone(ff_bufqueue_peek(&s->q, s->available));
335         if (!buf)
336             return AVERROR(ENOMEM);
337
338         ret = filter_frame(ctx->inputs[0], buf);
339         s->available--;
340     }
341
342     return ret;
343 }
344
345 static av_cold void uninit(AVFilterContext *ctx)
346 {
347     ATADenoiseContext *s = ctx->priv;
348
349     ff_bufqueue_discard_all(&s->q);
350 }
351
352 static const AVFilterPad inputs[] = {
353     {
354         .name         = "default",
355         .type         = AVMEDIA_TYPE_VIDEO,
356         .filter_frame = filter_frame,
357         .config_props = config_input,
358     },
359     { NULL }
360 };
361
362 static const AVFilterPad outputs[] = {
363     {
364         .name          = "default",
365         .type          = AVMEDIA_TYPE_VIDEO,
366         .request_frame = request_frame,
367     },
368     { NULL }
369 };
370
371 AVFilter ff_vf_atadenoise = {
372     .name          = "atadenoise",
373     .description   = NULL_IF_CONFIG_SMALL("Apply an Adaptive Temporal Averaging Denoiser."),
374     .priv_size     = sizeof(ATADenoiseContext),
375     .priv_class    = &atadenoise_class,
376     .init          = init,
377     .uninit        = uninit,
378     .query_formats = query_formats,
379     .inputs        = inputs,
380     .outputs       = outputs,
381     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL | AVFILTER_FLAG_SLICE_THREADS,
382 };