FFmpeg
vf_photosensitivity.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2019 Vladimir Panteleev
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 
21 #include <float.h>
22 
23 #include "libavutil/imgutils.h"
24 #include "libavutil/opt.h"
25 #include "libavutil/pixdesc.h"
26 #include "avfilter.h"
27 
28 #include "filters.h"
29 #include "formats.h"
30 #include "internal.h"
31 #include "video.h"
32 
33 #define MAX_FRAMES 240
34 #define GRID_SIZE 8
35 #define NUM_CHANNELS 3
36 
37 typedef struct PhotosensitivityFrame {
38  uint8_t grid[GRID_SIZE][GRID_SIZE][4];
40 
41 typedef struct PhotosensitivityContext {
42  const AVClass *class;
43 
44  int nb_frames;
45  int skip;
47  int bypass;
48 
50 
51  /* Circular buffer */
54 
58 
59 #define OFFSET(x) offsetof(PhotosensitivityContext, x)
60 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
61 
63  { "frames", "set how many frames to use", OFFSET(nb_frames), AV_OPT_TYPE_INT, {.i64=30}, 2, MAX_FRAMES, FLAGS },
64  { "f", "set how many frames to use", OFFSET(nb_frames), AV_OPT_TYPE_INT, {.i64=30}, 2, MAX_FRAMES, FLAGS },
65  { "threshold", "set detection threshold factor (lower is stricter)", OFFSET(threshold_multiplier), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0.1, FLT_MAX, FLAGS },
66  { "t", "set detection threshold factor (lower is stricter)", OFFSET(threshold_multiplier), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0.1, FLT_MAX, FLAGS },
67  { "skip", "set pixels to skip when sampling frames", OFFSET(skip), AV_OPT_TYPE_INT, {.i64=1}, 1, 1024, FLAGS },
68  { "bypass", "leave frames unchanged", OFFSET(bypass), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS },
69  { NULL }
70 };
71 
72 AVFILTER_DEFINE_CLASS(photosensitivity);
73 
75 {
78  int skip;
80 
81 #define NUM_CELLS (GRID_SIZE * GRID_SIZE)
82 
83 static int convert_frame_partial(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
84 {
85  int cell, gx, gy, x0, x1, y0, y1, x, y, c, area;
86  int sum[NUM_CHANNELS];
87  const uint8_t *p;
88 
90 
91  const int slice_start = (NUM_CELLS * jobnr) / nb_jobs;
92  const int slice_end = (NUM_CELLS * (jobnr+1)) / nb_jobs;
93 
94  int width = td->in->width, height = td->in->height, linesize = td->in->linesize[0], skip = td->skip;
95  const uint8_t *data = td->in->data[0];
96 
97  for (cell = slice_start; cell < slice_end; cell++) {
98  gx = cell % GRID_SIZE;
99  gy = cell / GRID_SIZE;
100 
101  x0 = width * gx / GRID_SIZE;
102  x1 = width * (gx+1) / GRID_SIZE;
103  y0 = height * gy / GRID_SIZE;
104  y1 = height * (gy+1) / GRID_SIZE;
105 
106  for (c = 0; c < NUM_CHANNELS; c++) {
107  sum[c] = 0;
108  }
109  for (y = y0; y < y1; y += skip) {
110  p = data + y * linesize + x0 * NUM_CHANNELS;
111  for (x = x0; x < x1; x += skip) {
112  //av_log(NULL, AV_LOG_VERBOSE, "%d %d %d : (%d,%d) (%d,%d) -> %d,%d | *%d\n", c, gx, gy, x0, y0, x1, y1, x, y, (int)row);
113  sum[0] += p[0];
114  sum[1] += p[1];
115  sum[2] += p[2];
116  p += NUM_CHANNELS * skip;
117  // TODO: variable size
118  }
119  }
120 
121  area = ((x1 - x0 + skip - 1) / skip) * ((y1 - y0 + skip - 1) / skip);
122  for (c = 0; c < NUM_CHANNELS; c++) {
123  if (area)
124  sum[c] /= area;
125  td->out->grid[gy][gx][c] = sum[c];
126  }
127  }
128  return 0;
129 }
130 
132 {
134  td.in = in;
135  td.out = out;
136  td.skip = skip;
139 }
140 
142 {
145  uint16_t s_mul;
147 
148 static int blend_frame_partial(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
149 {
150  int x, y;
151  uint8_t *t, *s;
152 
154  const uint16_t s_mul = td->s_mul;
155  const uint16_t t_mul = 0x100 - s_mul;
156  const int slice_start = (td->target->height * jobnr) / nb_jobs;
157  const int slice_end = (td->target->height * (jobnr+1)) / nb_jobs;
158  const int linesize = td->target->linesize[0];
159 
160  for (y = slice_start; y < slice_end; y++) {
161  t = td->target->data[0] + y * td->target->linesize[0];
162  s = td->source->data[0] + y * td->source->linesize[0];
163  for (x = 0; x < linesize; x++) {
164  *t = (*t * t_mul + *s * s_mul) >> 8;
165  t++; s++;
166  }
167  }
168  return 0;
169 }
170 
171 static void blend_frame(AVFilterContext *ctx, AVFrame *target, AVFrame *source, float factor)
172 {
174  td.target = target;
175  td.source = source;
176  td.s_mul = (uint16_t)(factor * 0x100);
178  FFMIN(ctx->outputs[0]->h, ff_filter_get_nb_threads(ctx)));
179 }
180 
182 {
183  int badness, x, y, c;
184  badness = 0;
185  for (c = 0; c < NUM_CHANNELS; c++) {
186  for (y = 0; y < GRID_SIZE; y++) {
187  for (x = 0; x < GRID_SIZE; x++) {
188  badness += abs((int)a->grid[y][x][c] - (int)b->grid[y][x][c]);
189  //av_log(NULL, AV_LOG_VERBOSE, "%d - %d -> %d \n", a->grid[y][x], b->grid[y][x], badness);
190  //av_log(NULL, AV_LOG_VERBOSE, "%d -> %d \n", abs((int)a->grid[y][x] - (int)b->grid[y][x]), badness);
191  }
192  }
193  }
194  return badness;
195 }
196 
198 {
199  /* const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format); */
200  AVFilterContext *ctx = inlink->dst;
201  PhotosensitivityContext *s = ctx->priv;
202 
203  s->badness_threshold = (int)(GRID_SIZE * GRID_SIZE * 4 * 256 * s->nb_frames * s->threshold_multiplier / 128);
204 
205  return 0;
206 }
207 
209 {
210  int this_badness, current_badness, fixed_badness, new_badness, i, res;
212  AVFrame *src, *out;
213  int free_in = 0;
214  float factor;
215  AVDictionary **metadata;
216 
217  AVFilterContext *ctx = inlink->dst;
218  AVFilterLink *outlink = ctx->outputs[0];
219  PhotosensitivityContext *s = ctx->priv;
220 
221  /* weighted moving average */
222  current_badness = 0;
223  for (i = 1; i < s->nb_frames; i++)
224  current_badness += i * s->history[(s->history_pos + i) % s->nb_frames];
225  current_badness /= s->nb_frames;
226 
227  convert_frame(ctx, in, &ef, s->skip);
228  this_badness = get_badness(&ef, &s->last_frame_e);
229  new_badness = current_badness + this_badness;
230  av_log(s, AV_LOG_VERBOSE, "badness: %6d -> %6d / %6d (%3d%% - %s)\n",
231  current_badness, new_badness, s->badness_threshold,
232  100 * new_badness / s->badness_threshold, new_badness < s->badness_threshold ? "OK" : "EXCEEDED");
233 
234  fixed_badness = new_badness;
235  if (new_badness < s->badness_threshold || !s->last_frame_av || s->bypass) {
236  factor = 1; /* for metadata */
237  av_frame_free(&s->last_frame_av);
238  s->last_frame_av = src = in;
239  s->last_frame_e = ef;
240  s->history[s->history_pos] = this_badness;
241  } else {
242  factor = (float)(s->badness_threshold - current_badness) / (new_badness - current_badness);
243  if (factor <= 0) {
244  /* just duplicate the frame */
245  s->history[s->history_pos] = 0; /* frame was duplicated, thus, delta is zero */
246  } else {
247  res = ff_inlink_make_frame_writable(inlink, &s->last_frame_av);
248  if (res) {
249  av_frame_free(&in);
250  return res;
251  }
252  blend_frame(ctx, s->last_frame_av, in, factor);
253 
254  convert_frame(ctx, s->last_frame_av, &ef, s->skip);
255  this_badness = get_badness(&ef, &s->last_frame_e);
256  fixed_badness = current_badness + this_badness;
257  av_log(s, AV_LOG_VERBOSE, " fixed: %6d -> %6d / %6d (%3d%%) factor=%5.3f\n",
258  current_badness, fixed_badness, s->badness_threshold,
259  100 * new_badness / s->badness_threshold, factor);
260  s->last_frame_e = ef;
261  s->history[s->history_pos] = this_badness;
262  }
263  src = s->last_frame_av;
264  free_in = 1;
265  }
266  s->history_pos = (s->history_pos + 1) % s->nb_frames;
267 
268  out = ff_get_video_buffer(outlink, in->width, in->height);
269  if (!out) {
270  if (free_in == 1)
271  av_frame_free(&in);
272  return AVERROR(ENOMEM);
273  }
275  metadata = &out->metadata;
276  if (metadata) {
277  char value[128];
278 
279  snprintf(value, sizeof(value), "%f", (float)new_badness / s->badness_threshold);
280  av_dict_set(metadata, "lavfi.photosensitivity.badness", value, 0);
281 
282  snprintf(value, sizeof(value), "%f", (float)fixed_badness / s->badness_threshold);
283  av_dict_set(metadata, "lavfi.photosensitivity.fixed-badness", value, 0);
284 
285  snprintf(value, sizeof(value), "%f", (float)this_badness / s->badness_threshold);
286  av_dict_set(metadata, "lavfi.photosensitivity.frame-badness", value, 0);
287 
288  snprintf(value, sizeof(value), "%f", factor);
289  av_dict_set(metadata, "lavfi.photosensitivity.factor", value, 0);
290  }
292  if (free_in == 1)
293  av_frame_free(&in);
294  return ff_filter_frame(outlink, out);
295 }
296 
298 {
299  PhotosensitivityContext *s = ctx->priv;
300 
301  av_frame_free(&s->last_frame_av);
302 }
303 
304 static const AVFilterPad inputs[] = {
305  {
306  .name = "default",
307  .type = AVMEDIA_TYPE_VIDEO,
308  .filter_frame = filter_frame,
309  .config_props = config_input,
310  },
311 };
312 
313 static const AVFilterPad outputs[] = {
314  {
315  .name = "default",
316  .type = AVMEDIA_TYPE_VIDEO,
317  },
318 };
319 
321  .name = "photosensitivity",
322  .description = NULL_IF_CONFIG_SMALL("Filter out photosensitive epilepsy seizure-inducing flashes."),
323  .priv_size = sizeof(PhotosensitivityContext),
324  .priv_class = &photosensitivity_class,
325  .uninit = uninit,
329 };
ff_get_video_buffer
AVFrame * ff_get_video_buffer(AVFilterLink *link, int w, int h)
Request a picture buffer with a specific set of permissions.
Definition: video.c:101
td
#define td
Definition: regdef.h:70
AVFILTER_DEFINE_CLASS
AVFILTER_DEFINE_CLASS(photosensitivity)
AVERROR
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
opt.h
config_input
static int config_input(AVFilterLink *inlink)
Definition: vf_photosensitivity.c:197
out
FILE * out
Definition: movenc.c:54
ff_filter_frame
int ff_filter_frame(AVFilterLink *link, AVFrame *frame)
Send a frame of data to the next filter.
Definition: avfilter.c:969
PhotosensitivityContext
Definition: vf_photosensitivity.c:41
inlink
The exact code depends on how similar the blocks are and how related they are to the and needs to apply these operations to the correct inlink or outlink if there are several Macros are available to factor that when no extra processing is inlink
Definition: filter_design.txt:212
PhotosensitivityContext::history
int history[MAX_FRAMES]
Definition: vf_photosensitivity.c:52
PhotosensitivityContext::badness_threshold
int badness_threshold
Definition: vf_photosensitivity.c:49
av_frame_free
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:99
AVFrame
This structure describes decoded (raw) audio or video data.
Definition: frame.h:330
pixdesc.h
AVFrame::width
int width
Definition: frame.h:402
GRID_SIZE
#define GRID_SIZE
Definition: vf_photosensitivity.c:34
AVOption
AVOption.
Definition: opt.h:251
b
#define b
Definition: input.c:41
data
const char data[16]
Definition: mxf.c:146
AV_LOG_VERBOSE
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:196
float.h
AV_PIX_FMT_BGR24
@ AV_PIX_FMT_BGR24
packed RGB 8:8:8, 24bpp, BGRBGR...
Definition: pixfmt.h:69
AVDictionary
Definition: dict.c:32
AVFilter::name
const char * name
Filter name.
Definition: avfilter.h:165
video.h
convert_frame_partial
static int convert_frame_partial(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
Definition: vf_photosensitivity.c:83
formats.h
ThreadData_blend_frame::target
AVFrame * target
Definition: vf_photosensitivity.c:143
uninit
static av_cold void uninit(AVFilterContext *ctx)
Definition: vf_photosensitivity.c:297
photosensitivity_options
static const AVOption photosensitivity_options[]
Definition: vf_photosensitivity.c:62
PhotosensitivityContext::last_frame_e
PhotosensitivityFrame last_frame_e
Definition: vf_photosensitivity.c:55
PhotosensitivityContext::last_frame_av
AVFrame * last_frame_av
Definition: vf_photosensitivity.c:56
ThreadData_convert_frame::skip
int skip
Definition: vf_photosensitivity.c:78
ff_vf_photosensitivity
const AVFilter ff_vf_photosensitivity
Definition: vf_photosensitivity.c:320
AVFilterPad
A filter pad used for either input or output.
Definition: internal.h:49
av_cold
#define av_cold
Definition: attributes.h:90
float
float
Definition: af_crystalizer.c:122
width
#define width
s
#define s(width, name)
Definition: cbs_vp9.c:256
ThreadData_convert_frame
Definition: vf_photosensitivity.c:74
slice_end
static int slice_end(AVCodecContext *avctx, AVFrame *pict)
Handle slice ends.
Definition: mpeg12dec.c:2006
PhotosensitivityFrame::grid
uint8_t grid[GRID_SIZE][GRID_SIZE][4]
Definition: vf_photosensitivity.c:38
OFFSET
#define OFFSET(x)
Definition: vf_photosensitivity.c:59
filters.h
outputs
static const AVFilterPad outputs[]
Definition: vf_photosensitivity.c:313
ctx
AVFormatContext * ctx
Definition: movenc.c:48
FILTER_INPUTS
#define FILTER_INPUTS(array)
Definition: internal.h:194
convert_frame
static void convert_frame(AVFilterContext *ctx, AVFrame *in, PhotosensitivityFrame *out, int skip)
Definition: vf_photosensitivity.c:131
ff_inlink_make_frame_writable
int ff_inlink_make_frame_writable(AVFilterLink *link, AVFrame **rframe)
Make sure a frame is writable.
Definition: avfilter.c:1408
arg
const char * arg
Definition: jacosubdec.c:67
AVClass
Describe the class of an AVClass context structure.
Definition: log.h:66
NULL
#define NULL
Definition: coverity.c:32
av_frame_copy_props
int av_frame_copy_props(AVFrame *dst, const AVFrame *src)
Copy only "metadata" fields from src to dst.
Definition: frame.c:594
FLAGS
#define FLAGS
Definition: vf_photosensitivity.c:60
ThreadData_convert_frame::out
PhotosensitivityFrame * out
Definition: vf_photosensitivity.c:77
PhotosensitivityFrame
Definition: vf_photosensitivity.c:37
abs
#define abs(x)
Definition: cuda_runtime.h:35
c
Undefined Behavior In the C some operations are like signed integer dereferencing freed accessing outside allocated Undefined Behavior must not occur in a C it is not safe even if the output of undefined operations is unused The unsafety may seem nit picking but Optimizing compilers have in fact optimized code on the assumption that no undefined Behavior occurs Optimizing code based on wrong assumptions can and has in some cases lead to effects beyond the output of computations The signed integer overflow problem in speed critical code Code which is highly optimized and works with signed integers sometimes has the problem that often the output of the computation does not c
Definition: undefined.txt:32
PhotosensitivityContext::history_pos
int history_pos
Definition: vf_photosensitivity.c:53
source
these buffered frames must be flushed immediately if a new input produces new the filter must not call request_frame to get more It must just process the frame or queue it The task of requesting more frames is left to the filter s request_frame method or the application If a filter has several the filter must be ready for frames arriving randomly on any input any filter with several inputs will most likely require some kind of queuing mechanism It is perfectly acceptable to have a limited queue and to drop frames when the inputs are too unbalanced request_frame For filters that do not use the this method is called when a frame is wanted on an output For a source
Definition: filter_design.txt:255
AV_PIX_FMT_RGB24
@ AV_PIX_FMT_RGB24
packed RGB 8:8:8, 24bpp, RGBRGB...
Definition: pixfmt.h:68
NULL_IF_CONFIG_SMALL
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition: internal.h:115
FILTER_PIXFMTS
#define FILTER_PIXFMTS(...)
Definition: internal.h:180
av_frame_copy
int av_frame_copy(AVFrame *dst, const AVFrame *src)
Copy the frame data from src to dst.
Definition: frame.c:762
filter_frame
static int filter_frame(AVFilterLink *inlink, AVFrame *in)
Definition: vf_photosensitivity.c:208
blend_frame
static void blend_frame(AVFilterContext *ctx, AVFrame *target, AVFrame *source, float factor)
Definition: vf_photosensitivity.c:171
height
#define height
a
The reader does not expect b to be semantically here and if the code is changed by maybe adding a a division or other the signedness will almost certainly be mistaken To avoid this confusion a new type was SUINT is the C unsigned type but it holds a signed int to use the same example SUINT a
Definition: undefined.txt:41
internal.h
AV_OPT_TYPE_FLOAT
@ AV_OPT_TYPE_FLOAT
Definition: opt.h:228
PhotosensitivityContext::skip
int skip
Definition: vf_photosensitivity.c:45
NUM_CHANNELS
#define NUM_CHANNELS
Definition: vf_photosensitivity.c:35
i
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:269
ff_filter_get_nb_threads
int ff_filter_get_nb_threads(AVFilterContext *ctx)
Get number of threads for current filter instance.
Definition: avfilter.c:777
value
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf default value
Definition: writing_filters.txt:86
FFMIN
#define FFMIN(a, b)
Definition: macros.h:49
ThreadData_blend_frame::s_mul
uint16_t s_mul
Definition: vf_photosensitivity.c:145
AVFilterPad::name
const char * name
Pad name.
Definition: internal.h:55
PhotosensitivityContext::bypass
int bypass
Definition: vf_photosensitivity.c:47
AVFilter
Filter definition.
Definition: avfilter.h:161
ThreadData_blend_frame
Definition: vf_photosensitivity.c:141
ThreadData_blend_frame::source
AVFrame * source
Definition: vf_photosensitivity.c:144
MAX_FRAMES
#define MAX_FRAMES
Definition: vf_photosensitivity.c:33
AVFrame::height
int height
Definition: frame.h:402
blend_frame_partial
static int blend_frame_partial(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
Definition: vf_photosensitivity.c:148
AV_OPT_TYPE_INT
@ AV_OPT_TYPE_INT
Definition: opt.h:225
avfilter.h
AVFilterContext
An instance of a filter.
Definition: avfilter.h:392
factor
static const int factor[16]
Definition: vf_pp7.c:76
AVMEDIA_TYPE_VIDEO
@ AVMEDIA_TYPE_VIDEO
Definition: avutil.h:201
inputs
static const AVFilterPad inputs[]
Definition: vf_photosensitivity.c:304
AV_OPT_TYPE_BOOL
@ AV_OPT_TYPE_BOOL
Definition: opt.h:244
FILTER_OUTPUTS
#define FILTER_OUTPUTS(array)
Definition: internal.h:195
av_dict_set
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:86
src
INIT_CLIP pixel * src
Definition: h264pred_template.c:418
imgutils.h
av_log
#define av_log(a,...)
Definition: tableprint_vlc.h:27
PhotosensitivityContext::nb_frames
int nb_frames
Definition: vf_photosensitivity.c:44
get_badness
static int get_badness(PhotosensitivityFrame *a, PhotosensitivityFrame *b)
Definition: vf_photosensitivity.c:181
ff_filter_execute
static av_always_inline int ff_filter_execute(AVFilterContext *ctx, avfilter_action_func *func, void *arg, int *ret, int nb_jobs)
Definition: internal.h:146
NUM_CELLS
#define NUM_CELLS
Definition: vf_photosensitivity.c:81
int
int
Definition: ffmpeg_filter.c:156
snprintf
#define snprintf
Definition: snprintf.h:34
PhotosensitivityContext::threshold_multiplier
float threshold_multiplier
Definition: vf_photosensitivity.c:46
skip
static void BS_FUNC() skip(BSCTX *bc, unsigned int n)
Skip n bits in the buffer.
Definition: bitstream_template.h:375
ThreadData_convert_frame::in
AVFrame * in
Definition: vf_photosensitivity.c:76