]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_noise.c
Merge commit '68f930d2188aba5b32624887dcbf688c23482834'
[ffmpeg] / libavfilter / vf_noise.c
1 /*
2  * Copyright (c) 2002 Michael Niedermayer <michaelni@gmx.at>
3  * Copyright (c) 2013 Paul B Mahol
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 General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 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
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * 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  * noise generator
25  */
26
27 #include "libavutil/opt.h"
28 #include "libavutil/imgutils.h"
29 #include "libavutil/parseutils.h"
30 #include "libavutil/pixdesc.h"
31 #include "avfilter.h"
32 #include "formats.h"
33 #include "internal.h"
34 #include "video.h"
35
36 #define MAX_NOISE 4096
37 #define MAX_SHIFT 1024
38 #define MAX_RES (MAX_NOISE-MAX_SHIFT)
39
40 #define NOISE_UNIFORM  1
41 #define NOISE_TEMPORAL 2
42 #define NOISE_QUALITY  4
43 #define NOISE_AVERAGED 8
44 #define NOISE_PATTERN  16
45
46 typedef struct {
47     int strength;
48     unsigned flags;
49     int shiftptr;
50     int seed;
51     int8_t *noise;
52     int8_t *prev_shift[MAX_RES][3];
53 } FilterParams;
54
55 typedef struct {
56     const AVClass *class;
57     int nb_planes;
58     int linesize[4];
59     int height[4];
60     FilterParams all;
61     FilterParams param[4];
62     int rand_shift[MAX_RES];
63     int rand_shift_init;
64 } NoiseContext;
65
66 #define OFFSET(x) offsetof(NoiseContext, x)
67 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
68
69 #define NOISE_PARAMS(name, x, param)                                                                                             \
70     {#name"_seed", "set component #"#x" noise seed", OFFSET(param.seed), AV_OPT_TYPE_INT, {.i64=-1}, -1, INT_MAX, FLAGS},        \
71     {#name"_strength", "set component #"#x" strength", OFFSET(param.strength), AV_OPT_TYPE_INT, {.i64=0}, 0, 100, FLAGS},        \
72     {#name"s",         "set component #"#x" strength", OFFSET(param.strength), AV_OPT_TYPE_INT, {.i64=0}, 0, 100, FLAGS},        \
73     {#name"_flags", "set component #"#x" flags", OFFSET(param.flags), AV_OPT_TYPE_FLAGS, {.i64=0}, 0, 31, FLAGS, #name"_flags"}, \
74     {#name"f", "set component #"#x" flags", OFFSET(param.flags), AV_OPT_TYPE_FLAGS, {.i64=0}, 0, 31, FLAGS, #name"_flags"},      \
75     {"a", "averaged noise", 0, AV_OPT_TYPE_CONST, {.i64=NOISE_AVERAGED}, 0, 0, FLAGS, #name"_flags"},                            \
76     {"p", "(semi)regular pattern", 0, AV_OPT_TYPE_CONST, {.i64=NOISE_PATTERN},  0, 0, FLAGS, #name"_flags"},                     \
77     {"q", "high quality",   0, AV_OPT_TYPE_CONST, {.i64=NOISE_QUALITY},  0, 0, FLAGS, #name"_flags"},                            \
78     {"t", "temporal noise", 0, AV_OPT_TYPE_CONST, {.i64=NOISE_TEMPORAL}, 0, 0, FLAGS, #name"_flags"},                            \
79     {"u", "uniform noise",  0, AV_OPT_TYPE_CONST, {.i64=NOISE_UNIFORM},  0, 0, FLAGS, #name"_flags"},
80
81 static const AVOption noise_options[] = {
82     NOISE_PARAMS(all, 0, all)
83     NOISE_PARAMS(c0,  0, param[0])
84     NOISE_PARAMS(c1,  1, param[1])
85     NOISE_PARAMS(c2,  2, param[2])
86     NOISE_PARAMS(c3,  3, param[3])
87     {NULL}
88 };
89
90 AVFILTER_DEFINE_CLASS(noise);
91
92 static const int8_t patt[4] = { -1, 0, 1, 0 };
93
94 #define RAND_N(range) ((int) ((double) range * rand() / (RAND_MAX + 1.0)))
95 static int init_noise(NoiseContext *n, int comp)
96 {
97     int8_t *noise = av_malloc(MAX_NOISE * sizeof(int8_t));
98     FilterParams *fp = &n->param[comp];
99     int strength = fp->strength;
100     int flags = fp->flags;
101     int i, j;
102
103     if (!noise)
104         return AVERROR(ENOMEM);
105
106     srand(fp->seed);
107
108     for (i = 0, j = 0; i < MAX_NOISE; i++, j++) {
109         if (flags & NOISE_UNIFORM) {
110             if (flags & NOISE_AVERAGED) {
111                 if (flags & NOISE_PATTERN) {
112                     noise[i] = (RAND_N(strength) - strength / 2) / 6
113                         + patt[j % 4] * strength * 0.25 / 3;
114                 } else {
115                     noise[i] = (RAND_N(strength) - strength / 2) / 3;
116                 }
117             } else {
118                 if (flags & NOISE_PATTERN) {
119                     noise[i] = (RAND_N(strength) - strength / 2) / 2
120                         + patt[j % 4] * strength * 0.25;
121                 } else {
122                     noise[i] = RAND_N(strength) - strength / 2;
123                 }
124             }
125         } else {
126             double x1, x2, w, y1;
127             do {
128                 x1 = 2.0 * rand() / (float)RAND_MAX - 1.0;
129                 x2 = 2.0 * rand() / (float)RAND_MAX - 1.0;
130                 w = x1 * x1 + x2 * x2;
131             } while (w >= 1.0);
132
133             w   = sqrt((-2.0 * log(w)) / w);
134             y1  = x1 * w;
135             y1 *= strength / sqrt(3.0);
136             if (flags & NOISE_PATTERN) {
137                 y1 /= 2;
138                 y1 += patt[j % 4] * strength * 0.35;
139             }
140             y1 = av_clipf(y1, -128, 127);
141             if (flags & NOISE_AVERAGED)
142                 y1 /= 3.0;
143             noise[i] = (int)y1;
144         }
145         if (RAND_N(6) == 0)
146             j--;
147     }
148
149     for (i = 0; i < MAX_RES; i++)
150         for (j = 0; j < 3; j++)
151             fp->prev_shift[i][j] = noise + (rand() & (MAX_SHIFT - 1));
152
153     if (!n->rand_shift_init) {
154         for (i = 0; i < MAX_RES; i++)
155             n->rand_shift[i] = rand() & (MAX_SHIFT - 1);
156         n->rand_shift_init = 1;
157     }
158
159     fp->noise = noise;
160     fp->shiftptr = 0;
161     return 0;
162 }
163
164 static av_cold int init(AVFilterContext *ctx, const char *args)
165 {
166     NoiseContext *n = ctx->priv;
167     int ret, i;
168
169     n->class = &noise_class;
170     av_opt_set_defaults(n);
171
172     if ((ret = av_set_options_string(n, args, "=", ":")) < 0)
173         return ret;
174
175     for (i = 0; i < 4; i++) {
176         if (n->all.seed >= 0)
177             n->param[i].seed = n->all.seed;
178         else
179             n->param[i].seed = 123457;
180         if (n->all.strength)
181             n->param[i].strength = n->all.strength;
182         if (n->all.flags)
183             n->param[i].flags = n->all.flags;
184     }
185
186     for (i = 0; i < 4; i++) {
187         if (n->param[i].strength && ((ret = init_noise(n, i)) < 0))
188             return ret;
189     }
190
191     return 0;
192 }
193
194 static int query_formats(AVFilterContext *ctx)
195 {
196     AVFilterFormats *formats = NULL;
197     int fmt;
198
199     for (fmt = 0; fmt < AV_PIX_FMT_NB; fmt++) {
200         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(fmt);
201         if (desc->flags & PIX_FMT_PLANAR && !((desc->comp[0].depth_minus1 + 1) & 7))
202             ff_add_format(&formats, fmt);
203     }
204
205     ff_set_common_formats(ctx, formats);
206     return 0;
207 }
208
209 static int config_input(AVFilterLink *inlink)
210 {
211     NoiseContext *n = inlink->dst->priv;
212     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
213     int i, ret;
214
215     for (i = 0; i < desc->nb_components; i++)
216         n->nb_planes = FFMAX(n->nb_planes, desc->comp[i].plane);
217     n->nb_planes++;
218
219     if ((ret = av_image_fill_linesizes(n->linesize, inlink->format, inlink->w)) < 0)
220         return ret;
221
222     n->height[1] = n->height[2] = inlink->h >> desc->log2_chroma_h;
223     n->height[0] = n->height[3] = inlink->h;
224
225     return 0;
226 }
227
228 static void line_noise(uint8_t *dst, const uint8_t *src, int8_t *noise,
229                        int len, int shift)
230 {
231     int i;
232
233     noise += shift;
234     for (i = 0; i < len; i++) {
235         int v = src[i] + noise[i];
236
237         dst[i] = av_clip_uint8(v);
238     }
239 }
240
241 static void line_noise_avg(uint8_t *dst, const uint8_t *src,
242                            int len, int8_t **shift)
243 {
244     int i;
245     int8_t *src2 = (int8_t*)src;
246
247     for (i = 0; i < len; i++) {
248         const int n = shift[0][i] + shift[1][i] + shift[2][i];
249         dst[i] = src2[i] + ((n * src2[i]) >> 7);
250     }
251 }
252
253 static void noise(uint8_t *dst, const uint8_t *src,
254                   int dst_linesize, int src_linesize,
255                   int width, int height, NoiseContext *n, int comp)
256 {
257     int8_t *noise = n->param[comp].noise;
258     int flags = n->param[comp].flags;
259     int shift, y;
260
261     if (!noise) {
262         if (dst != src) {
263             for (y = 0; y < height; y++) {
264                 memcpy(dst, src, width);
265                 dst += dst_linesize;
266                 src += src_linesize;
267             }
268         }
269
270         return;
271     }
272
273     for (y = 0; y < height; y++) {
274         if (flags & NOISE_TEMPORAL)
275             shift = rand() & (MAX_SHIFT - 1);
276         else
277             shift = n->rand_shift[y];
278
279         if (!(flags & NOISE_QUALITY))
280             shift &= ~7;
281
282         if (flags & NOISE_AVERAGED) {
283             line_noise_avg(dst, src, width, n->param[comp].prev_shift[y]);
284             n->param[comp].prev_shift[y][n->param[comp].shiftptr] = noise + shift;
285         } else {
286             line_noise(dst, src, noise, width, shift);
287         }
288         dst += dst_linesize;
289         src += src_linesize;
290     }
291
292     n->param[comp].shiftptr++;
293     if (n->param[comp].shiftptr == 3)
294         n->param[comp].shiftptr = 0;
295 }
296
297 static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
298 {
299     NoiseContext *n = inlink->dst->priv;
300     AVFilterLink *outlink = inlink->dst->outputs[0];
301     AVFilterBufferRef *out;
302     int ret, i;
303
304     if (inpicref->perms & AV_PERM_WRITE) {
305         out = inpicref;
306     } else {
307         out = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
308         if (!out) {
309             avfilter_unref_bufferp(&inpicref);
310             return AVERROR(ENOMEM);
311         }
312         avfilter_copy_buffer_ref_props(out, inpicref);
313     }
314
315     for (i = 0; i < n->nb_planes; i++)
316         noise(out->data[i], inpicref->data[i], out->linesize[i],
317               inpicref->linesize[i], n->linesize[i], n->height[i], n, i);
318
319     ret = ff_filter_frame(outlink, out);
320     if (inpicref != out)
321         avfilter_unref_buffer(inpicref);
322     return ret;
323 }
324
325 static av_cold void uninit(AVFilterContext *ctx)
326 {
327     NoiseContext *n = ctx->priv;
328     int i;
329
330     for (i = 0; i < 4; i++)
331         av_freep(&n->param[i].noise);
332     av_opt_free(n);
333 }
334
335 static const AVFilterPad noise_inputs[] = {
336     {
337         .name             = "default",
338         .type             = AVMEDIA_TYPE_VIDEO,
339         .get_video_buffer = ff_null_get_video_buffer,
340         .filter_frame     = filter_frame,
341         .config_props     = config_input,
342         .min_perms        = AV_PERM_READ,
343     },
344     { NULL }
345 };
346
347 static const AVFilterPad noise_outputs[] = {
348     {
349         .name          = "default",
350         .type          = AVMEDIA_TYPE_VIDEO,
351     },
352     { NULL }
353 };
354
355 AVFilter avfilter_vf_noise = {
356     .name          = "noise",
357     .description   = NULL_IF_CONFIG_SMALL("Add noise."),
358     .priv_size     = sizeof(NoiseContext),
359     .init          = init,
360     .uninit        = uninit,
361     .query_formats = query_formats,
362     .inputs        = noise_inputs,
363     .outputs       = noise_outputs,
364     .priv_class    = &noise_class,
365 };