]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_signalstats.c
Merge commit '55f03d872640175a00bfa262da4652b7312b905f'
[ffmpeg] / libavfilter / vf_signalstats.c
1 /*
2  * Copyright (c) 2010 Mark Heath mjpeg0 @ silicontrip dot org
3  * Copyright (c) 2014 Clément Bœsch
4  * Copyright (c) 2014 Dave Rice @dericed
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include "libavutil/opt.h"
24 #include "libavutil/pixdesc.h"
25 #include "internal.h"
26
27 enum FilterMode {
28     FILTER_NONE = -1,
29     FILTER_TOUT,
30     FILTER_VREP,
31     FILTER_BRNG,
32     FILT_NUMB
33 };
34
35 typedef struct {
36     const AVClass *class;
37     int chromah;    // height of chroma plane
38     int chromaw;    // width of chroma plane
39     int hsub;       // horizontal subsampling
40     int vsub;       // vertical subsampling
41     int fs;         // pixel count per frame
42     int cfs;        // pixel count per frame of chroma planes
43     enum FilterMode outfilter;
44     int filters;
45     AVFrame *frame_prev;
46     char *vrep_line;
47     uint8_t rgba_color[4];
48     int yuv_color[3];
49 } SignalstatsContext;
50
51 #define OFFSET(x) offsetof(SignalstatsContext, x)
52 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
53
54 static const AVOption signalstats_options[] = {
55     {"stat", "set statistics filters", OFFSET(filters), AV_OPT_TYPE_FLAGS, {.i64=0}, 0, INT_MAX, FLAGS, "filters"},
56         {"tout", "analyze pixels for temporal outliers",                0, AV_OPT_TYPE_CONST, {.i64=1<<FILTER_TOUT}, 0, 0, FLAGS, "filters"},
57         {"vrep", "analyze video lines for vertical line repitition",    0, AV_OPT_TYPE_CONST, {.i64=1<<FILTER_VREP}, 0, 0, FLAGS, "filters"},
58         {"brng", "analyze for pixels outside of broadcast range",       0, AV_OPT_TYPE_CONST, {.i64=1<<FILTER_BRNG}, 0, 0, FLAGS, "filters"},
59     {"out", "set video filter", OFFSET(outfilter), AV_OPT_TYPE_INT, {.i64=FILTER_NONE}, -1, FILT_NUMB-1, FLAGS, "out"},
60         {"tout", "highlight pixels that depict temporal outliers",              0, AV_OPT_TYPE_CONST, {.i64=FILTER_TOUT}, 0, 0, FLAGS, "out"},
61         {"vrep", "highlight video lines that depict vertical line repitition",  0, AV_OPT_TYPE_CONST, {.i64=FILTER_VREP}, 0, 0, FLAGS, "out"},
62         {"brng", "highlight pixels that are outside of broadcast range",        0, AV_OPT_TYPE_CONST, {.i64=FILTER_BRNG}, 0, 0, FLAGS, "out"},
63     {"c",     "set highlight color", OFFSET(rgba_color), AV_OPT_TYPE_COLOR, {.str="yellow"}, .flags=FLAGS},
64     {"color", "set highlight color", OFFSET(rgba_color), AV_OPT_TYPE_COLOR, {.str="yellow"}, .flags=FLAGS},
65     {NULL}
66 };
67
68 AVFILTER_DEFINE_CLASS(signalstats);
69
70 static av_cold int init(AVFilterContext *ctx)
71 {
72     uint8_t r, g, b;
73     SignalstatsContext *s = ctx->priv;
74
75     if (s->outfilter != FILTER_NONE)
76         s->filters |= 1 << s->outfilter;
77
78     r = s->rgba_color[0];
79     g = s->rgba_color[1];
80     b = s->rgba_color[2];
81     s->yuv_color[0] = (( 66*r + 129*g +  25*b + (1<<7)) >> 8) +  16;
82     s->yuv_color[1] = ((-38*r + -74*g + 112*b + (1<<7)) >> 8) + 128;
83     s->yuv_color[2] = ((112*r + -94*g + -18*b + (1<<7)) >> 8) + 128;
84     return 0;
85 }
86
87 static av_cold void uninit(AVFilterContext *ctx)
88 {
89     SignalstatsContext *s = ctx->priv;
90     av_frame_free(&s->frame_prev);
91     av_freep(&s->vrep_line);
92 }
93
94 static int query_formats(AVFilterContext *ctx)
95 {
96     // TODO: add more
97     static const enum AVPixelFormat pix_fmts[] = {
98         AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV411P,
99         AV_PIX_FMT_YUV440P,
100         AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ411P,
101         AV_PIX_FMT_YUVJ440P,
102         AV_PIX_FMT_NONE
103     };
104
105     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
106     return 0;
107 }
108
109 static int config_props(AVFilterLink *outlink)
110 {
111     AVFilterContext *ctx = outlink->src;
112     SignalstatsContext *s = ctx->priv;
113     AVFilterLink *inlink = outlink->src->inputs[0];
114     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(outlink->format);
115     s->hsub = desc->log2_chroma_w;
116     s->vsub = desc->log2_chroma_h;
117
118     outlink->w = inlink->w;
119     outlink->h = inlink->h;
120
121     s->chromaw = FF_CEIL_RSHIFT(inlink->w, s->hsub);
122     s->chromah = FF_CEIL_RSHIFT(inlink->h, s->vsub);
123
124     s->fs = inlink->w * inlink->h;
125     s->cfs = s->chromaw * s->chromah;
126
127     if (s->filters & 1<<FILTER_VREP) {
128         s->vrep_line = av_malloc(inlink->h * sizeof(*s->vrep_line));
129         if (!s->vrep_line)
130             return AVERROR(ENOMEM);
131     }
132
133     return 0;
134 }
135
136 static void burn_frame(SignalstatsContext *s, AVFrame *f, int x, int y)
137 {
138     const int chromax = x >> s->hsub;
139     const int chromay = y >> s->vsub;
140     f->data[0][y       * f->linesize[0] +       x] = s->yuv_color[0];
141     f->data[1][chromay * f->linesize[1] + chromax] = s->yuv_color[1];
142     f->data[2][chromay * f->linesize[2] + chromax] = s->yuv_color[2];
143 }
144
145 static int filter_brng(SignalstatsContext *s, const AVFrame *in, AVFrame *out, int y, int w, int h)
146 {
147     int x, score = 0;
148     const int yc = y >> s->vsub;
149     const uint8_t *pluma    = &in->data[0][y  * in->linesize[0]];
150     const uint8_t *pchromau = &in->data[1][yc * in->linesize[1]];
151     const uint8_t *pchromav = &in->data[2][yc * in->linesize[2]];
152
153     for (x = 0; x < w; x++) {
154         const int xc = x >> s->hsub;
155         const int luma    = pluma[x];
156         const int chromau = pchromau[xc];
157         const int chromav = pchromav[xc];
158         const int filt = luma    < 16 || luma    > 235 ||
159                          chromau < 16 || chromau > 240 ||
160                          chromav < 16 || chromav > 240;
161         score += filt;
162         if (out && filt)
163             burn_frame(s, out, x, y);
164     }
165     return score;
166 }
167
168 static int filter_tout_outlier(uint8_t x, uint8_t y, uint8_t z)
169 {
170     return ((abs(x - y) + abs (z - y)) / 2) - abs(z - x) > 4; // make 4 configurable?
171 }
172
173 static int filter_tout(SignalstatsContext *s, const AVFrame *in, AVFrame *out, int y, int w, int h)
174 {
175     const uint8_t *p = in->data[0];
176     int lw = in->linesize[0];
177     int x, score = 0, filt;
178
179     if (y - 1 < 0 || y + 1 >= h)
180         return 0;
181
182     // detect two pixels above and below (to eliminate interlace artefacts)
183     // should check that video format is infact interlaced.
184
185 #define FILTER(i, j) \
186 filter_tout_outlier(p[(y-j) * lw + x + i], \
187                     p[    y * lw + x + i], \
188                     p[(y+j) * lw + x + i])
189
190 #define FILTER3(j) (FILTER(-1, j) && FILTER(0, j) && FILTER(1, j))
191
192     if (y - 2 >= 0 && y + 2 < h) {
193         for (x = 1; x < w - 1; x++) {
194             filt = FILTER3(2) && FILTER3(1);
195             score += filt;
196             if (filt && out)
197                 burn_frame(s, out, x, y);
198         }
199     } else {
200         for (x = 1; x < w - 1; x++) {
201             filt = FILTER3(1);
202             score += filt;
203             if (filt && out)
204                 burn_frame(s, out, x, y);
205         }
206     }
207     return score;
208 }
209
210 #define VREP_START 4
211
212 static void filter_init_vrep(SignalstatsContext *s, const AVFrame *p, int w, int h)
213 {
214     int i, y;
215     int lw = p->linesize[0];
216
217     for (y = VREP_START; y < h; y++) {
218         int totdiff = 0;
219         int y2lw = (y - VREP_START) * lw;
220         int ylw = y * lw;
221
222         for (i = 0; i < w; i++)
223             totdiff += abs(p->data[0][y2lw + i] - p->data[0][ylw + i]);
224
225         /* this value should be definable */
226         s->vrep_line[y] = totdiff < w;
227     }
228 }
229
230 static int filter_vrep(SignalstatsContext *s, const AVFrame *in, AVFrame *out, int y, int w, int h)
231 {
232     int x, score = 0;
233
234     if (y < VREP_START)
235         return 0;
236
237     for (x = 0; x < w; x++) {
238         if (s->vrep_line[y]) {
239             score++;
240             if (out)
241                 burn_frame(s, out, x, y);
242         }
243     }
244     return score;
245 }
246
247 static const struct {
248     const char *name;
249     void (*init)(SignalstatsContext *s, const AVFrame *p, int w, int h);
250     int (*process)(SignalstatsContext *s, const AVFrame *in, AVFrame *out, int y, int w, int h);
251 } filters_def[] = {
252     {"TOUT", NULL,              filter_tout},
253     {"VREP", filter_init_vrep,  filter_vrep},
254     {"BRNG", NULL,              filter_brng},
255     {NULL}
256 };
257
258 #define DEPTH 256
259
260 static int filter_frame(AVFilterLink *link, AVFrame *in)
261 {
262     SignalstatsContext *s = link->dst->priv;
263     AVFilterLink *outlink = link->dst->outputs[0];
264     AVFrame *out = in;
265     int i, j;
266     int  w = 0,  cw = 0, // in
267         pw = 0, cpw = 0; // prev
268     int yuv, yuvu, yuvv;
269     int fil;
270     char metabuf[128];
271     unsigned int histy[DEPTH] = {0},
272                  histu[DEPTH] = {0},
273                  histv[DEPTH] = {0},
274                  histhue[360] = {0},
275                  histsat[DEPTH] = {0}; // limited to 8 bit data.
276     int miny  = -1, minu  = -1, minv  = -1;
277     int maxy  = -1, maxu  = -1, maxv  = -1;
278     int lowy  = -1, lowu  = -1, lowv  = -1;
279     int highy = -1, highu = -1, highv = -1;
280     int minsat = -1, maxsat = -1, lowsat = -1, highsat = -1;
281     int lowp, highp, clowp, chighp;
282     int accy, accu, accv;
283     int accsat, acchue = 0;
284     int medhue, maxhue;
285     int toty = 0, totu = 0, totv = 0, totsat=0;
286     int tothue = 0;
287     int dify = 0, difu = 0, difv = 0;
288
289     int filtot[FILT_NUMB] = {0};
290     AVFrame *prev;
291
292     if (!s->frame_prev)
293         s->frame_prev = av_frame_clone(in);
294
295     prev = s->frame_prev;
296
297     if (s->outfilter != FILTER_NONE)
298         out = av_frame_clone(in);
299
300     for (fil = 0; fil < FILT_NUMB; fil ++)
301         if ((s->filters & 1<<fil) && filters_def[fil].init)
302             filters_def[fil].init(s, in, link->w, link->h);
303
304     // Calculate luma histogram and difference with previous frame or field.
305     for (j = 0; j < link->h; j++) {
306         for (i = 0; i < link->w; i++) {
307             yuv = in->data[0][w + i];
308             histy[yuv]++;
309             dify += abs(in->data[0][w + i] - prev->data[0][pw + i]);
310         }
311         w  += in->linesize[0];
312         pw += prev->linesize[0];
313     }
314
315     // Calculate chroma histogram and difference with previous frame or field.
316     for (j = 0; j < s->chromah; j++) {
317         for (i = 0; i < s->chromaw; i++) {
318             int sat, hue;
319
320             yuvu = in->data[1][cw+i];
321             yuvv = in->data[2][cw+i];
322             histu[yuvu]++;
323             difu += abs(in->data[1][cw+i] - prev->data[1][cpw+i]);
324             histv[yuvv]++;
325             difv += abs(in->data[2][cw+i] - prev->data[2][cpw+i]);
326
327             // int or round?
328             sat = hypot(yuvu - 128, yuvv - 128);
329             histsat[sat]++;
330             hue = floor((180 / M_PI) * atan2f(yuvu-128, yuvv-128) + 180);
331             histhue[hue]++;
332         }
333         cw  += in->linesize[1];
334         cpw += prev->linesize[1];
335     }
336
337     for (j = 0; j < link->h; j++) {
338         for (fil = 0; fil < FILT_NUMB; fil ++) {
339             if (s->filters & 1<<fil) {
340                 AVFrame *dbg = out != in && s->outfilter == fil ? out : NULL;
341                 filtot[fil] += filters_def[fil].process(s, in, dbg, j, link->w, link->h);
342             }
343         }
344     }
345
346     // find low / high based on histogram percentile
347     // these only need to be calculated once.
348
349     lowp   = lrint(s->fs  * 10 / 100.);
350     highp  = lrint(s->fs  * 90 / 100.);
351     clowp  = lrint(s->cfs * 10 / 100.);
352     chighp = lrint(s->cfs * 90 / 100.);
353
354     accy = accu = accv = accsat = 0;
355     for (fil = 0; fil < DEPTH; fil++) {
356         if (miny   < 0 && histy[fil])   miny = fil;
357         if (minu   < 0 && histu[fil])   minu = fil;
358         if (minv   < 0 && histv[fil])   minv = fil;
359         if (minsat < 0 && histsat[fil]) minsat = fil;
360
361         if (histy[fil])   maxy   = fil;
362         if (histu[fil])   maxu   = fil;
363         if (histv[fil])   maxv   = fil;
364         if (histsat[fil]) maxsat = fil;
365
366         toty   += histy[fil]   * fil;
367         totu   += histu[fil]   * fil;
368         totv   += histv[fil]   * fil;
369         totsat += histsat[fil] * fil;
370
371         accy   += histy[fil];
372         accu   += histu[fil];
373         accv   += histv[fil];
374         accsat += histsat[fil];
375
376         if (lowy   == -1 && accy   >=  lowp) lowy   = fil;
377         if (lowu   == -1 && accu   >= clowp) lowu   = fil;
378         if (lowv   == -1 && accv   >= clowp) lowv   = fil;
379         if (lowsat == -1 && accsat >= clowp) lowsat = fil;
380
381         if (highy   == -1 && accy   >=  highp) highy   = fil;
382         if (highu   == -1 && accu   >= chighp) highu   = fil;
383         if (highv   == -1 && accv   >= chighp) highv   = fil;
384         if (highsat == -1 && accsat >= chighp) highsat = fil;
385     }
386
387     maxhue = histhue[0];
388     medhue = -1;
389     for (fil = 0; fil < 360; fil++) {
390         tothue += histhue[fil] * fil;
391         acchue += histhue[fil];
392
393         if (medhue == -1 && acchue > s->cfs / 2)
394             medhue = fil;
395         if (histhue[fil] > maxhue) {
396             maxhue = histhue[fil];
397         }
398     }
399
400     av_frame_free(&s->frame_prev);
401     s->frame_prev = av_frame_clone(in);
402
403 #define SET_META(key, fmt, val) do {                                \
404     snprintf(metabuf, sizeof(metabuf), fmt, val);                   \
405     av_dict_set(&out->metadata, "lavfi.signalstats." key, metabuf, 0);   \
406 } while (0)
407
408     SET_META("YMIN",    "%d", miny);
409     SET_META("YLOW",    "%d", lowy);
410     SET_META("YAVG",    "%g", 1.0 * toty / s->fs);
411     SET_META("YHIGH",   "%d", highy);
412     SET_META("YMAX",    "%d", maxy);
413
414     SET_META("UMIN",    "%d", minu);
415     SET_META("ULOW",    "%d", lowu);
416     SET_META("UAVG",    "%g", 1.0 * totu / s->cfs);
417     SET_META("UHIGH",   "%d", highu);
418     SET_META("UMAX",    "%d", maxu);
419
420     SET_META("VMIN",    "%d", minv);
421     SET_META("VLOW",    "%d", lowv);
422     SET_META("VAVG",    "%g", 1.0 * totv / s->cfs);
423     SET_META("VHIGH",   "%d", highv);
424     SET_META("VMAX",    "%d", maxv);
425
426     SET_META("SATMIN",  "%d", minsat);
427     SET_META("SATLOW",  "%d", lowsat);
428     SET_META("SATAVG",  "%g", 1.0 * totsat / s->cfs);
429     SET_META("SATHIGH", "%d", highsat);
430     SET_META("SATMAX",  "%d", maxsat);
431
432     SET_META("HUEMED",  "%d", medhue);
433     SET_META("HUEAVG",  "%g", 1.0 * tothue / s->cfs);
434
435     SET_META("YDIF",    "%g", 1.0 * dify / s->fs);
436     SET_META("UDIF",    "%g", 1.0 * difu / s->cfs);
437     SET_META("VDIF",    "%g", 1.0 * difv / s->cfs);
438
439     for (fil = 0; fil < FILT_NUMB; fil ++) {
440         if (s->filters & 1<<fil) {
441             char metaname[128];
442             snprintf(metabuf,  sizeof(metabuf),  "%g", 1.0 * filtot[fil] / s->fs);
443             snprintf(metaname, sizeof(metaname), "lavfi.signalstats.%s", filters_def[fil].name);
444             av_dict_set(&out->metadata, metaname, metabuf, 0);
445         }
446     }
447
448     if (in != out)
449         av_frame_free(&in);
450     return ff_filter_frame(outlink, out);
451 }
452
453 static const AVFilterPad signalstats_inputs[] = {
454     {
455         .name           = "default",
456         .type           = AVMEDIA_TYPE_VIDEO,
457         .filter_frame   = filter_frame,
458     },
459     { NULL }
460 };
461
462 static const AVFilterPad signalstats_outputs[] = {
463     {
464         .name           = "default",
465         .config_props   = config_props,
466         .type           = AVMEDIA_TYPE_VIDEO,
467     },
468     { NULL }
469 };
470
471 AVFilter ff_vf_signalstats = {
472     .name          = "signalstats",
473     .description   = "Generate statistics from video analysis.",
474     .init          = init,
475     .uninit        = uninit,
476     .query_formats = query_formats,
477     .priv_size     = sizeof(SignalstatsContext),
478     .inputs        = signalstats_inputs,
479     .outputs       = signalstats_outputs,
480     .priv_class    = &signalstats_class,
481 };