1 /*
2  * Copyright (c) 2011 Stefano Sabatini
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 /**
22  * @file
23  * filter for selecting which frame passes in the filterchain
24  */
25 
26 #include "config_components.h"
27 
28 #include "libavutil/avstring.h"
29 #include "libavutil/eval.h"
30 #include "libavutil/fifo.h"
31 #include "libavutil/imgutils.h"
32 #include "libavutil/internal.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/pixdesc.h"
35 #include "avfilter.h"
36 #include "audio.h"
37 #include "formats.h"
38 #include "internal.h"
39 #include "video.h"
40 #include "scene_sad.h"
41 
42 static const char *const var_names[] = {
43     "TB",                ///< timebase
44 
45     "pts",               ///< original pts in the file of the frame
46     "start_pts",         ///< first PTS in the stream, expressed in TB units
47     "prev_pts",          ///< previous frame PTS
48     "prev_selected_pts", ///< previous selected frame PTS
49 
50     "t",                 ///< timestamp expressed in seconds
51     "start_t",           ///< first PTS in the stream, expressed in seconds
52     "prev_t",            ///< previous frame time
53     "prev_selected_t",   ///< previously selected time
54 
55     "pict_type",         ///< the type of picture in the movie
56     "I",
57     "P",
58     "B",
59     "S",
60     "SI",
61     "SP",
62     "BI",
63     "PICT_TYPE_I",
64     "PICT_TYPE_P",
65     "PICT_TYPE_B",
66     "PICT_TYPE_S",
67     "PICT_TYPE_SI",
68     "PICT_TYPE_SP",
69     "PICT_TYPE_BI",
70 
71     "interlace_type",    ///< the frame interlace type
72     "PROGRESSIVE",
73     "TOPFIRST",
74     "BOTTOMFIRST",
75 
76     "consumed_samples_n",///< number of samples consumed by the filter (only audio)
77     "samples_n",         ///< number of samples in the current frame (only audio)
78     "sample_rate",       ///< sample rate (only audio)
79 
80     "n",                 ///< frame number (starting from zero)
81     "selected_n",        ///< selected frame number (starting from zero)
82     "prev_selected_n",   ///< number of the last selected frame
83 
84     "key",               ///< tell if the frame is a key frame
85     "pos",               ///< original position in the file of the frame
86 
87     "scene",
88 
89     "concatdec_select",  ///< frame is within the interval set by the concat demuxer
90 
91     NULL
92 };
93 
94 enum var_name {
95     VAR_TB,
96 
97     VAR_PTS,
98     VAR_START_PTS,
99     VAR_PREV_PTS,
100     VAR_PREV_SELECTED_PTS,
101 
102     VAR_T,
103     VAR_START_T,
104     VAR_PREV_T,
105     VAR_PREV_SELECTED_T,
106 
107     VAR_PICT_TYPE,
108     VAR_I,
109     VAR_P,
110     VAR_B,
111     VAR_S,
112     VAR_SI,
113     VAR_SP,
114     VAR_BI,
115     VAR_PICT_TYPE_I,
116     VAR_PICT_TYPE_P,
117     VAR_PICT_TYPE_B,
118     VAR_PICT_TYPE_S,
119     VAR_PICT_TYPE_SI,
120     VAR_PICT_TYPE_SP,
121     VAR_PICT_TYPE_BI,
122 
123     VAR_INTERLACE_TYPE,
124     VAR_INTERLACE_TYPE_P,
125     VAR_INTERLACE_TYPE_T,
126     VAR_INTERLACE_TYPE_B,
127 
128     VAR_CONSUMED_SAMPLES_N,
129     VAR_SAMPLES_N,
130     VAR_SAMPLE_RATE,
131 
132     VAR_N,
133     VAR_SELECTED_N,
134     VAR_PREV_SELECTED_N,
135 
136     VAR_KEY,
137     VAR_POS,
138 
139     VAR_SCENE,
140 
141     VAR_CONCATDEC_SELECT,
142 
143     VAR_VARS_NB
144 };
145 
146 typedef struct SelectContext {
147     const AVClass *class;
148     char *expr_str;
149     AVExpr *expr;
150     double var_values[VAR_VARS_NB];
151     int bitdepth;
152     int nb_planes;
153     ptrdiff_t width[4];
154     ptrdiff_t height[4];
155     int do_scene_detect;            ///< 1 if the expression requires scene detection variables, 0 otherwise
156     ff_scene_sad_fn sad;            ///< Sum of the absolute difference function (scene detect only)
157     double prev_mafd;               ///< previous MAFD                           (scene detect only)
158     AVFrame *prev_picref;           ///< previous frame                          (scene detect only)
159     double select;
160     int select_out;                 ///< mark the selected output pad index
161     int nb_outputs;
162 } SelectContext;
163 
164 #define OFFSET(x) offsetof(SelectContext, x)
165 #define DEFINE_OPTIONS(filt_name, FLAGS)                            \
166 static const AVOption filt_name##_options[] = {                     \
167     { "expr", "set an expression to use for selecting frames", OFFSET(expr_str), AV_OPT_TYPE_STRING, { .str = "1" }, .flags=FLAGS }, \
168     { "e",    "set an expression to use for selecting frames", OFFSET(expr_str), AV_OPT_TYPE_STRING, { .str = "1" }, .flags=FLAGS }, \
169     { "outputs", "set the number of outputs", OFFSET(nb_outputs), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, .flags=FLAGS }, \
170     { "n",       "set the number of outputs", OFFSET(nb_outputs), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, .flags=FLAGS }, \
171     { NULL }                                                            \
172 }
173 
174 static int request_frame(AVFilterLink *outlink);
175 
init(AVFilterContext *ctx)176 static av_cold int init(AVFilterContext *ctx)
177 {
178     SelectContext *select = ctx->priv;
179     int i, ret;
180 
181     if ((ret = av_expr_parse(&select->expr, select->expr_str,
182                              var_names, NULL, NULL, NULL, NULL, 0, ctx)) < 0) {
183         av_log(ctx, AV_LOG_ERROR, "Error while parsing expression '%s'\n",
184                select->expr_str);
185         return ret;
186     }
187     select->do_scene_detect = !!strstr(select->expr_str, "scene");
188 
189     for (i = 0; i < select->nb_outputs; i++) {
190         AVFilterPad pad = { 0 };
191 
192         pad.name = av_asprintf("output%d", i);
193         if (!pad.name)
194             return AVERROR(ENOMEM);
195         pad.type = ctx->filter->inputs[0].type;
196         pad.request_frame = request_frame;
197         if ((ret = ff_append_outpad_free_name(ctx, &pad)) < 0)
198             return ret;
199     }
200 
201     return 0;
202 }
203 
204 #define INTERLACE_TYPE_P 0
205 #define INTERLACE_TYPE_T 1
206 #define INTERLACE_TYPE_B 2
207 
config_input(AVFilterLink *inlink)208 static int config_input(AVFilterLink *inlink)
209 {
210     SelectContext *select = inlink->dst->priv;
211     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
212     int is_yuv = !(desc->flags & AV_PIX_FMT_FLAG_RGB) &&
213                  (desc->flags & AV_PIX_FMT_FLAG_PLANAR) &&
214                  desc->nb_components >= 3;
215 
216     select->bitdepth = desc->comp[0].depth;
217     select->nb_planes = is_yuv ? 1 : av_pix_fmt_count_planes(inlink->format);
218 
219     for (int plane = 0; plane < select->nb_planes; plane++) {
220         ptrdiff_t line_size = av_image_get_linesize(inlink->format, inlink->w, plane);
221         int vsub = desc->log2_chroma_h;
222 
223         select->width[plane] = line_size >> (select->bitdepth > 8);
224         select->height[plane] = plane == 1 || plane == 2 ?  AV_CEIL_RSHIFT(inlink->h, vsub) : inlink->h;
225     }
226 
227     select->var_values[VAR_N]          = 0.0;
228     select->var_values[VAR_SELECTED_N] = 0.0;
229 
230     select->var_values[VAR_TB] = av_q2d(inlink->time_base);
231 
232     select->var_values[VAR_PREV_PTS]          = NAN;
233     select->var_values[VAR_PREV_SELECTED_PTS] = NAN;
234     select->var_values[VAR_PREV_SELECTED_T]   = NAN;
235     select->var_values[VAR_PREV_T]            = NAN;
236     select->var_values[VAR_START_PTS]         = NAN;
237     select->var_values[VAR_START_T]           = NAN;
238 
239     select->var_values[VAR_I]  = AV_PICTURE_TYPE_I;
240     select->var_values[VAR_P]  = AV_PICTURE_TYPE_P;
241     select->var_values[VAR_B]  = AV_PICTURE_TYPE_B;
242     select->var_values[VAR_SI] = AV_PICTURE_TYPE_SI;
243     select->var_values[VAR_SP] = AV_PICTURE_TYPE_SP;
244     select->var_values[VAR_BI] = AV_PICTURE_TYPE_BI;
245     select->var_values[VAR_PICT_TYPE_I]  = AV_PICTURE_TYPE_I;
246     select->var_values[VAR_PICT_TYPE_P]  = AV_PICTURE_TYPE_P;
247     select->var_values[VAR_PICT_TYPE_B]  = AV_PICTURE_TYPE_B;
248     select->var_values[VAR_PICT_TYPE_SI] = AV_PICTURE_TYPE_SI;
249     select->var_values[VAR_PICT_TYPE_SP] = AV_PICTURE_TYPE_SP;
250     select->var_values[VAR_PICT_TYPE_BI] = AV_PICTURE_TYPE_BI;
251 
252     select->var_values[VAR_INTERLACE_TYPE_P] = INTERLACE_TYPE_P;
253     select->var_values[VAR_INTERLACE_TYPE_T] = INTERLACE_TYPE_T;
254     select->var_values[VAR_INTERLACE_TYPE_B] = INTERLACE_TYPE_B;
255 
256     select->var_values[VAR_PICT_TYPE]         = NAN;
257     select->var_values[VAR_INTERLACE_TYPE]    = NAN;
258     select->var_values[VAR_SCENE]             = NAN;
259     select->var_values[VAR_CONSUMED_SAMPLES_N] = NAN;
260     select->var_values[VAR_SAMPLES_N]          = NAN;
261 
262     select->var_values[VAR_SAMPLE_RATE] =
263         inlink->type == AVMEDIA_TYPE_AUDIO ? inlink->sample_rate : NAN;
264 
265     if (CONFIG_SELECT_FILTER && select->do_scene_detect) {
266         select->sad = ff_scene_sad_get_fn(select->bitdepth == 8 ? 8 : 16);
267         if (!select->sad)
268             return AVERROR(EINVAL);
269     }
270     return 0;
271 }
272 
get_scene_score(AVFilterContext *ctx, AVFrame *frame)273 static double get_scene_score(AVFilterContext *ctx, AVFrame *frame)
274 {
275     double ret = 0;
276     SelectContext *select = ctx->priv;
277     AVFrame *prev_picref = select->prev_picref;
278 
279     if (prev_picref &&
280         frame->height == prev_picref->height &&
281         frame->width  == prev_picref->width) {
282         uint64_t sad = 0;
283         double mafd, diff;
284         uint64_t count = 0;
285 
286         for (int plane = 0; plane < select->nb_planes; plane++) {
287             uint64_t plane_sad;
288             select->sad(prev_picref->data[plane], prev_picref->linesize[plane],
289                     frame->data[plane], frame->linesize[plane],
290                     select->width[plane], select->height[plane], &plane_sad);
291             sad += plane_sad;
292             count += select->width[plane] * select->height[plane];
293         }
294 
295         emms_c();
296         mafd = (double)sad / count / (1ULL << (select->bitdepth - 8));
297         diff = fabs(mafd - select->prev_mafd);
298         ret  = av_clipf(FFMIN(mafd, diff) / 100., 0, 1);
299         select->prev_mafd = mafd;
300         av_frame_free(&prev_picref);
301     }
302     select->prev_picref = av_frame_clone(frame);
303     return ret;
304 }
305 
get_concatdec_select(AVFrame *frame, int64_t pts)306 static double get_concatdec_select(AVFrame *frame, int64_t pts)
307 {
308     AVDictionary *metadata = frame->metadata;
309     AVDictionaryEntry *start_time_entry = av_dict_get(metadata, "lavf.concatdec.start_time", NULL, 0);
310     AVDictionaryEntry *duration_entry = av_dict_get(metadata, "lavf.concatdec.duration", NULL, 0);
311     if (start_time_entry) {
312         int64_t start_time = strtoll(start_time_entry->value, NULL, 10);
313         if (pts >= start_time) {
314             if (duration_entry) {
315               int64_t duration = strtoll(duration_entry->value, NULL, 10);
316               if (pts < start_time + duration)
317                   return -1;
318               else
319                   return 0;
320             }
321             return -1;
322         }
323         return 0;
324     }
325     return NAN;
326 }
327 
select_frame(AVFilterContext *ctx, AVFrame *frame)328 static void select_frame(AVFilterContext *ctx, AVFrame *frame)
329 {
330     SelectContext *select = ctx->priv;
331     AVFilterLink *inlink = ctx->inputs[0];
332     double res;
333 
334     if (isnan(select->var_values[VAR_START_PTS]))
335         select->var_values[VAR_START_PTS] = TS2D(frame->pts);
336     if (isnan(select->var_values[VAR_START_T]))
337         select->var_values[VAR_START_T] = TS2D(frame->pts) * av_q2d(inlink->time_base);
338 
339     select->var_values[VAR_N  ] = inlink->frame_count_out;
340     select->var_values[VAR_PTS] = TS2D(frame->pts);
341     select->var_values[VAR_T  ] = TS2D(frame->pts) * av_q2d(inlink->time_base);
342     select->var_values[VAR_POS] = frame->pkt_pos == -1 ? NAN : frame->pkt_pos;
343     select->var_values[VAR_KEY] = frame->key_frame;
344     select->var_values[VAR_CONCATDEC_SELECT] = get_concatdec_select(frame, av_rescale_q(frame->pts, inlink->time_base, AV_TIME_BASE_Q));
345 
346     switch (inlink->type) {
347     case AVMEDIA_TYPE_AUDIO:
348         select->var_values[VAR_SAMPLES_N] = frame->nb_samples;
349         break;
350 
351     case AVMEDIA_TYPE_VIDEO:
352         select->var_values[VAR_INTERLACE_TYPE] =
353             !frame->interlaced_frame ? INTERLACE_TYPE_P :
354         frame->top_field_first ? INTERLACE_TYPE_T : INTERLACE_TYPE_B;
355         select->var_values[VAR_PICT_TYPE] = frame->pict_type;
356         if (select->do_scene_detect) {
357             char buf[32];
358             select->var_values[VAR_SCENE] = get_scene_score(ctx, frame);
359             // TODO: document metadata
360             snprintf(buf, sizeof(buf), "%f", select->var_values[VAR_SCENE]);
361             av_dict_set(&frame->metadata, "lavfi.scene_score", buf, 0);
362         }
363         break;
364     }
365 
366     select->select = res = av_expr_eval(select->expr, select->var_values, NULL);
367     av_log(inlink->dst, AV_LOG_DEBUG,
368            "n:%f pts:%f t:%f key:%d",
369            select->var_values[VAR_N],
370            select->var_values[VAR_PTS],
371            select->var_values[VAR_T],
372            frame->key_frame);
373 
374     switch (inlink->type) {
375     case AVMEDIA_TYPE_VIDEO:
376         av_log(inlink->dst, AV_LOG_DEBUG, " interlace_type:%c pict_type:%c scene:%f",
377                (!frame->interlaced_frame) ? 'P' :
378                frame->top_field_first     ? 'T' : 'B',
379                av_get_picture_type_char(frame->pict_type),
380                select->var_values[VAR_SCENE]);
381         break;
382     case AVMEDIA_TYPE_AUDIO:
383         av_log(inlink->dst, AV_LOG_DEBUG, " samples_n:%d consumed_samples_n:%f",
384                frame->nb_samples,
385                select->var_values[VAR_CONSUMED_SAMPLES_N]);
386         break;
387     }
388 
389     if (res == 0) {
390         select->select_out = -1; /* drop */
391     } else if (isnan(res) || res < 0) {
392         select->select_out = 0; /* first output */
393     } else {
394         select->select_out = FFMIN(ceilf(res)-1, select->nb_outputs-1); /* other outputs */
395     }
396 
397     av_log(inlink->dst, AV_LOG_DEBUG, " -> select:%f select_out:%d\n", res, select->select_out);
398 
399     if (res) {
400         select->var_values[VAR_PREV_SELECTED_N]   = select->var_values[VAR_N];
401         select->var_values[VAR_PREV_SELECTED_PTS] = select->var_values[VAR_PTS];
402         select->var_values[VAR_PREV_SELECTED_T]   = select->var_values[VAR_T];
403         select->var_values[VAR_SELECTED_N] += 1.0;
404         if (inlink->type == AVMEDIA_TYPE_AUDIO)
405             select->var_values[VAR_CONSUMED_SAMPLES_N] += frame->nb_samples;
406     }
407 
408     select->var_values[VAR_PREV_PTS] = select->var_values[VAR_PTS];
409     select->var_values[VAR_PREV_T]   = select->var_values[VAR_T];
410 }
411 
filter_frame(AVFilterLink *inlink, AVFrame *frame)412 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
413 {
414     AVFilterContext *ctx = inlink->dst;
415     SelectContext *select = ctx->priv;
416 
417     select_frame(ctx, frame);
418     if (select->select)
419         return ff_filter_frame(ctx->outputs[select->select_out], frame);
420 
421     av_frame_free(&frame);
422     return 0;
423 }
424 
request_frame(AVFilterLink *outlink)425 static int request_frame(AVFilterLink *outlink)
426 {
427     AVFilterLink *inlink = outlink->src->inputs[0];
428     int ret = ff_request_frame(inlink);
429     return ret;
430 }
431 
uninit(AVFilterContext *ctx)432 static av_cold void uninit(AVFilterContext *ctx)
433 {
434     SelectContext *select = ctx->priv;
435 
436     av_expr_free(select->expr);
437     select->expr = NULL;
438 
439     if (select->do_scene_detect) {
440         av_frame_free(&select->prev_picref);
441     }
442 }
443 
444 #if CONFIG_ASELECT_FILTER
445 
446 DEFINE_OPTIONS(aselect, AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM);
447 AVFILTER_DEFINE_CLASS(aselect);
448 
aselect_init(AVFilterContext *ctx)449 static av_cold int aselect_init(AVFilterContext *ctx)
450 {
451     SelectContext *select = ctx->priv;
452     int ret;
453 
454     if ((ret = init(ctx)) < 0)
455         return ret;
456 
457     if (select->do_scene_detect) {
458         av_log(ctx, AV_LOG_ERROR, "Scene detection is ignored in aselect filter\n");
459         return AVERROR(EINVAL);
460     }
461 
462     return 0;
463 }
464 
465 static const AVFilterPad avfilter_af_aselect_inputs[] = {
466     {
467         .name         = "default",
468         .type         = AVMEDIA_TYPE_AUDIO,
469         .config_props = config_input,
470         .filter_frame = filter_frame,
471     },
472 };
473 
474 const AVFilter ff_af_aselect = {
475     .name        = "aselect",
476     .description = NULL_IF_CONFIG_SMALL("Select audio frames to pass in output."),
477     .init        = aselect_init,
478     .uninit      = uninit,
479     .priv_size   = sizeof(SelectContext),
480     FILTER_INPUTS(avfilter_af_aselect_inputs),
481     .priv_class  = &aselect_class,
482     .flags       = AVFILTER_FLAG_DYNAMIC_OUTPUTS,
483 };
484 #endif /* CONFIG_ASELECT_FILTER */
485 
486 #if CONFIG_SELECT_FILTER
487 
query_formats(AVFilterContext *ctx)488 static int query_formats(AVFilterContext *ctx)
489 {
490     SelectContext *select = ctx->priv;
491 
492     if (!select->do_scene_detect) {
493         return ff_default_query_formats(ctx);
494     } else {
495         static const enum AVPixelFormat pix_fmts[] = {
496             AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24, AV_PIX_FMT_RGBA,
497             AV_PIX_FMT_ABGR, AV_PIX_FMT_BGRA, AV_PIX_FMT_GRAY8,
498             AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVJ420P,
499             AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUVJ422P,
500             AV_PIX_FMT_YUV420P10,
501             AV_PIX_FMT_NONE
502         };
503         return ff_set_common_formats_from_list(ctx, pix_fmts);
504     }
505 }
506 
507 DEFINE_OPTIONS(select, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM);
508 AVFILTER_DEFINE_CLASS(select);
509 
select_init(AVFilterContext *ctx)510 static av_cold int select_init(AVFilterContext *ctx)
511 {
512     int ret;
513 
514     if ((ret = init(ctx)) < 0)
515         return ret;
516 
517     return 0;
518 }
519 
520 static const AVFilterPad avfilter_vf_select_inputs[] = {
521     {
522         .name         = "default",
523         .type         = AVMEDIA_TYPE_VIDEO,
524         .config_props = config_input,
525         .filter_frame = filter_frame,
526     },
527 };
528 
529 const AVFilter ff_vf_select = {
530     .name          = "select",
531     .description   = NULL_IF_CONFIG_SMALL("Select video frames to pass in output."),
532     .init          = select_init,
533     .uninit        = uninit,
534     .priv_size     = sizeof(SelectContext),
535     .priv_class    = &select_class,
536     FILTER_INPUTS(avfilter_vf_select_inputs),
537     FILTER_QUERY_FUNC(query_formats),
538     .flags         = AVFILTER_FLAG_DYNAMIC_OUTPUTS | AVFILTER_FLAG_METADATA_ONLY,
539 };
540 #endif /* CONFIG_SELECT_FILTER */
541