libavfilter/f_select.c
07586b68
 /*
  * Copyright (c) 2011 Stefano Sabatini
  *
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
  * FFmpeg is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with FFmpeg; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 /**
  * @file
  * filter for selecting which frame passes in the filterchain
  */
 
dcc1b323
 #include "libavutil/avstring.h"
07586b68
 #include "libavutil/eval.h"
 #include "libavutil/fifo.h"
1d9c2dc8
 #include "libavutil/internal.h"
6ba1f280
 #include "libavutil/opt.h"
07586b68
 #include "avfilter.h"
f5461fac
 #include "audio.h"
72868144
 #include "formats.h"
803391f7
 #include "internal.h"
c04c533f
 #include "video.h"
07586b68
 
2f39d7ff
 #if CONFIG_AVCODEC
 #include "libavcodec/dsputil.h"
 #endif
 
b0f29db5
 static const char *const var_names[] = {
07586b68
     "TB",                ///< timebase
 
     "pts",               ///< original pts in the file of the frame
     "start_pts",         ///< first PTS in the stream, expressed in TB units
     "prev_pts",          ///< previous frame PTS
     "prev_selected_pts", ///< previous selected frame PTS
 
     "t",                 ///< first PTS in seconds
     "start_t",           ///< first PTS in the stream, expressed in seconds
     "prev_t",            ///< previous frame time
     "prev_selected_t",   ///< previously selected time
 
     "pict_type",         ///< the type of picture in the movie
d763fb7d
     "I",
     "P",
     "B",
     "S",
     "SI",
     "SP",
     "BI",
91cae60e
     "PICT_TYPE_I",
     "PICT_TYPE_P",
     "PICT_TYPE_B",
     "PICT_TYPE_S",
     "PICT_TYPE_SI",
     "PICT_TYPE_SP",
     "PICT_TYPE_BI",
07586b68
 
     "interlace_type",    ///< the frame interlace type
d763fb7d
     "PROGRESSIVE",
     "TOPFIRST",
     "BOTTOMFIRST",
07586b68
 
f5461fac
     "consumed_samples_n",///< number of samples consumed by the filter (only audio)
     "samples_n",         ///< number of samples in the current frame (only audio)
     "sample_rate",       ///< sample rate (only audio)
 
07586b68
     "n",                 ///< frame number (starting from zero)
     "selected_n",        ///< selected frame number (starting from zero)
     "prev_selected_n",   ///< number of the last selected frame
 
     "key",               ///< tell if the frame is a key frame
     "pos",               ///< original position in the file of the frame
 
72868144
     "scene",
 
07586b68
     NULL
 };
 
 enum var_name {
     VAR_TB,
 
     VAR_PTS,
     VAR_START_PTS,
     VAR_PREV_PTS,
     VAR_PREV_SELECTED_PTS,
 
     VAR_T,
     VAR_START_T,
     VAR_PREV_T,
     VAR_PREV_SELECTED_T,
 
     VAR_PICT_TYPE,
91cae60e
     VAR_I,
     VAR_P,
     VAR_B,
     VAR_S,
     VAR_SI,
     VAR_SP,
     VAR_BI,
07586b68
     VAR_PICT_TYPE_I,
     VAR_PICT_TYPE_P,
     VAR_PICT_TYPE_B,
     VAR_PICT_TYPE_S,
     VAR_PICT_TYPE_SI,
     VAR_PICT_TYPE_SP,
     VAR_PICT_TYPE_BI,
 
     VAR_INTERLACE_TYPE,
     VAR_INTERLACE_TYPE_P,
     VAR_INTERLACE_TYPE_T,
     VAR_INTERLACE_TYPE_B,
 
f5461fac
     VAR_CONSUMED_SAMPLES_N,
     VAR_SAMPLES_N,
     VAR_SAMPLE_RATE,
 
07586b68
     VAR_N,
     VAR_SELECTED_N,
     VAR_PREV_SELECTED_N,
 
     VAR_KEY,
     VAR_POS,
 
72868144
     VAR_SCENE,
 
07586b68
     VAR_VARS_NB
 };
 
74a8dbe1
 typedef struct SelectContext {
6ba1f280
     const AVClass *class;
     char *expr_str;
b3fb2d8c
     AVExpr *expr;
07586b68
     double var_values[VAR_VARS_NB];
72868144
     int do_scene_detect;            ///< 1 if the expression requires scene detection variables, 0 otherwise
2f39d7ff
 #if CONFIG_AVCODEC
72868144
     AVCodecContext *avctx;          ///< codec context required for the DSPContext (scene detect only)
     DSPContext c;                   ///< context providing optimized SAD methods   (scene detect only)
     double prev_mafd;               ///< previous MAFD                             (scene detect only)
2f39d7ff
 #endif
a05a44e2
     AVFrame *prev_picref; ///< previous frame                            (scene detect only)
07586b68
     double select;
dcc1b323
     int select_out;                 ///< mark the selected output pad index
     int nb_outputs;
07586b68
 } SelectContext;
 
