]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_noise.c
Merge remote-tracking branch 'qatar/master'
[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 & AV_PIX_FMT_FLAG_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 ret;
188
189     n->nb_planes = av_pix_fmt_count_planes(inlink->format);
190
191     if ((ret = av_image_fill_linesizes(n->linesize, inlink->format, inlink->w)) < 0)
192         return ret;
193
194     n->height[1] = n->height[2] = FF_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
195     n->height[0] = n->height[3] = inlink->h;
196
197     return 0;
198 }
199
200 static inline void line_noise_c(uint8_t *dst, const uint8_t *src, int8_t *noise,
201                        int len, int shift)
202 {
203     int i;
204
205     noise += shift;
206     for (i = 0; i < len; i++) {
207         int v = src[i] + noise[i];
208
209         dst[i] = av_clip_uint8(v);
210     }
211 }
212
213 #define ASMALIGN(ZEROBITS) ".p2align " #ZEROBITS "\n\t"
214
215 static void line_noise_mmx(uint8_t *dst, const uint8_t *src,
216                            int8_t *noise, int len, int shift)
217 {
218 #if HAVE_MMX_INLINE
219     x86_reg mmx_len= len&(~7);
220     noise+=shift;
221
222     __asm__ volatile(
223             "mov %3, %%"REG_a"               \n\t"
224             "pcmpeqb %%mm7, %%mm7            \n\t"
225             "psllw $15, %%mm7                \n\t"
226             "packsswb %%mm7, %%mm7           \n\t"
227             ASMALIGN(4)
228             "1:                              \n\t"
229             "movq (%0, %%"REG_a"), %%mm0     \n\t"
230             "movq (%1, %%"REG_a"), %%mm1     \n\t"
231             "pxor %%mm7, %%mm0               \n\t"
232             "paddsb %%mm1, %%mm0             \n\t"
233             "pxor %%mm7, %%mm0               \n\t"
234             "movq %%mm0, (%2, %%"REG_a")     \n\t"
235             "add $8, %%"REG_a"               \n\t"
236             " js 1b                          \n\t"
237             :: "r" (src+mmx_len), "r" (noise+mmx_len), "r" (dst+mmx_len), "g" (-mmx_len)
238             : "%"REG_a
239     );
240     if (mmx_len!=len)
241         line_noise_c(dst+mmx_len, src+mmx_len, noise+mmx_len, len-mmx_len, 0);
242 #endif
243 }
244
245 static void line_noise_mmxext(uint8_t *dst, const uint8_t *src,
246                               int8_t *noise, int len, int shift)
247 {
248 #if HAVE_MMXEXT_INLINE
249     x86_reg mmx_len= len&(~7);
250     noise+=shift;
251
252     __asm__ volatile(
253             "mov %3, %%"REG_a"                \n\t"
254             "pcmpeqb %%mm7, %%mm7             \n\t"
255             "psllw $15, %%mm7                 \n\t"
256             "packsswb %%mm7, %%mm7            \n\t"
257             ASMALIGN(4)
258             "1:                               \n\t"
259             "movq (%0, %%"REG_a"), %%mm0      \n\t"
260             "movq (%1, %%"REG_a"), %%mm1      \n\t"
261             "pxor %%mm7, %%mm0                \n\t"
262             "paddsb %%mm1, %%mm0              \n\t"
263             "pxor %%mm7, %%mm0                \n\t"
264             "movntq %%mm0, (%2, %%"REG_a")    \n\t"
265             "add $8, %%"REG_a"                \n\t"
266             " js 1b                           \n\t"
267             :: "r" (src+mmx_len), "r" (noise+mmx_len), "r" (dst+mmx_len), "g" (-mmx_len)
268             : "%"REG_a
269             );
270     if (mmx_len != len)
271         line_noise_c(dst+mmx_len, src+mmx_len, noise+mmx_len, len-mmx_len, 0);
272 #endif
273 }
274
275 static inline void line_noise_avg_c(uint8_t *dst, const uint8_t *src,
276                            int len, int8_t **shift)
277 {
278     int i;
279     int8_t *src2 = (int8_t*)src;
280
281     for (i = 0; i < len; i++) {
282         const int n = shift[0][i] + shift[1][i] + shift[2][i];
283         dst[i] = src2[i] + ((n * src2[i]) >> 7);
284     }
285 }
286
287 static inline void line_noise_avg_mmx(uint8_t *dst, const uint8_t *src,
288                                       int len, int8_t **shift)
289 {
290 #if HAVE_MMX_INLINE
291     x86_reg mmx_len= len&(~7);
292
293     __asm__ volatile(
294             "mov %5, %%"REG_a"              \n\t"
295             ASMALIGN(4)
296             "1:                             \n\t"
297             "movq (%1, %%"REG_a"), %%mm1    \n\t"
298             "movq (%0, %%"REG_a"), %%mm0    \n\t"
299             "paddb (%2, %%"REG_a"), %%mm1   \n\t"
300             "paddb (%3, %%"REG_a"), %%mm1   \n\t"
301             "movq %%mm0, %%mm2              \n\t"
302             "movq %%mm1, %%mm3              \n\t"
303             "punpcklbw %%mm0, %%mm0         \n\t"
304             "punpckhbw %%mm2, %%mm2         \n\t"
305             "punpcklbw %%mm1, %%mm1         \n\t"
306             "punpckhbw %%mm3, %%mm3         \n\t"
307             "pmulhw %%mm0, %%mm1            \n\t"
308             "pmulhw %%mm2, %%mm3            \n\t"
309             "paddw %%mm1, %%mm1             \n\t"
310             "paddw %%mm3, %%mm3             \n\t"
311             "paddw %%mm0, %%mm1             \n\t"
312             "paddw %%mm2, %%mm3             \n\t"
313             "psrlw $8, %%mm1                \n\t"
314             "psrlw $8, %%mm3                \n\t"
315             "packuswb %%mm3, %%mm1          \n\t"
316             "movq %%mm1, (%4, %%"REG_a")    \n\t"
317             "add $8, %%"REG_a"              \n\t"
318             " js 1b                         \n\t"
319             :: "r" (src+mmx_len), "r" (shift[0]+mmx_len), "r" (shift[1]+mmx_len), "r" (shift[2]+mmx_len),
320                "r" (dst+mmx_len), "g" (-mmx_len)
321             : "%"REG_a
322         );
323
324     if (mmx_len != len){
325         int8_t *shift2[3]={shift[0]+mmx_len, shift[1]+mmx_len, shift[2]+mmx_len};
326         line_noise_avg_c(dst+mmx_len, src+mmx_len, len-mmx_len, shift2);
327     }
328 #endif
329 }
330
331 static void noise(uint8_t *dst, const uint8_t *src,
332                   int dst_linesize, int src_linesize,
333                   int width, int height, NoiseContext *n, int comp)
334 {
335     int8_t *noise = n->param[comp].noise;
336     int flags = n->param[comp].flags;
337     AVLFG *lfg = &n->param[comp].lfg;
338     int shift, y;
339
340     if (!noise) {
341         if (dst != src) {
342             for (y = 0; y < height; y++) {
343                 memcpy(dst, src, width);
344                 dst += dst_linesize;
345                 src += src_linesize;
346             }
347         }
348
349         return;
350     }
351
352     for (y = 0; y < height; y++) {
353         if (flags & NOISE_TEMPORAL)
354             shift = av_lfg_get(lfg) & (MAX_SHIFT - 1);
355         else
356             shift = n->rand_shift[y];
357
358         if (flags & NOISE_AVERAGED) {
359             n->line_noise_avg(dst, src, width, n->param[comp].prev_shift[y]);
360             n->param[comp].prev_shift[y][n->param[comp].shiftptr] = noise + shift;
361         } else {
362             n->line_noise(dst, src, noise, width, shift);
363         }
364         dst += dst_linesize;
365         src += src_linesize;
366     }
367
368     n->param[comp].shiftptr++;
369     if (n->param[comp].shiftptr == 3)
370         n->param[comp].shiftptr = 0;
371 }
372
373 static int filter_frame(AVFilterLink *inlink, AVFrame *inpicref)
374 {
375     NoiseContext *n = inlink->dst->priv;
376     AVFilterLink *outlink = inlink->dst->outputs[0];
377     AVFrame *out;
378     int i;
379
380     if (av_frame_is_writable(inpicref)) {
381         out = inpicref;
382     } else {
383         out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
384         if (!out) {
385             av_frame_free(&inpicref);
386             return AVERROR(ENOMEM);
387         }
388         av_frame_copy_props(out, inpicref);
389     }
390
391     for (i = 0; i < n->nb_planes; i++)
392         noise(out->data[i], inpicref->data[i], out->linesize[i],
393               inpicref->linesize[i], n->linesize[i], n->height[i], n, i);
394     emms_c();
395
396     if (inpicref != out)
397         av_frame_free(&inpicref);
398     return ff_filter_frame(outlink, out);
399 }
400
401 static av_cold int init(AVFilterContext *ctx)
402 {
403     NoiseContext *n = ctx->priv;
404     int ret, i;
405     int cpu_flags = av_get_cpu_flags();
406
407     for (i = 0; i < 4; i++) {
408         if (n->all.seed >= 0)
409             n->param[i].seed = n->all.seed;
410         else
411             n->param[i].seed = 123457;
412         if (n->all.strength)
413             n->param[i].strength = n->all.strength;
414         if (n->all.flags)
415             n->param[i].flags = n->all.flags;
416     }
417
418     for (i = 0; i < 4; i++) {
419         if (n->param[i].strength && ((ret = init_noise(n, i)) < 0))
420             return ret;
421     }
422
423     if (HAVE_MMX_INLINE &&
424         cpu_flags & AV_CPU_FLAG_MMX) {
425         n->line_noise = line_noise_mmx;
426         n->line_noise_avg = line_noise_avg_mmx;
427     }
428     if (HAVE_MMXEXT_INLINE &&
429         cpu_flags & AV_CPU_FLAG_MMXEXT)
430         n->line_noise = line_noise_mmxext;
431
432     return 0;
433 }
434
435 static av_cold void uninit(AVFilterContext *ctx)
436 {
437     NoiseContext *n = ctx->priv;
438     int i;
439
440     for (i = 0; i < 4; i++)
441         av_freep(&n->param[i].noise);
442 }
443
444 static const AVFilterPad noise_inputs[] = {
445     {
446         .name             = "default",
447         .type             = AVMEDIA_TYPE_VIDEO,
448         .filter_frame     = filter_frame,
449         .config_props     = config_input,
450     },
451     { NULL }
452 };
453
454 static const AVFilterPad noise_outputs[] = {
455     {
456         .name          = "default",
457         .type          = AVMEDIA_TYPE_VIDEO,
458     },
459     { NULL }
460 };
461
462 AVFilter avfilter_vf_noise = {
463     .name          = "noise",
464     .description   = NULL_IF_CONFIG_SMALL("Add noise."),
465     .priv_size     = sizeof(NoiseContext),
466     .init          = init,
467     .uninit        = uninit,
468     .query_formats = query_formats,
469     .inputs        = noise_inputs,
470     .outputs       = noise_outputs,
471     .priv_class    = &noise_class,
472     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,
473 };