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
27enum FilterMode {
28    FILTER_NONE = -1,
29    FILTER_TOUT,
30    FILTER_VREP,
31    FILTER_BRNG,
32    FILT_NUMB
33};
34
35typedef 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
54static 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
68AVFILTER_DEFINE_CLASS(signalstats);
69
70static 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
87static 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
94static int query_formats(AVFilterContext *ctx)
95{
96    // TODO: add more
97    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_NONE
100    };
101
102    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
103    return 0;
104}
105
106static int config_props(AVFilterLink *outlink)
107{
108    AVFilterContext *ctx = outlink->src;
109    SignalstatsContext *s = ctx->priv;
110    AVFilterLink *inlink = outlink->src->inputs[0];
111    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(outlink->format);
112    s->hsub = desc->log2_chroma_w;
113    s->vsub = desc->log2_chroma_h;
114
115    outlink->w = inlink->w;
116    outlink->h = inlink->h;
117
118    s->chromaw = FF_CEIL_RSHIFT(inlink->w, s->hsub);
119    s->chromah = FF_CEIL_RSHIFT(inlink->h, s->vsub);
120
121    s->fs = inlink->w * inlink->h;
122    s->cfs = s->chromaw * s->chromah;
123
124    if (s->filters & 1<<FILTER_VREP) {
125        s->vrep_line = av_malloc(inlink->h * sizeof(*s->vrep_line));
126        if (!s->vrep_line)
127            return AVERROR(ENOMEM);
128    }
129
130    return 0;
131}
132
133static void burn_frame(SignalstatsContext *s, AVFrame *f, int x, int y)
134{
135    const int chromax = x >> s->hsub;
136    const int chromay = y >> s->vsub;
137    f->data[0][y       * f->linesize[0] +       x] = s->yuv_color[0];
138    f->data[1][chromay * f->linesize[1] + chromax] = s->yuv_color[1];
139    f->data[2][chromay * f->linesize[2] + chromax] = s->yuv_color[2];
140}
141
142static int filter_brng(SignalstatsContext *s, const AVFrame *in, AVFrame *out, int y, int w, int h)
143{
144    int x, score = 0;
145    const int yc = y >> s->vsub;
146    const uint8_t *pluma    = &in->data[0][y  * in->linesize[0]];
147    const uint8_t *pchromau = &in->data[1][yc * in->linesize[1]];
148    const uint8_t *pchromav = &in->data[2][yc * in->linesize[2]];
149
150    for (x = 0; x < w; x++) {
151        const int xc = x >> s->hsub;
152        const int luma    = pluma[x];
153        const int chromau = pchromau[xc];
154        const int chromav = pchromav[xc];
155        const int filt = luma    < 16 || luma    > 235 ||
156                         chromau < 16 || chromau > 240 ||
157                         chromav < 16 || chromav > 240;
158        score += filt;
159        if (out && filt)
160            burn_frame(s, out, x, y);
161    }
162    return score;
163}
164
165static int filter_tout_outlier(uint8_t x, uint8_t y, uint8_t z)
166{
167    return ((abs(x - y) + abs (z - y)) / 2) - abs(z - x) > 4; // make 4 configurable?
168}
169
170static int filter_tout(SignalstatsContext *s, const AVFrame *in, AVFrame *out, int y, int w, int h)
171{
172    const uint8_t *p = in->data[0];
173    int lw = in->linesize[0];
174    int x, score = 0, filt;
175
176    if (y - 1 < 0 || y + 1 >= h)
177        return 0;
178
179    // detect two pixels above and below (to eliminate interlace artefacts)
180    // should check that video format is infact interlaced.
181
182#define FILTER(i, j) \
183filter_tout_outlier(p[(y-j) * lw + x + i], \
184                    p[    y * lw + x + i], \
185                    p[(y+j) * lw + x + i])
186
187#define FILTER3(j) (FILTER(-1, j) && FILTER(0, j) && FILTER(1, j))
188
189    if (y - 2 >= 0 && y + 2 < h) {
190        for (x = 1; x < w - 1; x++) {
191            filt = FILTER3(2) && FILTER3(1);
192            score += filt;
193            if (filt && out)
194                burn_frame(s, out, x, y);
195        }
196    } else {
197        for (x = 1; x < w - 1; x++) {
198            filt = FILTER3(1);
199            score += filt;
200            if (filt && out)
201                burn_frame(s, out, x, y);
202        }
203    }
204    return score;
205}
206
207#define VREP_START 4
208
209static void filter_init_vrep(SignalstatsContext *s, const AVFrame *p, int w, int h)
210{
211    int i, y;
212    int lw = p->linesize[0];
213
214    for (y = VREP_START; y < h; y++) {
215        int totdiff = 0;
216        int y2lw = (y - VREP_START) * lw;
217        int ylw = y * lw;
218
219        for (i = 0; i < w; i++)
220            totdiff += abs(p->data[0][y2lw + i] - p->data[0][ylw + i]);
221
222        /* this value should be definable */
223        s->vrep_line[y] = totdiff < w;
224    }
225}
226
227static int filter_vrep(SignalstatsContext *s, const AVFrame *in, AVFrame *out, int y, int w, int h)
228{
229    int x, score = 0;
230
231    if (y < VREP_START)
232        return 0;
233
234    for (x = 0; x < w; x++) {
235        if (s->vrep_line[y]) {
236            score++;
237            if (out)
238                burn_frame(s, out, x, y);
239        }
240    }
241    return score;
242}
243
244static const struct {
245    const char *name;
246    void (*init)(SignalstatsContext *s, const AVFrame *p, int w, int h);
247    int (*process)(SignalstatsContext *s, const AVFrame *in, AVFrame *out, int y, int w, int h);
248} filters_def[] = {
249    {"TOUT", NULL,              filter_tout},
250    {"VREP", filter_init_vrep,  filter_vrep},
251    {"BRNG", NULL,              filter_brng},
252    {NULL}
253};
254
255#define DEPTH 256
256
257static int filter_frame(AVFilterLink *link, AVFrame *in)
258{
259    SignalstatsContext *s = link->dst->priv;
260    AVFilterLink *outlink = link->dst->outputs[0];
261    AVFrame *out = in;
262    int i, j;
263    int  w = 0,  cw = 0, // in
264        pw = 0, cpw = 0; // prev
265    int yuv, yuvu, yuvv;
266    int fil;
267    char metabuf[128];
268    unsigned int histy[DEPTH] = {0},
269                 histu[DEPTH] = {0},
270                 histv[DEPTH] = {0},
271                 histhue[360] = {0},
272                 histsat[DEPTH] = {0}; // limited to 8 bit data.
273    int miny  = -1, minu  = -1, minv  = -1;
274    int maxy  = -1, maxu  = -1, maxv  = -1;
275    int lowy  = -1, lowu  = -1, lowv  = -1;
276    int highy = -1, highu = -1, highv = -1;
277    int minsat = -1, maxsat = -1, lowsat = -1, highsat = -1;
278    int lowp, highp, clowp, chighp;
279    int accy, accu, accv;
280    int accsat, acchue = 0;
281    int medhue, maxhue;
282    int toty = 0, totu = 0, totv = 0, totsat=0;
283    int tothue = 0;
284    int dify = 0, difu = 0, difv = 0;
285
286    int filtot[FILT_NUMB] = {0};
287    AVFrame *prev;
288
289    if (!s->frame_prev)
290        s->frame_prev = av_frame_clone(in);
291
292    prev = s->frame_prev;
293
294    if (s->outfilter != FILTER_NONE)
295        out = av_frame_clone(in);
296
297    for (fil = 0; fil < FILT_NUMB; fil ++)
298        if ((s->filters & 1<<fil) && filters_def[fil].init)
299            filters_def[fil].init(s, in, link->w, link->h);
300
301    // Calculate luma histogram and difference with previous frame or field.
302    for (j = 0; j < link->h; j++) {
303        for (i = 0; i < link->w; i++) {
304            yuv = in->data[0][w + i];
305            histy[yuv]++;
306            dify += abs(in->data[0][w + i] - prev->data[0][pw + i]);
307        }
308        w  += in->linesize[0];
309        pw += prev->linesize[0];
310    }
311
312    // Calculate chroma histogram and difference with previous frame or field.
313    for (j = 0; j < s->chromah; j++) {
314        for (i = 0; i < s->chromaw; i++) {
315            int sat, hue;
316
317            yuvu = in->data[1][cw+i];
318            yuvv = in->data[2][cw+i];
319            histu[yuvu]++;
320            difu += abs(in->data[1][cw+i] - prev->data[1][cpw+i]);
321            histv[yuvv]++;
322            difv += abs(in->data[2][cw+i] - prev->data[2][cpw+i]);
323
324            // int or round?
325            sat = hypot(yuvu - 128, yuvv - 128);
326            histsat[sat]++;
327            hue = floor((180 / M_PI) * atan2f(yuvu-128, yuvv-128) + 180);
328            histhue[hue]++;
329        }
330        cw  += in->linesize[1];
331        cpw += prev->linesize[1];
332    }
333
334    for (j = 0; j < link->h; j++) {
335        for (fil = 0; fil < FILT_NUMB; fil ++) {
336            if (s->filters & 1<<fil) {
337                AVFrame *dbg = out != in && s->outfilter == fil ? out : NULL;
338                filtot[fil] += filters_def[fil].process(s, in, dbg, j, link->w, link->h);
339            }
340        }
341    }
342
343    // find low / high based on histogram percentile
344    // these only need to be calculated once.
345
346    lowp   = lrint(s->fs  * 10 / 100.);
347    highp  = lrint(s->fs  * 90 / 100.);
348    clowp  = lrint(s->cfs * 10 / 100.);
349    chighp = lrint(s->cfs * 90 / 100.);
350
351    accy = accu = accv = accsat = 0;
352    for (fil = 0; fil < DEPTH; fil++) {
353        if (miny   < 0 && histy[fil])   miny = fil;
354        if (minu   < 0 && histu[fil])   minu = fil;
355        if (minv   < 0 && histv[fil])   minv = fil;
356        if (minsat < 0 && histsat[fil]) minsat = fil;
357
358        if (histy[fil])   maxy   = fil;
359        if (histu[fil])   maxu   = fil;
360        if (histv[fil])   maxv   = fil;
361        if (histsat[fil]) maxsat = fil;
362
363        toty   += histy[fil]   * fil;
364        totu   += histu[fil]   * fil;
365        totv   += histv[fil]   * fil;
366        totsat += histsat[fil] * fil;
367
368        accy   += histy[fil];
369        accu   += histu[fil];
370        accv   += histv[fil];
371        accsat += histsat[fil];
372
373        if (lowy   == -1 && accy   >=  lowp) lowy   = fil;
374        if (lowu   == -1 && accu   >= clowp) lowu   = fil;
375        if (lowv   == -1 && accv   >= clowp) lowv   = fil;
376        if (lowsat == -1 && accsat >= clowp) lowsat = fil;
377
378        if (highy   == -1 && accy   >=  highp) highy   = fil;
379        if (highu   == -1 && accu   >= chighp) highu   = fil;
380        if (highv   == -1 && accv   >= chighp) highv   = fil;
381        if (highsat == -1 && accsat >= chighp) highsat = fil;
382    }
383
384    maxhue = histhue[0];
385    medhue = -1;
386    for (fil = 0; fil < 360; fil++) {
387        tothue += histhue[fil] * fil;
388        acchue += histhue[fil];
389
390        if (medhue == -1 && acchue > s->cfs / 2)
391            medhue = fil;
392        if (histhue[fil] > maxhue) {
393            maxhue = histhue[fil];
394        }
395    }
396
397    av_frame_free(&s->frame_prev);
398    s->frame_prev = av_frame_clone(in);
399
400#define SET_META(key, fmt, val) do {                                \
401    snprintf(metabuf, sizeof(metabuf), fmt, val);                   \
402    av_dict_set(&out->metadata, "lavfi.signalstats." key, metabuf, 0);   \
403} while (0)
404
405    SET_META("YMIN",    "%d", miny);
406    SET_META("YLOW",    "%d", lowy);
407    SET_META("YAVG",    "%g", 1.0 * toty / s->fs);
408    SET_META("YHIGH",   "%d", highy);
409    SET_META("YMAX",    "%d", maxy);
410
411    SET_META("UMIN",    "%d", minu);
412    SET_META("ULOW",    "%d", lowu);
413    SET_META("UAVG",    "%g", 1.0 * totu / s->cfs);
414    SET_META("UHIGH",   "%d", highu);
415    SET_META("UMAX",    "%d", maxu);
416
417    SET_META("VMIN",    "%d", minv);
418    SET_META("VLOW",    "%d", lowv);
419    SET_META("VAVG",    "%g", 1.0 * totv / s->cfs);
420    SET_META("VHIGH",   "%d", highv);
421    SET_META("VMAX",    "%d", maxv);
422
423    SET_META("SATMIN",  "%d", minsat);
424    SET_META("SATLOW",  "%d", lowsat);
425    SET_META("SATAVG",  "%g", 1.0 * totsat / s->cfs);
426    SET_META("SATHIGH", "%d", highsat);
427    SET_META("SATMAX",  "%d", maxsat);
428
429    SET_META("HUEMED",  "%d", medhue);
430    SET_META("HUEAVG",  "%g", 1.0 * tothue / s->cfs);
431
432    SET_META("YDIF",    "%g", 1.0 * dify / s->fs);
433    SET_META("UDIF",    "%g", 1.0 * difu / s->cfs);
434    SET_META("VDIF",    "%g", 1.0 * difv / s->cfs);
435
436    for (fil = 0; fil < FILT_NUMB; fil ++) {
437        if (s->filters & 1<<fil) {
438            char metaname[128];
439            snprintf(metabuf,  sizeof(metabuf),  "%g", 1.0 * filtot[fil] / s->fs);
440            snprintf(metaname, sizeof(metaname), "lavfi.signalstats.%s", filters_def[fil].name);
441            av_dict_set(&out->metadata, metaname, metabuf, 0);
442        }
443    }
444
445    if (in != out)
446        av_frame_free(&in);
447    return ff_filter_frame(outlink, out);
448}
449
450static const AVFilterPad signalstats_inputs[] = {
451    {
452        .name           = "default",
453        .type           = AVMEDIA_TYPE_VIDEO,
454        .filter_frame   = filter_frame,
455    },
456    { NULL }
457};
458
459static const AVFilterPad signalstats_outputs[] = {
460    {
461        .name           = "default",
462        .config_props   = config_props,
463        .type           = AVMEDIA_TYPE_VIDEO,
464    },
465    { NULL }
466};
467
468AVFilter ff_vf_signalstats = {
469    .name          = "signalstats",
470    .description   = "Generate statistics from video analysis.",
471    .init          = init,
472    .uninit        = uninit,
473    .query_formats = query_formats,
474    .priv_size     = sizeof(SignalstatsContext),
475    .inputs        = signalstats_inputs,
476    .outputs       = signalstats_outputs,
477    .priv_class    = &signalstats_class,
478};
479