8bfd8781
 #define OFFSET(x) offsetof(SelectContext, x)
 #define DEFINE_OPTIONS(filt_name, FLAGS)                            \
 static const AVOption filt_name##_options[] = {                     \
     { "expr", "set an expression to use for selecting frames", OFFSET(expr_str), AV_OPT_TYPE_STRING, { .str = "1" }, .flags=FLAGS }, \
     { "e",    "set an expression to use for selecting frames", OFFSET(expr_str), AV_OPT_TYPE_STRING, { .str = "1" }, .flags=FLAGS }, \
     { "outputs", "set the number of outputs", OFFSET(nb_outputs), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, .flags=FLAGS }, \
     { "n",       "set the number of outputs", OFFSET(nb_outputs), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, .flags=FLAGS }, \
     { NULL }                                                            \
 }
 
dcc1b323
 static int request_frame(AVFilterLink *outlink);
6ba1f280
 
fd6228e6
 static av_cold int init(AVFilterContext *ctx)
07586b68
 {
     SelectContext *select = ctx->priv;
dcc1b323
     int i, ret;
07586b68
 
6ba1f280
     if ((ret = av_expr_parse(&select->expr, select->expr_str,
07586b68
                              var_names, NULL, NULL, NULL, NULL, 0, ctx)) < 0) {
b3fb2d8c
         av_log(ctx, AV_LOG_ERROR, "Error while parsing expression '%s'\n",
                select->expr_str);
07586b68
         return ret;
     }
6ba1f280
     select->do_scene_detect = !!strstr(select->expr_str, "scene");
07586b68
 
dcc1b323
     for (i = 0; i < select->nb_outputs; i++) {
         AVFilterPad pad = { 0 };
 
         pad.name = av_asprintf("output%d", i);
         if (!pad.name)
             return AVERROR(ENOMEM);
         pad.type = ctx->filter->inputs[0].type;
         pad.request_frame = request_frame;
         ff_insert_outpad(ctx, i, &pad);
     }
 
07586b68
     return 0;
 }
 
 #define INTERLACE_TYPE_P 0
 #define INTERLACE_TYPE_T 1
 #define INTERLACE_TYPE_B 2
 
 static int config_input(AVFilterLink *inlink)
 {
     SelectContext *select = inlink->dst->priv;
 
     select->var_values[VAR_N]          = 0.0;
     select->var_values[VAR_SELECTED_N] = 0.0;
 
     select->var_values[VAR_TB] = av_q2d(inlink->time_base);
 
     select->var_values[VAR_PREV_PTS]          = NAN;
     select->var_values[VAR_PREV_SELECTED_PTS] = NAN;
     select->var_values[VAR_PREV_SELECTED_T]   = NAN;
c0a4871c
     select->var_values[VAR_PREV_T]            = NAN;
07586b68
     select->var_values[VAR_START_PTS]         = NAN;
     select->var_values[VAR_START_T]           = NAN;
 
91cae60e
     select->var_values[VAR_I]  = AV_PICTURE_TYPE_I;
     select->var_values[VAR_P]  = AV_PICTURE_TYPE_P;
     select->var_values[VAR_B]  = AV_PICTURE_TYPE_B;
     select->var_values[VAR_SI] = AV_PICTURE_TYPE_SI;
     select->var_values[VAR_SP] = AV_PICTURE_TYPE_SP;
     select->var_values[VAR_BI] = AV_PICTURE_TYPE_BI;
07586b68
     select->var_values[VAR_PICT_TYPE_I]  = AV_PICTURE_TYPE_I;
     select->var_values[VAR_PICT_TYPE_P]  = AV_PICTURE_TYPE_P;
     select->var_values[VAR_PICT_TYPE_B]  = AV_PICTURE_TYPE_B;
     select->var_values[VAR_PICT_TYPE_SI] = AV_PICTURE_TYPE_SI;
     select->var_values[VAR_PICT_TYPE_SP] = AV_PICTURE_TYPE_SP;
4868855b
     select->var_values[VAR_PICT_TYPE_BI] = AV_PICTURE_TYPE_BI;
07586b68
 
     select->var_values[VAR_INTERLACE_TYPE_P] = INTERLACE_TYPE_P;
     select->var_values[VAR_INTERLACE_TYPE_T] = INTERLACE_TYPE_T;
4da45aff
     select->var_values[VAR_INTERLACE_TYPE_B] = INTERLACE_TYPE_B;
07586b68
 
43912625
     select->var_values[VAR_PICT_TYPE]         = NAN;
     select->var_values[VAR_INTERLACE_TYPE]    = NAN;
     select->var_values[VAR_SCENE]             = NAN;
     select->var_values[VAR_CONSUMED_SAMPLES_N] = NAN;
     select->var_values[VAR_SAMPLES_N]          = NAN;
 
f5461fac
     select->var_values[VAR_SAMPLE_RATE] =
         inlink->type == AVMEDIA_TYPE_AUDIO ? inlink->sample_rate : NAN;
 
174c483e
 #if CONFIG_AVCODEC
     if (select->do_scene_detect) {
72868144
         select->avctx = avcodec_alloc_context3(NULL);
         if (!select->avctx)
             return AVERROR(ENOMEM);
1e3104cd
         avpriv_dsputil_init(&select->c, select->avctx);
72868144
     }
174c483e
 #endif
07586b68
     return 0;
 }
 
