FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
vf_signalstats.c
Go to the documentation of this file.
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 {
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
44  int filters;
46  uint8_t rgba_color[4];
47  int yuv_color[3];
48  int nb_jobs;
49  int *jobs_rets;
50 
54 
55 typedef struct ThreadData {
56  const AVFrame *in;
57  AVFrame *out;
58 } ThreadData;
59 
60 typedef struct ThreadDataHueSatMetrics {
61  const AVFrame *src;
64 
65 #define OFFSET(x) offsetof(SignalstatsContext, x)
66 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
67 
68 static const AVOption signalstats_options[] = {
69  {"stat", "set statistics filters", OFFSET(filters), AV_OPT_TYPE_FLAGS, {.i64=0}, 0, INT_MAX, FLAGS, "filters"},
70  {"tout", "analyze pixels for temporal outliers", 0, AV_OPT_TYPE_CONST, {.i64=1<<FILTER_TOUT}, 0, 0, FLAGS, "filters"},
71  {"vrep", "analyze video lines for vertical line repetition", 0, AV_OPT_TYPE_CONST, {.i64=1<<FILTER_VREP}, 0, 0, FLAGS, "filters"},
72  {"brng", "analyze for pixels outside of broadcast range", 0, AV_OPT_TYPE_CONST, {.i64=1<<FILTER_BRNG}, 0, 0, FLAGS, "filters"},
73  {"out", "set video filter", OFFSET(outfilter), AV_OPT_TYPE_INT, {.i64=FILTER_NONE}, -1, FILT_NUMB-1, FLAGS, "out"},
74  {"tout", "highlight pixels that depict temporal outliers", 0, AV_OPT_TYPE_CONST, {.i64=FILTER_TOUT}, 0, 0, FLAGS, "out"},
75  {"vrep", "highlight video lines that depict vertical line repetition", 0, AV_OPT_TYPE_CONST, {.i64=FILTER_VREP}, 0, 0, FLAGS, "out"},
76  {"brng", "highlight pixels that are outside of broadcast range", 0, AV_OPT_TYPE_CONST, {.i64=FILTER_BRNG}, 0, 0, FLAGS, "out"},
77  {"c", "set highlight color", OFFSET(rgba_color), AV_OPT_TYPE_COLOR, {.str="yellow"}, .flags=FLAGS},
78  {"color", "set highlight color", OFFSET(rgba_color), AV_OPT_TYPE_COLOR, {.str="yellow"}, .flags=FLAGS},
79  {NULL}
80 };
81 
82 AVFILTER_DEFINE_CLASS(signalstats);
83 
84 static av_cold int init(AVFilterContext *ctx)
85 {
86  uint8_t r, g, b;
87  SignalstatsContext *s = ctx->priv;
88 
89  if (s->outfilter != FILTER_NONE)
90  s->filters |= 1 << s->outfilter;
91 
92  r = s->rgba_color[0];
93  g = s->rgba_color[1];
94  b = s->rgba_color[2];
95  s->yuv_color[0] = (( 66*r + 129*g + 25*b + (1<<7)) >> 8) + 16;
96  s->yuv_color[1] = ((-38*r + -74*g + 112*b + (1<<7)) >> 8) + 128;
97  s->yuv_color[2] = ((112*r + -94*g + -18*b + (1<<7)) >> 8) + 128;
98  return 0;
99 }
100 
101 static av_cold void uninit(AVFilterContext *ctx)
102 {
103  SignalstatsContext *s = ctx->priv;
107  av_freep(&s->jobs_rets);
108 }
109 
111 {
112  // TODO: add more
113  static const enum AVPixelFormat pix_fmts[] = {
119  };
120 
122  return 0;
123 }
124 
125 static AVFrame *alloc_frame(enum AVPixelFormat pixfmt, int w, int h)
126 {
128  if (!frame)
129  return NULL;
130 
131  frame->format = pixfmt;
132  frame->width = w;
133  frame->height = h;
134 
135  if (av_frame_get_buffer(frame, 32) < 0) {
136  av_frame_free(&frame);
137  return NULL;
138  }
139 
140  return frame;
141 }
142 
143 static int config_props(AVFilterLink *outlink)
144 {
145  AVFilterContext *ctx = outlink->src;
146  SignalstatsContext *s = ctx->priv;
147  AVFilterLink *inlink = outlink->src->inputs[0];
148  const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(outlink->format);
149  s->hsub = desc->log2_chroma_w;
150  s->vsub = desc->log2_chroma_h;
151 
152  outlink->w = inlink->w;
153  outlink->h = inlink->h;
154 
155  s->chromaw = FF_CEIL_RSHIFT(inlink->w, s->hsub);
156  s->chromah = FF_CEIL_RSHIFT(inlink->h, s->vsub);
157 
158  s->fs = inlink->w * inlink->h;
159  s->cfs = s->chromaw * s->chromah;
160 
161  s->nb_jobs = FFMAX(1, FFMIN(inlink->h, ctx->graph->nb_threads));
162  s->jobs_rets = av_malloc_array(s->nb_jobs, sizeof(*s->jobs_rets));
163  if (!s->jobs_rets)
164  return AVERROR(ENOMEM);
165 
166  s->frame_sat = alloc_frame(AV_PIX_FMT_GRAY8, inlink->w, inlink->h);
167  s->frame_hue = alloc_frame(AV_PIX_FMT_GRAY16, inlink->w, inlink->h);
168  if (!s->frame_sat || !s->frame_hue)
169  return AVERROR(ENOMEM);
170 
171  return 0;
172 }
173 
174 static void burn_frame(const SignalstatsContext *s, AVFrame *f, int x, int y)
175 {
176  const int chromax = x >> s->hsub;
177  const int chromay = y >> s->vsub;
178  f->data[0][y * f->linesize[0] + x] = s->yuv_color[0];
179  f->data[1][chromay * f->linesize[1] + chromax] = s->yuv_color[1];
180  f->data[2][chromay * f->linesize[2] + chromax] = s->yuv_color[2];
181 }
182 
183 static int filter_brng(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
184 {
185  ThreadData *td = arg;
186  const SignalstatsContext *s = ctx->priv;
187  const AVFrame *in = td->in;
188  AVFrame *out = td->out;
189  const int w = in->width;
190  const int h = in->height;
191  const int slice_start = (h * jobnr ) / nb_jobs;
192  const int slice_end = (h * (jobnr+1)) / nb_jobs;
193  int x, y, score = 0;
194 
195  for (y = slice_start; y < slice_end; y++) {
196  const int yc = y >> s->vsub;
197  const uint8_t *pluma = &in->data[0][y * in->linesize[0]];
198  const uint8_t *pchromau = &in->data[1][yc * in->linesize[1]];
199  const uint8_t *pchromav = &in->data[2][yc * in->linesize[2]];
200 
201  for (x = 0; x < w; x++) {
202  const int xc = x >> s->hsub;
203  const int luma = pluma[x];
204  const int chromau = pchromau[xc];
205  const int chromav = pchromav[xc];
206  const int filt = luma < 16 || luma > 235 ||
207  chromau < 16 || chromau > 240 ||
208  chromav < 16 || chromav > 240;
209  score += filt;
210  if (out && filt)
211  burn_frame(s, out, x, y);
212  }
213  }
214  return score;
215 }
216 
218 {
219  return ((abs(x - y) + abs (z - y)) / 2) - abs(z - x) > 4; // make 4 configurable?
220 }
221 
222 static int filter_tout(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
223 {
224  ThreadData *td = arg;
225  const SignalstatsContext *s = ctx->priv;
226  const AVFrame *in = td->in;
227  AVFrame *out = td->out;
228  const int w = in->width;
229  const int h = in->height;
230  const int slice_start = (h * jobnr ) / nb_jobs;
231  const int slice_end = (h * (jobnr+1)) / nb_jobs;
232  const uint8_t *p = in->data[0];
233  int lw = in->linesize[0];
234  int x, y, score = 0, filt;
235 
236  for (y = slice_start; y < slice_end; y++) {
237 
238  if (y - 1 < 0 || y + 1 >= h)
239  continue;
240 
241  // detect two pixels above and below (to eliminate interlace artefacts)
242  // should check that video format is infact interlaced.
243 
244 #define FILTER(i, j) \
245  filter_tout_outlier(p[(y-j) * lw + x + i], \
246  p[ y * lw + x + i], \
247  p[(y+j) * lw + x + i])
248 
249 #define FILTER3(j) (FILTER(-1, j) && FILTER(0, j) && FILTER(1, j))
250 
251  if (y - 2 >= 0 && y + 2 < h) {
252  for (x = 1; x < w - 1; x++) {
253  filt = FILTER3(2) && FILTER3(1);
254  score += filt;
255  if (filt && out)
256  burn_frame(s, out, x, y);
257  }
258  } else {
259  for (x = 1; x < w - 1; x++) {
260  filt = FILTER3(1);
261  score += filt;
262  if (filt && out)
263  burn_frame(s, out, x, y);
264  }
265  }
266  }
267  return score;
268 }
269 
270 #define VREP_START 4
271 
272 static int filter_vrep(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
273 {
274  ThreadData *td = arg;
275  const SignalstatsContext *s = ctx->priv;
276  const AVFrame *in = td->in;
277  AVFrame *out = td->out;
278  const int w = in->width;
279  const int h = in->height;
280  const int slice_start = (h * jobnr ) / nb_jobs;
281  const int slice_end = (h * (jobnr+1)) / nb_jobs;
282  const uint8_t *p = in->data[0];
283  const int lw = in->linesize[0];
284  int x, y, score = 0;
285 
286  for (y = slice_start; y < slice_end; y++) {
287  const int y2lw = (y - VREP_START) * lw;
288  const int ylw = y * lw;
289  int filt, totdiff = 0;
290 
291  if (y < VREP_START)
292  continue;
293 
294  for (x = 0; x < w; x++)
295  totdiff += abs(p[y2lw + x] - p[ylw + x]);
296  filt = totdiff < w;
297 
298  score += filt;
299  if (filt && out)
300  for (x = 0; x < w; x++)
301  burn_frame(s, out, x, y);
302  }
303  return score * w;
304 }
305 
306 static const struct {
307  const char *name;
308  int (*process)(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs);
309 } filters_def[] = {
310  {"TOUT", filter_tout},
311  {"VREP", filter_vrep},
312  {"BRNG", filter_brng},
313  {NULL}
314 };
315 
316 #define DEPTH 256
317 
318 static int compute_sat_hue_metrics(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
319 {
320  int i, j;
322  const SignalstatsContext *s = ctx->priv;
323  const AVFrame *src = td->src;
324  AVFrame *dst_sat = td->dst_sat;
325  AVFrame *dst_hue = td->dst_hue;
326 
327  const int slice_start = (s->chromah * jobnr ) / nb_jobs;
328  const int slice_end = (s->chromah * (jobnr+1)) / nb_jobs;
329 
330  const int lsz_u = src->linesize[1];
331  const int lsz_v = src->linesize[2];
332  const uint8_t *p_u = src->data[1] + slice_start * lsz_u;
333  const uint8_t *p_v = src->data[2] + slice_start * lsz_v;
334 
335  const int lsz_sat = dst_sat->linesize[0];
336  const int lsz_hue = dst_hue->linesize[0];
337  uint8_t *p_sat = dst_sat->data[0] + slice_start * lsz_sat;
338  uint8_t *p_hue = dst_hue->data[0] + slice_start * lsz_hue;
339 
340  for (j = slice_start; j < slice_end; j++) {
341  for (i = 0; i < s->chromaw; i++) {
342  const int yuvu = p_u[i];
343  const int yuvv = p_v[i];
344  p_sat[i] = hypot(yuvu - 128, yuvv - 128); // int or round?
345  ((int16_t*)p_hue)[i] = floor((180 / M_PI) * atan2f(yuvu-128, yuvv-128) + 180);
346  }
347  p_u += lsz_u;
348  p_v += lsz_v;
349  p_sat += lsz_sat;
350  p_hue += lsz_hue;
351  }
352 
353  return 0;
354 }
355 
356 static int filter_frame(AVFilterLink *link, AVFrame *in)
357 {
358  AVFilterContext *ctx = link->dst;
359  SignalstatsContext *s = ctx->priv;
360  AVFilterLink *outlink = ctx->outputs[0];
361  AVFrame *out = in;
362  int i, j;
363  int w = 0, cw = 0, // in
364  pw = 0, cpw = 0; // prev
365  int fil;
366  char metabuf[128];
367  unsigned int histy[DEPTH] = {0},
368  histu[DEPTH] = {0},
369  histv[DEPTH] = {0},
370  histhue[360] = {0},
371  histsat[DEPTH] = {0}; // limited to 8 bit data.
372  int miny = -1, minu = -1, minv = -1;
373  int maxy = -1, maxu = -1, maxv = -1;
374  int lowy = -1, lowu = -1, lowv = -1;
375  int highy = -1, highu = -1, highv = -1;
376  int minsat = -1, maxsat = -1, lowsat = -1, highsat = -1;
377  int lowp, highp, clowp, chighp;
378  int accy, accu, accv;
379  int accsat, acchue = 0;
380  int medhue, maxhue;
381  int toty = 0, totu = 0, totv = 0, totsat=0;
382  int tothue = 0;
383  int dify = 0, difu = 0, difv = 0;
384 
385  int filtot[FILT_NUMB] = {0};
386  AVFrame *prev;
387 
388  AVFrame *sat = s->frame_sat;
389  AVFrame *hue = s->frame_hue;
390  const uint8_t *p_sat = sat->data[0];
391  const uint8_t *p_hue = hue->data[0];
392  const int lsz_sat = sat->linesize[0];
393  const int lsz_hue = hue->linesize[0];
394  ThreadDataHueSatMetrics td_huesat = {
395  .src = in,
396  .dst_sat = sat,
397  .dst_hue = hue,
398  };
399 
400  if (!s->frame_prev)
401  s->frame_prev = av_frame_clone(in);
402 
403  prev = s->frame_prev;
404 
405  if (s->outfilter != FILTER_NONE) {
406  out = av_frame_clone(in);
408  }
409 
410  ctx->internal->execute(ctx, compute_sat_hue_metrics, &td_huesat,
411  NULL, FFMIN(s->chromah, ctx->graph->nb_threads));
412 
413  // Calculate luma histogram and difference with previous frame or field.
414  for (j = 0; j < link->h; j++) {
415  for (i = 0; i < link->w; i++) {
416  const int yuv = in->data[0][w + i];
417  histy[yuv]++;
418  dify += abs(yuv - prev->data[0][pw + i]);
419  }
420  w += in->linesize[0];
421  pw += prev->linesize[0];
422  }
423 
424  // Calculate chroma histogram and difference with previous frame or field.
425  for (j = 0; j < s->chromah; j++) {
426  for (i = 0; i < s->chromaw; i++) {
427  const int yuvu = in->data[1][cw+i];
428  const int yuvv = in->data[2][cw+i];
429  histu[yuvu]++;
430  difu += abs(yuvu - prev->data[1][cpw+i]);
431  histv[yuvv]++;
432  difv += abs(yuvv - prev->data[2][cpw+i]);
433 
434  histsat[p_sat[i]]++;
435  histhue[((int16_t*)p_hue)[i]]++;
436  }
437  cw += in->linesize[1];
438  cpw += prev->linesize[1];
439  p_sat += lsz_sat;
440  p_hue += lsz_hue;
441  }
442 
443  for (fil = 0; fil < FILT_NUMB; fil ++) {
444  if (s->filters & 1<<fil) {
445  ThreadData td = {
446  .in = in,
447  .out = out != in && s->outfilter == fil ? out : NULL,
448  };
449  memset(s->jobs_rets, 0, s->nb_jobs * sizeof(*s->jobs_rets));
450  ctx->internal->execute(ctx, filters_def[fil].process,
451  &td, s->jobs_rets, s->nb_jobs);
452  for (i = 0; i < s->nb_jobs; i++)
453  filtot[fil] += s->jobs_rets[i];
454  }
455  }
456 
457  // find low / high based on histogram percentile
458  // these only need to be calculated once.
459 
460  lowp = lrint(s->fs * 10 / 100.);
461  highp = lrint(s->fs * 90 / 100.);
462  clowp = lrint(s->cfs * 10 / 100.);
463  chighp = lrint(s->cfs * 90 / 100.);
464 
465  accy = accu = accv = accsat = 0;
466  for (fil = 0; fil < DEPTH; fil++) {
467  if (miny < 0 && histy[fil]) miny = fil;
468  if (minu < 0 && histu[fil]) minu = fil;
469  if (minv < 0 && histv[fil]) minv = fil;
470  if (minsat < 0 && histsat[fil]) minsat = fil;
471 
472  if (histy[fil]) maxy = fil;
473  if (histu[fil]) maxu = fil;
474  if (histv[fil]) maxv = fil;
475  if (histsat[fil]) maxsat = fil;
476 
477  toty += histy[fil] * fil;
478  totu += histu[fil] * fil;
479  totv += histv[fil] * fil;
480  totsat += histsat[fil] * fil;
481 
482  accy += histy[fil];
483  accu += histu[fil];
484  accv += histv[fil];
485  accsat += histsat[fil];
486 
487  if (lowy == -1 && accy >= lowp) lowy = fil;
488  if (lowu == -1 && accu >= clowp) lowu = fil;
489  if (lowv == -1 && accv >= clowp) lowv = fil;
490  if (lowsat == -1 && accsat >= clowp) lowsat = fil;
491 
492  if (highy == -1 && accy >= highp) highy = fil;
493  if (highu == -1 && accu >= chighp) highu = fil;
494  if (highv == -1 && accv >= chighp) highv = fil;
495  if (highsat == -1 && accsat >= chighp) highsat = fil;
496  }
497 
498  maxhue = histhue[0];
499  medhue = -1;
500  for (fil = 0; fil < 360; fil++) {
501  tothue += histhue[fil] * fil;
502  acchue += histhue[fil];
503 
504  if (medhue == -1 && acchue > s->cfs / 2)
505  medhue = fil;
506  if (histhue[fil] > maxhue) {
507  maxhue = histhue[fil];
508  }
509  }
510 
512  s->frame_prev = av_frame_clone(in);
513 
514 #define SET_META(key, fmt, val) do { \
515  snprintf(metabuf, sizeof(metabuf), fmt, val); \
516  av_dict_set(&out->metadata, "lavfi.signalstats." key, metabuf, 0); \
517 } while (0)
518 
519  SET_META("YMIN", "%d", miny);
520  SET_META("YLOW", "%d", lowy);
521  SET_META("YAVG", "%g", 1.0 * toty / s->fs);
522  SET_META("YHIGH", "%d", highy);
523  SET_META("YMAX", "%d", maxy);
524 
525  SET_META("UMIN", "%d", minu);
526  SET_META("ULOW", "%d", lowu);
527  SET_META("UAVG", "%g", 1.0 * totu / s->cfs);
528  SET_META("UHIGH", "%d", highu);
529  SET_META("UMAX", "%d", maxu);
530 
531  SET_META("VMIN", "%d", minv);
532  SET_META("VLOW", "%d", lowv);
533  SET_META("VAVG", "%g", 1.0 * totv / s->cfs);
534  SET_META("VHIGH", "%d", highv);
535  SET_META("VMAX", "%d", maxv);
536 
537  SET_META("SATMIN", "%d", minsat);
538  SET_META("SATLOW", "%d", lowsat);
539  SET_META("SATAVG", "%g", 1.0 * totsat / s->cfs);
540  SET_META("SATHIGH", "%d", highsat);
541  SET_META("SATMAX", "%d", maxsat);
542 
543  SET_META("HUEMED", "%d", medhue);
544  SET_META("HUEAVG", "%g", 1.0 * tothue / s->cfs);
545 
546  SET_META("YDIF", "%g", 1.0 * dify / s->fs);
547  SET_META("UDIF", "%g", 1.0 * difu / s->cfs);
548  SET_META("VDIF", "%g", 1.0 * difv / s->cfs);
549 
550  for (fil = 0; fil < FILT_NUMB; fil ++) {
551  if (s->filters & 1<<fil) {
552  char metaname[128];
553  snprintf(metabuf, sizeof(metabuf), "%g", 1.0 * filtot[fil] / s->fs);
554  snprintf(metaname, sizeof(metaname), "lavfi.signalstats.%s", filters_def[fil].name);
555  av_dict_set(&out->metadata, metaname, metabuf, 0);
556  }
557  }
558 
559  if (in != out)
560  av_frame_free(&in);
561  return ff_filter_frame(outlink, out);
562 }
563 
564 static const AVFilterPad signalstats_inputs[] = {
565  {
566  .name = "default",
567  .type = AVMEDIA_TYPE_VIDEO,
568  .filter_frame = filter_frame,
569  },
570  { NULL }
571 };
572 
574  {
575  .name = "default",
576  .config_props = config_props,
577  .type = AVMEDIA_TYPE_VIDEO,
578  },
579  { NULL }
580 };
581 
583  .name = "signalstats",
584  .description = "Generate statistics from video analysis.",
585  .init = init,
586  .uninit = uninit,
587  .query_formats = query_formats,
588  .priv_size = sizeof(SignalstatsContext),
589  .inputs = signalstats_inputs,
590  .outputs = signalstats_outputs,
591  .priv_class = &signalstats_class,
593 };