]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_noise.c
Merge commit 'e926b5ceb1962833f0c884a328382bc2eca67aff'
[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/lfg.h"
30 #include "libavutil/parseutils.h"
31 #include "libavutil/pixdesc.h"
32 #include "libavutil/x86/asm.h"
33 #include "avfilter.h"
34 #include "formats.h"
35 #include "internal.h"
36 #include "video.h"
37
38 #define MAX_NOISE 4096
39 #define MAX_SHIFT 1024
40 #define MAX_RES (MAX_NOISE-MAX_SHIFT)
41
42 #define NOISE_UNIFORM  1
43 #define NOISE_TEMPORAL 2
44 #define NOISE_AVERAGED 8
45 #define NOISE_PATTERN  16
46
47 typedef struct {
48     int strength;
49     unsigned flags;
50     int shiftptr;
51     AVLFG lfg;
52     int seed;
53     int8_t *noise;
54     int8_t *prev_shift[MAX_RES][3];
55 } FilterParams;
56
57 typedef struct {
58     const AVClass *class;
59     int nb_planes;
60     int linesize[4];
61     int height[4];
62     FilterParams all;
63     FilterParams param[4];
64     int rand_shift[MAX_RES];
65     int rand_shift_init;
66     void (*line_noise)(uint8_t *dst, const uint8_t *src, int8_t *noise, int len, int shift);
67     void (*line_noise_avg)(uint8_t *dst, const uint8_t *src, int len, int8_t **shift);
68 } NoiseContext;
69
70 #define OFFSET(x) offsetof(NoiseContext, x)
71 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
72
73 #define NOISE_PARAMS(name, x, param)                                                                                             \
74     {#name"_seed", "set component #"#x" noise seed", OFFSET(param.seed), AV_OPT_TYPE_INT, {.i64=-1}, -1, INT_MAX, FLAGS},        \
75     {#name"_strength", "set component #"#x" strength", OFFSET(param.strength), AV_OPT_TYPE_INT, {.i64=0}, 0, 100, FLAGS},        \
76     {#name"s",         "set component #"#x" strength", OFFSET(param.strength), AV_OPT_TYPE_INT, {.i64=0}, 0, 100, FLAGS},        \
77     {#name"_flags", "set component #"#x" flags", OFFSET(param.flags), AV_OPT_TYPE_FLAGS, {.i64=0}, 0, 31, FLAGS, #name"_flags"}, \
78     {#name"f", "set component #"#x" flags", OFFSET(param.flags), AV_OPT_TYPE_FLAGS, {.i64=0}, 0, 31, FLAGS, #name"_flags"},      \
79     {"a", "averaged noise", 0, AV_OPT_TYPE_CONST, {.i64=NOISE_AVERAGED}, 0, 0, FLAGS, #name"_flags"},                            \
80     {"p", "(semi)regular pattern", 0, AV_OPT_TYPE_CONST, {.i64=NOISE_PATTERN},  0, 0, FLAGS, #name"_flags"},                     \
81     {"t", "temporal noise", 0, AV_OPT_TYPE_CONST, {.i64=NOISE_TEMPORAL}, 0, 0, FLAGS, #name"_flags"},                            \
82     {"u", "uniform noise",  0, AV_OPT_TYPE_CONST, {.i64=NOISE_UNIFORM},  0, 0, FLAGS, #name"_flags"},
83
84 static const AVOption noise_options[] = {
85     NOISE_PARAMS(all, 0, all)
86     NOISE_PARAMS(c0,  0, param[0])
87     NOISE_PARAMS(c1,  1, param[1])
88     NOISE_PARAMS(c2,  2, param[2])
89     NOISE_PARAMS(c3,  3, param[3])
90     {NULL}
91 };
92
93 AVFILTER_DEFINE_CLASS(noise);
94
95 static const int8_t patt[4] = { -1, 0, 1, 0 };
96
97 #define RAND_N(range) ((int) ((double) range * av_lfg_get(lfg) / (UINT_MAX + 1.0)))
98 static int init_noise(NoiseContext *n, int comp)
99 {
100     int8_t *noise = av_malloc(MAX_NOISE * sizeof(int8_t));
101     FilterParams *fp = &n->param[comp];
102     AVLFG *lfg = &n->param[comp].lfg;
103     int strength = fp->strength;
104     int flags = fp->flags;
105     int i, j;
106
107     if (!noise)
108         return AVERROR(ENOMEM);
109
110     av_lfg_init(&fp->lfg, fp->seed);
111
112     for (i = 0, j = 0; i < MAX_NOISE; i++, j++) {
113         if (flags & NOISE_UNIFORM) {
114             if (flags & NOISE_AVERAGED) {
115                 if (flags & NOISE_PATTERN) {
116                     noise[i] = (RAND_N(strength) - strength / 2) / 6
117                         + patt[j % 4] * strength * 0.25 / 3;
118                 } else {
119                     noise[i] = (RAND_N(strength) - strength / 2) / 3;
120                 }
121             } else {
122                 if (flags & NOISE_PATTERN) {
123                     noise[i] = (RAND_N(strength) - strength / 2) / 2
124                         + patt[j % 4] * strength * 0.25;
125                 } else {
126                     noise[i] = RAND_N(strength) - strength / 2;
127                 }
128             }
129         } else {
130             double x1, x2, w, y1;
131             do {
132                 x1 = 2.0 * av_lfg_get(lfg) / (float)UINT_MAX - 1.0;
133                 x2 = 2.0 * av_lfg_get(lfg) / (float)UINT_MAX - 1.0;
134                 w = x1 * x1 + x2 * x2;
135             } while (w >= 1.0);
136
137             w   = sqrt((-2.0 * log(w)) / w);
138             y1  = x1 * w;
139             y1 *= strength / sqrt(3.0);
140             if (flags & NOISE_PATTERN) {
141                 y1 /= 2;
142                 y1 += patt[j % 4] * strength * 0.35;
143             }
144             y1 = av_clipf(y1, -128, 127);
145             if (flags & NOISE_AVERAGED)
146                 y1 /= 3.0;
147             noise[i] = (int)y1;
148         }
149         if (RAND_N(6) == 0)
150             j--;
151     }
152
153     for (i = 0; i < MAX_RES; i++)
154         for (j = 0; j < 3; j++)
155             fp->prev_shift[i][j] = noise + (av_lfg_get(lfg) & (MAX_SHIFT - 1));
156
157     if (!n->rand_shift_init) {
158         for (i = 0; i < MAX_RES; i++)
159             n->rand_shift[i] = av_lfg_get(lfg) & (MAX_SHIFT - 1);
160         n->rand_shift_init = 1;
161     }
162
163     fp->noise = noise;
164     fp->shiftptr = 0;
165     return 0;
166 }
167
168 static int query_formats(AVFilterContext *ctx)
169 {
170     AVFilterFormats *formats = NULL;
171     int fmt;
172
173     for (fmt = 0; fmt < AV_PIX_FMT_NB; fmt++) {
174         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(fmt);
175         if (desc->flags & PIX_FMT_PLANAR && !((desc->comp[0].depth_minus1 + 1) & 7))
176             ff_add_format(&formats, fmt);
177     }
178
179     ff_set_common_formats(ctx, formats);
180     return 0;
181 }
182
183 static int config_input(AVFilterLink *inlink)
184 {
185     NoiseContext *n = inlink->dst->priv;
186     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
187     int i, ret;
188
189     for (i = 0; i < desc->nb_components; i++)
190         n->nb_planes = FFMAX(n->nb_planes, desc->comp[i].plane);
191     n->nb_planes++;
192
193     if ((ret = av_image_fill_linesizes(n->linesize, inlink->format, inlink->w)) < 0)
194         return ret;
195
196     n->height[1] = n->height[2] = inlink->h >> desc->log2_chroma_h;
197     n->height[0] = n->height[3] = inlink->h;
198
199     return 0;
200 }
201
202 static inline void line_noise_c(uint8_t *dst, const uint8_t *src, int8_t *noise,
203                        int len, int shift)
204 {
205     int i;
206
207     noise += shift;
208     for (i = 0; i < len; i++) {
209         int v = src[i] + noise[i];
210
211         dst[i] = av_clip_uint8(v);
212     }
213 }
214
215 #define ASMALIGN(ZEROBITS) ".p2align " #ZEROBITS "\n\t"
216
217 static void line_noise_mmx(uint8_t *dst, const uint8_t *src,
218                            int8_t *noise, int len, int shift)
219 {
220 #if HAVE_MMX_INLINE
221     x86_reg mmx_len= len&(~7);
222     noise+=shift;
223
224     __asm__ volatile(
225             "mov %3, %%"REG_a"               \n\t"
226             "pcmpeqb %%mm7, %%mm7            \n\t"
227             "psllw $15, %%mm7                \n\t"
228             "packsswb %%mm7, %%mm7           \n\t"
229             ASMALIGN(4)
230             "1:                              \n\t"
231             "movq (%0, %%"REG_a"), %%mm0     \n\t"
232             "movq (%1, %%"REG_a"), %%mm1     \n\t"
233             "pxor %%mm7, %%mm0               \n\t"
234             "paddsb %%mm1, %%mm0             \n\t"
235             "pxor %%mm7, %%mm0               \n\t"
236             "movq %%mm0, (%2, %%"REG_a")     \n\t"
237             "add $8, %%"REG_a"               \n\t"
238             " js 1b                          \n\t"
239             :: "r" (src+mmx_len), "r" (noise+mmx_len), "r" (dst+mmx_len), "g" (-mmx_len)
240             : "%"REG_a
241     );
242     if (mmx_len!=len)
243         line_noise_c(dst+mmx_len, src+mmx_len, noise+mmx_len, len-mmx_len, 0);
244 #endif
245 }
246
247 static void line_noise_mmxext(uint8_t *dst, const uint8_t *src,
248                               int8_t *noise, int len, int shift)
249 {
250 #if HAVE_MMXEXT_INLINE
251     x86_reg mmx_len= len&(~7);
252     noise+=shift;
253
254     __asm__ volatile(
255             "mov %3, %%"REG_a"                \n\t"
256             "pcmpeqb %%mm7, %%mm7             \n\t"
257             "psllw $15, %%mm7                 \n\t"
258             "packsswb %%mm7, %%mm7            \n\t"
259             ASMALIGN(4)
260             "1:                               \n\t"
261             "movq (%0, %%"REG_a"), %%mm0      \n\t"
262             "movq (%1, %%"REG_a"), %%mm1      \n\t"
263             "pxor %%mm7, %%mm0                \n\t"
264             "paddsb %%mm1, %%mm0              \n\t"
265             "pxor %%mm7, %%mm0                \n\t"
266             "movntq %%mm0, (%2, %%"REG_a")    \n\t"
267             "add $8, %%"REG_a"                \n\t"
268             " js 1b                           \n\t"
269             :: "r" (src+mmx_len), "r" (noise+mmx_len), "r" (dst+mmx_len), "g" (-mmx_len)
270             : "%"REG_a
271             );
272     if (mmx_len != len)
273         line_noise_c(dst+mmx_len, src+mmx_len, noise+mmx_len, len-mmx_len, 0);
274 #endif
275 }
276
277 static inline void line_noise_avg_c(uint8_t *dst, const uint8_t *src,
278                            int len, int8_t **shift)
279 {
280     int i;
281     int8_t *src2 = (int8_t*)src;
282
283     for (i = 0; i < len; i++) {
284         const int n = shift[0][i] + shift[1][i] + shift[2][i];
285         dst[i] = src2[i] + ((n * src2[i]) >> 7);
286     }
287 }
288
289 static inline void line_noise_avg_mmx(uint8_t *dst, const uint8_t *src,
290                                       int len, int8_t **shift)
291 {
292 #if HAVE_MMX_INLINE
293     x86_reg mmx_len= len&(~7);
294
295     __asm__ volatile(
296             "mov %5, %%"REG_a"              \n\t"
297             ASMALIGN(4)
298             "1:                             \n\t"
299             "movq (%1, %%"REG_a"), %%mm1    \n\t"
300             "movq (%0, %%"REG_a"), %%mm0    \n\t"
301             "paddb (%2, %%"REG_a"), %%mm1   \n\t"
302             "paddb (%3, %%"REG_a"), %%mm1   \n\t"
303             "movq %%mm0, %%mm2              \n\t"
304             "movq %%mm1, %%mm3              \n\t"
305             "punpcklbw %%mm0, %%mm0         \n\t"
306             "punpckhbw %%mm2, %%mm2         \n\t"
307             "punpcklbw %%mm1, %%mm1         \n\t"
308             "punpckhbw %%mm3, %%mm3         \n\t"
309             "pmulhw %%mm0, %%mm1            \n\t"
310             "pmulhw %%mm2, %%mm3            \n\t"
311             "paddw %%mm1, %%mm1             \n\t"
312             "paddw %%mm3, %%mm3             \n\t"
313             "paddw %%mm0, %%mm1             \n\t"
314             "paddw %%mm2, %%mm3             \n\t"
315             "psrlw $8, %%mm1                \n\t"
316             "psrlw $8, %%mm3                \n\t"
317             "packuswb %%mm3, %%mm1          \n\t"
318             "movq %%mm1, (%4, %%"REG_a")    \n\t"
319             "add $8, %%"REG_a"              \n\t"
320             " js 1b                         \n\t"
321             :: "r" (src+mmx_len), "r" (shift[0]+mmx_len), "r" (shift[1]+mmx_len), "r" (shift[2]+mmx_len),
322                "r" (dst+mmx_len), "g" (-mmx_len)
323             : "%"REG_a
324         );
325
326     if (mmx_len != len){
327         int8_t *shift2[3]={shift[0]+mmx_len, shift[1]+mmx_len, shift[2]+mmx_len};
328         line_noise_avg_c(dst+mmx_len, src+mmx_len, len-mmx_len, shift2);
329     }
330 #endif
331 }
332
333 static void noise(uint8_t *dst, const uint8_t *src,
334                   int dst_linesize, int src_linesize,
335                   int width, int height, NoiseContext *n, int comp)
336 {
337     int8_t *noise = n->param[comp].noise;
338     int flags = n->param[comp].flags;
339     AVLFG *lfg = &n->param[comp].lfg;
340     int shift, y;
341
342     if (!noise) {
343         if (dst != src) {
344             for (y = 0; y < height; y++) {
345                 memcpy(dst, src, width);
346                 dst += dst_linesize;
347                 src += src_linesize;
348             }
349         }
350
351         return;
352     }
353
354     for (y = 0; y < height; y++) {
355         if (flags & NOISE_TEMPORAL)
356             shift = av_lfg_get(lfg) & (MAX_SHIFT - 1);
357         else
358             shift = n->rand_shift[y];
359
360         if (flags & NOISE_AVERAGED) {
361             n->line_noise_avg(dst, src, width, n->param[comp].prev_shift[y]);
362             n->param[comp].prev_shift[y][n->param[comp].shiftptr] = noise + shift;
363         } else {
364             n->line_noise(dst, src, noise, width, shift);
365         }
366         dst += dst_linesize;
367         src += src_linesize;
368     }
369
370     n->param[comp].shiftptr++;
371     if (n->param[comp].shiftptr == 3)
372         n->param[comp].shiftptr = 0;
373 }
374
375 static int filter_frame(AVFilterLink *inlink, AVFrame *inpicref)
376 {
377     NoiseContext *n = inlink->dst->priv;
378     AVFilterLink *outlink = inlink->dst->outputs[0];
379     AVFrame *out;
380     int i;
381
382     if (av_frame_is_writable(inpicref)) {
383         out = inpicref;
384     } else {
385         out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
386         if (!out) {
387             av_frame_free(&inpicref);
388             return AVERROR(ENOMEM);
389         }
390         av_frame_copy_props(out, inpicref);
391     }
392
393     for (i = 0; i < n->nb_planes; i++)
394         noise(out->data[i], inpicref->data[i], out->linesize[i],
395               inpicref->linesize[i], n->linesize[i], n->height[i], n, i);
396     emms_c();
397
398     if (inpicref != out)
399         av_frame_free(&inpicref);
400     return ff_filter_frame(outlink, out);
401 }
402
403 static av_cold int init(AVFilterContext *ctx)
404 {
405     NoiseContext *n = ctx->priv;
406     int ret, i;
407     int cpu_flags = av_get_cpu_flags();
408
409     for (i = 0; i < 4; i++) {
410         if (n->all.seed >= 0)
411             n->param[i].seed = n->all.seed;
412         else
413             n->param[i].seed = 123457;
414         if (n->all.strength)
415             n->param[i].strength = n->all.strength;
416         if (n->all.flags)
417             n->param[i].flags = n->all.flags;
418     }
419
420     for (i = 0; i < 4; i++) {
421         if (n->param[i].strength && ((ret = init_noise(n, i)) < 0))
422             return ret;
423     }
424
425     if (HAVE_MMX_INLINE &&
426         cpu_flags & AV_CPU_FLAG_MMX) {
427         n->line_noise = line_noise_mmx;
428         n->line_noise_avg = line_noise_avg_mmx;
429     }
430     if (HAVE_MMXEXT_INLINE &&
431         cpu_flags & AV_CPU_FLAG_MMXEXT)
432         n->line_noise = line_noise_mmxext;
433
434     return 0;
435 }
436
437 static av_cold void uninit(AVFilterContext *ctx)
438 {
439     NoiseContext *n = ctx->priv;
440     int i;
441
442     for (i = 0; i < 4; i++)
443         av_freep(&n->param[i].noise);
444 }
445
446 static const AVFilterPad noise_inputs[] = {
447     {
448         .name             = "default",
449         .type             = AVMEDIA_TYPE_VIDEO,
450         .filter_frame     = filter_frame,
451         .config_props     = config_input,
452     },
453     { NULL }
454 };
455
456 static const AVFilterPad noise_outputs[] = {
457     {
458         .name          = "default",
459         .type          = AVMEDIA_TYPE_VIDEO,
460     },
461     { NULL }
462 };
463
464 AVFilter avfilter_vf_noise = {
465     .name          = "noise",
466     .description   = NULL_IF_CONFIG_SMALL("Add noise."),
467     .priv_size     = sizeof(NoiseContext),
468     .init          = init,
469     .uninit        = uninit,
470     .query_formats = query_formats,
471     .inputs        = noise_inputs,
472     .outputs       = noise_outputs,
473     .priv_class    = &noise_class,
474     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE,
475 };