2f39d7ff
 #if CONFIG_AVCODEC
a05a44e2
 static double get_scene_score(AVFilterContext *ctx, AVFrame *frame)
72868144
 {
     double ret = 0;
     SelectContext *select = ctx->priv;
a05a44e2
     AVFrame *prev_picref = select->prev_picref;
72868144
 
     if (prev_picref &&
a05a44e2
         frame->height    == prev_picref->height &&
         frame->width    == prev_picref->width &&
         frame->linesize[0] == prev_picref->linesize[0]) {
08526483
         int x, y, nb_sad = 0;
dff826b4
         int64_t sad = 0;
72868144
         double mafd, diff;
a05a44e2
         uint8_t *p1 =      frame->data[0];
72868144
         uint8_t *p2 = prev_picref->data[0];
a05a44e2
         const int linesize = frame->linesize[0];
72868144
 
a05a44e2
         for (y = 0; y < frame->height - 8; y += 8) {
             for (x = 0; x < frame->width*3 - 8; x += 8) {
6bd17412
                 sad += select->c.sad[1](NULL, p1 + x, p2 + x,
72868144
                                         linesize, 8);
08526483
                 nb_sad += 8 * 8;
             }
096d96ff
             p1 += 8 * linesize;
             p2 += 8 * linesize;
08526483
         }
72868144
         emms_c();
5a8ef3c6
         mafd = nb_sad ? (double)sad / nb_sad : 0;
13a7bd70
         diff = fabs(mafd - select->prev_mafd);
72868144
         ret  = av_clipf(FFMIN(mafd, diff) / 100., 0, 1);
         select->prev_mafd = mafd;
a05a44e2
         av_frame_free(&prev_picref);
72868144
     }
a05a44e2
     select->prev_picref = av_frame_clone(frame);
72868144
     return ret;
 }
2f39d7ff
 #endif
72868144
 
07586b68
 #define D2TS(d)  (isnan(d) ? AV_NOPTS_VALUE : (int64_t)(d))
 #define TS2D(ts) ((ts) == AV_NOPTS_VALUE ? NAN : (double)(ts))
 
565c50ac
 static void select_frame(AVFilterContext *ctx, AVFrame *frame)
