• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "formats.h"
29 #include "internal.h"
30 #include "video.h"
31 
32 #define MAX_FRAMES 240
33 #define GRID_SIZE 8
34 #define NUM_CHANNELS 3
35 
36 typedef struct PhotosensitivityFrame {
37     uint8_t grid[GRID_SIZE][GRID_SIZE][4];
38 } PhotosensitivityFrame;
39 
40 typedef struct PhotosensitivityContext {
41     const AVClass *class;
42 
43     int nb_frames;
44     int skip;
45     float threshold_multiplier;
46     int bypass;
47 
48     int badness_threshold;
49 
50     /* Circular buffer */
51     int history[MAX_FRAMES];
52     int history_pos;
53 
54     PhotosensitivityFrame last_frame_e;
55     AVFrame *last_frame_av;
56 } PhotosensitivityContext;
57 
58 #define OFFSET(x) offsetof(PhotosensitivityContext, x)
59 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
60 
61 static const AVOption photosensitivity_options[] = {
62     { "frames",    "set how many frames to use",                          OFFSET(nb_frames),            AV_OPT_TYPE_INT,   {.i64=30}, 2, MAX_FRAMES, FLAGS },
63     { "f",         "set how many frames to use",                          OFFSET(nb_frames),            AV_OPT_TYPE_INT,   {.i64=30}, 2, MAX_FRAMES, FLAGS },
64     { "threshold", "set detection threshold factor (lower is stricter)",  OFFSET(threshold_multiplier), AV_OPT_TYPE_FLOAT, {.dbl=1},  0.1, FLT_MAX,  FLAGS },
65     { "t",         "set detection threshold factor (lower is stricter)",  OFFSET(threshold_multiplier), AV_OPT_TYPE_FLOAT, {.dbl=1},  0.1, FLT_MAX,  FLAGS },
66     { "skip",      "set pixels to skip when sampling frames",             OFFSET(skip),                 AV_OPT_TYPE_INT,   {.i64=1},  1, 1024,       FLAGS },
67     { "bypass",    "leave frames unchanged",                              OFFSET(bypass),               AV_OPT_TYPE_BOOL,  {.i64=0},  0, 1,          FLAGS },
68     { NULL }
69 };
70 
71 AVFILTER_DEFINE_CLASS(photosensitivity);
72 
73 typedef struct ThreadData_convert_frame
74 {
75     AVFrame *in;
76     PhotosensitivityFrame *out;
77     int skip;
78 } ThreadData_convert_frame;
79 
80 #define NUM_CELLS (GRID_SIZE * GRID_SIZE)
81 
convert_frame_partial(AVFilterContext * ctx,void * arg,int jobnr,int nb_jobs)82 static int convert_frame_partial(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
83 {
84     int cell, gx, gy, x0, x1, y0, y1, x, y, c, area;
85     int sum[NUM_CHANNELS];
86     const uint8_t *p;
87 
88     ThreadData_convert_frame *td = arg;
89 
90     const int slice_start = (NUM_CELLS * jobnr) / nb_jobs;
91     const int slice_end = (NUM_CELLS * (jobnr+1)) / nb_jobs;
92 
93     int width = td->in->width, height = td->in->height, linesize = td->in->linesize[0], skip = td->skip;
94     const uint8_t *data = td->in->data[0];
95 
96     for (cell = slice_start; cell < slice_end; cell++) {
97         gx = cell % GRID_SIZE;
98         gy = cell / GRID_SIZE;
99 
100         x0 = width  *  gx    / GRID_SIZE;
101         x1 = width  * (gx+1) / GRID_SIZE;
102         y0 = height *  gy    / GRID_SIZE;
103         y1 = height * (gy+1) / GRID_SIZE;
104 
105         for (c = 0; c < NUM_CHANNELS; c++) {
106             sum[c] = 0;
107         }
108         for (y = y0; y < y1; y += skip) {
109             p = data + y * linesize + x0 * NUM_CHANNELS;
110             for (x = x0; x < x1; x += skip) {
111                 //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);
112                 sum[0] += p[0];
113                 sum[1] += p[1];
114                 sum[2] += p[2];
115                 p += NUM_CHANNELS * skip;
116                 // TODO: variable size
117             }
118         }
119 
120         area = ((x1 - x0 + skip - 1) / skip) * ((y1 - y0 + skip - 1) / skip);
121         for (c = 0; c < NUM_CHANNELS; c++) {
122             if (area)
123                 sum[c] /= area;
124             td->out->grid[gy][gx][c] = sum[c];
125         }
126     }
127     return 0;
128 }
129 
convert_frame(AVFilterContext * ctx,AVFrame * in,PhotosensitivityFrame * out,int skip)130 static void convert_frame(AVFilterContext *ctx, AVFrame *in, PhotosensitivityFrame *out, int skip)
131 {
132     ThreadData_convert_frame td;
133     td.in = in;
134     td.out = out;
135     td.skip = skip;
136     ff_filter_execute(ctx, convert_frame_partial, &td, NULL,
137                       FFMIN(NUM_CELLS, ff_filter_get_nb_threads(ctx)));
138 }
139 
140 typedef struct ThreadData_blend_frame
141 {
142     AVFrame *target;
143     AVFrame *source;
144     uint16_t s_mul;
145 } ThreadData_blend_frame;
146 
blend_frame_partial(AVFilterContext * ctx,void * arg,int jobnr,int nb_jobs)147 static int blend_frame_partial(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
148 {
149     int x, y;
150     uint8_t *t, *s;
151 
152     ThreadData_blend_frame *td = arg;
153     const uint16_t s_mul = td->s_mul;
154     const uint16_t t_mul = 0x100 - s_mul;
155     const int slice_start = (td->target->height * jobnr) / nb_jobs;
156     const int slice_end = (td->target->height * (jobnr+1)) / nb_jobs;
157     const int linesize = td->target->linesize[0];
158 
159     for (y = slice_start; y < slice_end; y++) {
160         t = td->target->data[0] + y * td->target->linesize[0];
161         s = td->source->data[0] + y * td->source->linesize[0];
162         for (x = 0; x < linesize; x++) {
163             *t = (*t * t_mul + *s * s_mul) >> 8;
164             t++; s++;
165         }
166     }
167     return 0;
168 }
169 
blend_frame(AVFilterContext * ctx,AVFrame * target,AVFrame * source,float factor)170 static void blend_frame(AVFilterContext *ctx, AVFrame *target, AVFrame *source, float factor)
171 {
172     ThreadData_blend_frame td;
173     td.target = target;
174     td.source = source;
175     td.s_mul = (uint16_t)(factor * 0x100);
176     ff_filter_execute(ctx, blend_frame_partial, &td, NULL,
177                       FFMIN(ctx->outputs[0]->h, ff_filter_get_nb_threads(ctx)));
178 }
179 
get_badness(PhotosensitivityFrame * a,PhotosensitivityFrame * b)180 static int get_badness(PhotosensitivityFrame *a, PhotosensitivityFrame *b)
181 {
182     int badness, x, y, c;
183     badness = 0;
184     for (c = 0; c < NUM_CHANNELS; c++) {
185         for (y = 0; y < GRID_SIZE; y++) {
186             for (x = 0; x < GRID_SIZE; x++) {
187                 badness += abs((int)a->grid[y][x][c] - (int)b->grid[y][x][c]);
188                 //av_log(NULL, AV_LOG_VERBOSE, "%d - %d -> %d \n", a->grid[y][x], b->grid[y][x], badness);
189                 //av_log(NULL, AV_LOG_VERBOSE, "%d -> %d \n", abs((int)a->grid[y][x] - (int)b->grid[y][x]), badness);
190             }
191         }
192     }
193     return badness;
194 }
195 
config_input(AVFilterLink * inlink)196 static int config_input(AVFilterLink *inlink)
197 {
198     /* const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format); */
199     AVFilterContext *ctx = inlink->dst;
200     PhotosensitivityContext *s = ctx->priv;
201 
202     s->badness_threshold = (int)(GRID_SIZE * GRID_SIZE * 4 * 256 * s->nb_frames * s->threshold_multiplier / 128);
203 
204     return 0;
205 }
206 
filter_frame(AVFilterLink * inlink,AVFrame * in)207 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
208 {
209     int this_badness, current_badness, fixed_badness, new_badness, i, res;
210     PhotosensitivityFrame ef;
211     AVFrame *src, *out;
212     int free_in = 0;
213     float factor;
214     AVDictionary **metadata;
215 
216     AVFilterContext *ctx = inlink->dst;
217     AVFilterLink *outlink = ctx->outputs[0];
218     PhotosensitivityContext *s = ctx->priv;
219 
220     /* weighted moving average */
221     current_badness = 0;
222     for (i = 1; i < s->nb_frames; i++)
223         current_badness += i * s->history[(s->history_pos + i) % s->nb_frames];
224     current_badness /= s->nb_frames;
225 
226     convert_frame(ctx, in, &ef, s->skip);
227     this_badness = get_badness(&ef, &s->last_frame_e);
228     new_badness = current_badness + this_badness;
229     av_log(s, AV_LOG_VERBOSE, "badness: %6d -> %6d / %6d (%3d%% - %s)\n",
230         current_badness, new_badness, s->badness_threshold,
231         100 * new_badness / s->badness_threshold, new_badness < s->badness_threshold ? "OK" : "EXCEEDED");
232 
233     fixed_badness = new_badness;
234     if (new_badness < s->badness_threshold || !s->last_frame_av || s->bypass) {
235         factor = 1; /* for metadata */
236         av_frame_free(&s->last_frame_av);
237         s->last_frame_av = src = in;
238         s->last_frame_e = ef;
239         s->history[s->history_pos] = this_badness;
240     } else {
241         factor = (float)(s->badness_threshold - current_badness) / (new_badness - current_badness);
242         if (factor <= 0) {
243             /* just duplicate the frame */
244             s->history[s->history_pos] = 0; /* frame was duplicated, thus, delta is zero */
245         } else {
246             res = av_frame_make_writable(s->last_frame_av);
247             if (res) {
248                 av_frame_free(&in);
249                 return res;
250             }
251             blend_frame(ctx, s->last_frame_av, in, factor);
252 
253             convert_frame(ctx, s->last_frame_av, &ef, s->skip);
254             this_badness = get_badness(&ef, &s->last_frame_e);
255             fixed_badness = current_badness + this_badness;
256             av_log(s, AV_LOG_VERBOSE, "  fixed: %6d -> %6d / %6d (%3d%%) factor=%5.3f\n",
257                 current_badness, fixed_badness, s->badness_threshold,
258                 100 * new_badness / s->badness_threshold, factor);
259             s->last_frame_e = ef;
260             s->history[s->history_pos] = this_badness;
261         }
262         src = s->last_frame_av;
263         free_in = 1;
264     }
265     s->history_pos = (s->history_pos + 1) % s->nb_frames;
266 
267     out = ff_get_video_buffer(outlink, in->width, in->height);
268     if (!out) {
269         if (free_in == 1)
270             av_frame_free(&in);
271         return AVERROR(ENOMEM);
272     }
273     av_frame_copy_props(out, in);
274     metadata = &out->metadata;
275     if (metadata) {
276         char value[128];
277 
278         snprintf(value, sizeof(value), "%f", (float)new_badness / s->badness_threshold);
279         av_dict_set(metadata, "lavfi.photosensitivity.badness", value, 0);
280 
281         snprintf(value, sizeof(value), "%f", (float)fixed_badness / s->badness_threshold);
282         av_dict_set(metadata, "lavfi.photosensitivity.fixed-badness", value, 0);
283 
284         snprintf(value, sizeof(value), "%f", (float)this_badness / s->badness_threshold);
285         av_dict_set(metadata, "lavfi.photosensitivity.frame-badness", value, 0);
286 
287         snprintf(value, sizeof(value), "%f", factor);
288         av_dict_set(metadata, "lavfi.photosensitivity.factor", value, 0);
289     }
290     av_frame_copy(out, src);
291     if (free_in == 1)
292         av_frame_free(&in);
293     return ff_filter_frame(outlink, out);
294 }
295 
uninit(AVFilterContext * ctx)296 static av_cold void uninit(AVFilterContext *ctx)
297 {
298     PhotosensitivityContext *s = ctx->priv;
299 
300     av_frame_free(&s->last_frame_av);
301 }
302 
303 static const AVFilterPad inputs[] = {
304     {
305         .name         = "default",
306         .type         = AVMEDIA_TYPE_VIDEO,
307         .filter_frame = filter_frame,
308         .config_props = config_input,
309     },
310 };
311 
312 static const AVFilterPad outputs[] = {
313     {
314         .name          = "default",
315         .type          = AVMEDIA_TYPE_VIDEO,
316     },
317 };
318 
319 const AVFilter ff_vf_photosensitivity = {
320     .name          = "photosensitivity",
321     .description   = NULL_IF_CONFIG_SMALL("Filter out photosensitive epilepsy seizure-inducing flashes."),
322     .priv_size     = sizeof(PhotosensitivityContext),
323     .priv_class    = &photosensitivity_class,
324     .uninit        = uninit,
325     FILTER_INPUTS(inputs),
326     FILTER_OUTPUTS(outputs),
327     FILTER_PIXFMTS(AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24),
328 };
329