07586b68
 {
     SelectContext *select = ctx->priv;
     AVFilterLink *inlink = ctx->inputs[0];
     double res;
 
     if (isnan(select->var_values[VAR_START_PTS]))
a05a44e2
         select->var_values[VAR_START_PTS] = TS2D(frame->pts);
298fccad
     if (isnan(select->var_values[VAR_START_T]))
a05a44e2
         select->var_values[VAR_START_T] = TS2D(frame->pts) * av_q2d(inlink->time_base);
07586b68
 
b8a5c761
     select->var_values[VAR_N  ] = inlink->frame_count;
a05a44e2
     select->var_values[VAR_PTS] = TS2D(frame->pts);
     select->var_values[VAR_T  ] = TS2D(frame->pts) * av_q2d(inlink->time_base);
     select->var_values[VAR_POS] = av_frame_get_pkt_pos(frame) == -1 ? NAN : av_frame_get_pkt_pos(frame);
07586b68
 
f5461fac
     switch (inlink->type) {
     case AVMEDIA_TYPE_AUDIO:
a05a44e2
         select->var_values[VAR_SAMPLES_N] = frame->nb_samples;
f5461fac
         break;
 
     case AVMEDIA_TYPE_VIDEO:
         select->var_values[VAR_INTERLACE_TYPE] =
a05a44e2
             !frame->interlaced_frame ? INTERLACE_TYPE_P :
         frame->top_field_first ? INTERLACE_TYPE_T : INTERLACE_TYPE_B;
         select->var_values[VAR_PICT_TYPE] = frame->pict_type;
174c483e
 #if CONFIG_AVCODEC
         if (select->do_scene_detect) {
f5461fac
             char buf[32];
a05a44e2
             select->var_values[VAR_SCENE] = get_scene_score(ctx, frame);
f5461fac
             // TODO: document metadata
             snprintf(buf, sizeof(buf), "%f", select->var_values[VAR_SCENE]);
865e20da
             av_dict_set(avpriv_frame_get_metadatap(frame), "lavfi.scene_score", buf, 0);
f5461fac
         }
174c483e
 #endif
f5461fac
         break;
     }
07586b68
 
565c50ac
     select->select = res = av_expr_eval(select->expr, select->var_values, NULL);
07586b68
     av_log(inlink->dst, AV_LOG_DEBUG,
a05a44e2
            "n:%f pts:%f t:%f key:%d",
872855e2
            select->var_values[VAR_N],
            select->var_values[VAR_PTS],
07586b68
            select->var_values[VAR_T],
f5461fac
            (int)select->var_values[VAR_KEY]);
 
     switch (inlink->type) {
     case AVMEDIA_TYPE_VIDEO:
43912625
         av_log(inlink->dst, AV_LOG_DEBUG, " interlace_type:%c pict_type:%c scene:%f",
f5461fac
                select->var_values[VAR_INTERLACE_TYPE] == INTERLACE_TYPE_P ? 'P' :
                select->var_values[VAR_INTERLACE_TYPE] == INTERLACE_TYPE_T ? 'T' :
                select->var_values[VAR_INTERLACE_TYPE] == INTERLACE_TYPE_B ? 'B' : '?',
43912625
                av_get_picture_type_char(select->var_values[VAR_PICT_TYPE]),
                select->var_values[VAR_SCENE]);
f5461fac
         break;
     case AVMEDIA_TYPE_AUDIO:
         av_log(inlink->dst, AV_LOG_DEBUG, " samples_n:%d consumed_samples_n:%d",
                (int)select->var_values[VAR_SAMPLES_N],
                (int)select->var_values[VAR_CONSUMED_SAMPLES_N]);
         break;
     }
07586b68
 
dcc1b323
     if (res == 0) {
         select->select_out = -1; /* drop */
     } else if (isnan(res) || res < 0) {
         select->select_out = 0; /* first output */
     } else {
         select->select_out = FFMIN(ceilf(res)-1, select->nb_outputs-1); /* other outputs */
     }
 
     av_log(inlink->dst, AV_LOG_DEBUG, " -> select:%f select_out:%d\n", res, select->select_out);
07586b68
 
     if (res) {
         select->var_values[VAR_PREV_SELECTED_N]   = select->var_values[VAR_N];
         select->var_values[VAR_PREV_SELECTED_PTS] = select->var_values[VAR_PTS];
         select->var_values[VAR_PREV_SELECTED_T]   = select->var_values[VAR_T];
         select->var_values[VAR_SELECTED_N] += 1.0;
f5461fac
         if (inlink->type == AVMEDIA_TYPE_AUDIO)
a05a44e2
             select->var_values[VAR_CONSUMED_SAMPLES_N] += frame->nb_samples;
07586b68
     }
f5461fac
 
c0a4871c
     select->var_values[VAR_PREV_PTS] = select->var_values[VAR_PTS];
     select->var_values[VAR_PREV_T]   = select->var_values[VAR_T];
07586b68
 }
 
a05a44e2
 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
07586b68
 {
dcc1b323
     AVFilterContext *ctx = inlink->dst;
     SelectContext *select = ctx->priv;
07586b68
 
dcc1b323
     select_frame(ctx, frame);
64c5fbd7
     if (select->select)
dcc1b323
         return ff_filter_frame(ctx->outputs[select->select_out], frame);
ebc8d974
 
a05a44e2
     av_frame_free(&frame);
d4f89906
     return 0;
07586b68
 }
 
 static int request_frame(AVFilterLink *outlink)
 {
     AVFilterContext *ctx = outlink->src;
     SelectContext *select = ctx->priv;
     AVFilterLink *inlink = outlink->src->inputs[0];
dcc1b323
     int out_no = FF_OUTLINK_IDX(outlink);
07586b68
 
64c5fbd7
     do {
803391f7
         int ret = ff_request_frame(inlink);
07586b68
         if (ret < 0)
             return ret;
dcc1b323
     } while (select->select_out != out_no);
07586b68
 
     return 0;
 }
 
 static av_cold void uninit(AVFilterContext *ctx)
 {
     SelectContext *select = ctx->priv;
dcc1b323
     int i;
07586b68
 
d763fb7d
     av_expr_free(select->expr);
07586b68
     select->expr = NULL;
 
dcc1b323
     for (i = 0; i < ctx->nb_outputs; i++)
         av_freep(&ctx->output_pads[i].name);
 
174c483e
 #if CONFIG_AVCODEC
72868144
     if (select->do_scene_detect) {
a05a44e2
         av_frame_free(&select->prev_picref);
b89c16e7
         if (select->avctx) {
             avcodec_close(select->avctx);
             av_freep(&select->avctx);
         }
72868144
     }
174c483e
 #endif
72868144
 }
 
 static int query_formats(AVFilterContext *ctx)
 {
     SelectContext *select = ctx->priv;
 
     if (!select->do_scene_detect) {
         return ff_default_query_formats(ctx);
     } else {
ac627b3d
         static const enum AVPixelFormat pix_fmts[] = {
             AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
             AV_PIX_FMT_NONE
72868144
         };
c9e183b4
         ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
72868144
     }
     return 0;
07586b68
 }
 
f5461fac
 #if CONFIG_ASELECT_FILTER
6ba1f280
 
8bfd8781
 DEFINE_OPTIONS(aselect, AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM);
6ba1f280
 AVFILTER_DEFINE_CLASS(aselect);
 
fd6228e6
 static av_cold int aselect_init(AVFilterContext *ctx)
6ba1f280
 {
     SelectContext *select = ctx->priv;
     int ret;
 
fd6228e6
     if ((ret = init(ctx)) < 0)
6ba1f280
         return ret;
 
     if (select->do_scene_detect) {
         av_log(ctx, AV_LOG_ERROR, "Scene detection is ignored in aselect filter\n");
         return AVERROR(EINVAL);
     }
 
     return 0;
 }
 
f5461fac
 static const AVFilterPad avfilter_af_aselect_inputs[] = {
     {
b211607b
         .name         = "default",
         .type         = AVMEDIA_TYPE_AUDIO,
         .config_props = config_input,
         .filter_frame = filter_frame,
f5461fac
     },
     { NULL }
 };
 
325f6e0a
 AVFilter ff_af_aselect = {
b211607b
     .name        = "aselect",
f5461fac
     .description = NULL_IF_CONFIG_SMALL("Select audio frames to pass in output."),
b211607b
     .init        = aselect_init,
     .uninit      = uninit,
     .priv_size   = sizeof(SelectContext),
     .inputs      = avfilter_af_aselect_inputs,
     .priv_class  = &aselect_class,
     .flags       = AVFILTER_FLAG_DYNAMIC_OUTPUTS,
f5461fac
 };
 #endif /* CONFIG_ASELECT_FILTER */
 
 #if CONFIG_SELECT_FILTER
6ba1f280
 
8bfd8781
 DEFINE_OPTIONS(select, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM);
6ba1f280
 AVFILTER_DEFINE_CLASS(select);
 
fd6228e6
 static av_cold int select_init(AVFilterContext *ctx)
6ba1f280
 {
     SelectContext *select = ctx->priv;
     int ret;
 
fd6228e6
     if ((ret = init(ctx)) < 0)
6ba1f280
         return ret;
 
     if (select->do_scene_detect && !CONFIG_AVCODEC) {
         av_log(ctx, AV_LOG_ERROR, "Scene detection is not available without libavcodec.\n");
         return AVERROR(EINVAL);
     }
 
     return 0;
 }
 
568c70e7
 static const AVFilterPad avfilter_vf_select_inputs[] = {
     {
b211607b
         .name         = "default",
         .type         = AVMEDIA_TYPE_VIDEO,
         .config_props = config_input,
         .filter_frame = filter_frame,
568c70e7
     },
     { NULL }
 };
 
325f6e0a
 AVFilter ff_vf_select = {
b211607b
     .name          = "select",
     .description   = NULL_IF_CONFIG_SMALL("Select video frames to pass in output."),
     .init          = select_init,
     .uninit        = uninit,
72868144
     .query_formats = query_formats,
b211607b
     .priv_size     = sizeof(SelectContext),
     .priv_class    = &select_class,
     .inputs        = avfilter_vf_select_inputs,
     .flags         = AVFILTER_FLAG_DYNAMIC_OUTPUTS,
07586b68
 };
f5461fac
 #endif /* CONFIG_SELECT_FILTER */