]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_select.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavfilter / vf_select.c
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 "libavutil/eval.h"
27 #include "libavutil/fifo.h"
28 #include "libavcodec/dsputil.h"
29 #include "libavutil/internal.h"
30 #include "avfilter.h"
31 #include "formats.h"
32 #include "internal.h"
33 #include "video.h"
34
35 static const char *const var_names[] = {
36     "TB",                ///< timebase
37
38     "pts",               ///< original pts in the file of the frame
39     "start_pts",         ///< first PTS in the stream, expressed in TB units
40     "prev_pts",          ///< previous frame PTS
41     "prev_selected_pts", ///< previous selected frame PTS
42
43     "t",                 ///< first PTS in seconds
44     "start_t",           ///< first PTS in the stream, expressed in seconds
45     "prev_t",            ///< previous frame time
46     "prev_selected_t",   ///< previously selected time
47
48     "pict_type",         ///< the type of picture in the movie
49     "I",
50     "P",
51     "B",
52     "S",
53     "SI",
54     "SP",
55     "BI",
56
57     "interlace_type",    ///< the frame interlace type
58     "PROGRESSIVE",
59     "TOPFIRST",
60     "BOTTOMFIRST",
61
62     "n",                 ///< frame number (starting from zero)
63     "selected_n",        ///< selected frame number (starting from zero)
64     "prev_selected_n",   ///< number of the last selected frame
65
66     "key",               ///< tell if the frame is a key frame
67     "pos",               ///< original position in the file of the frame
68
69     "scene",
70
71     NULL
72 };
73
74 enum var_name {
75     VAR_TB,
76
77     VAR_PTS,
78     VAR_START_PTS,
79     VAR_PREV_PTS,
80     VAR_PREV_SELECTED_PTS,
81
82     VAR_T,
83     VAR_START_T,
84     VAR_PREV_T,
85     VAR_PREV_SELECTED_T,
86
87     VAR_PICT_TYPE,
88     VAR_PICT_TYPE_I,
89     VAR_PICT_TYPE_P,
90     VAR_PICT_TYPE_B,
91     VAR_PICT_TYPE_S,
92     VAR_PICT_TYPE_SI,
93     VAR_PICT_TYPE_SP,
94     VAR_PICT_TYPE_BI,
95
96     VAR_INTERLACE_TYPE,
97     VAR_INTERLACE_TYPE_P,
98     VAR_INTERLACE_TYPE_T,
99     VAR_INTERLACE_TYPE_B,
100
101     VAR_N,
102     VAR_SELECTED_N,
103     VAR_PREV_SELECTED_N,
104
105     VAR_KEY,
106     VAR_POS,
107
108     VAR_SCENE,
109
110     VAR_VARS_NB
111 };
112
113 #define FIFO_SIZE 8
114
115 typedef struct {
116     AVExpr *expr;
117     double var_values[VAR_VARS_NB];
118     int do_scene_detect;            ///< 1 if the expression requires scene detection variables, 0 otherwise
119     AVCodecContext *avctx;          ///< codec context required for the DSPContext (scene detect only)
120     DSPContext c;                   ///< context providing optimized SAD methods   (scene detect only)
121     double prev_mafd;               ///< previous MAFD                             (scene detect only)
122     AVFilterBufferRef *prev_picref; ///< previous frame                            (scene detect only)
123     double select;
124     int cache_frames;
125     AVFifoBuffer *pending_frames; ///< FIFO buffer of video frames
126 } SelectContext;
127
128 static av_cold int init(AVFilterContext *ctx, const char *args)
129 {
130     SelectContext *select = ctx->priv;
131     int ret;
132
133     if ((ret = av_expr_parse(&select->expr, args ? args : "1",
134                              var_names, NULL, NULL, NULL, NULL, 0, ctx)) < 0) {
135         av_log(ctx, AV_LOG_ERROR, "Error while parsing expression '%s'\n", args);
136         return ret;
137     }
138
139     select->pending_frames = av_fifo_alloc(FIFO_SIZE*sizeof(AVFilterBufferRef*));
140     if (!select->pending_frames) {
141         av_log(ctx, AV_LOG_ERROR, "Failed to allocate pending frames buffer.\n");
142         return AVERROR(ENOMEM);
143     }
144
145     select->do_scene_detect = args && strstr(args, "scene");
146     return 0;
147 }
148
149 #define INTERLACE_TYPE_P 0
150 #define INTERLACE_TYPE_T 1
151 #define INTERLACE_TYPE_B 2
152
153 static int config_input(AVFilterLink *inlink)
154 {
155     SelectContext *select = inlink->dst->priv;
156
157     select->var_values[VAR_N]          = 0.0;
158     select->var_values[VAR_SELECTED_N] = 0.0;
159
160     select->var_values[VAR_TB] = av_q2d(inlink->time_base);
161
162     select->var_values[VAR_PREV_PTS]          = NAN;
163     select->var_values[VAR_PREV_SELECTED_PTS] = NAN;
164     select->var_values[VAR_PREV_SELECTED_T]   = NAN;
165     select->var_values[VAR_START_PTS]         = NAN;
166     select->var_values[VAR_START_T]           = NAN;
167
168     select->var_values[VAR_PICT_TYPE_I]  = AV_PICTURE_TYPE_I;
169     select->var_values[VAR_PICT_TYPE_P]  = AV_PICTURE_TYPE_P;
170     select->var_values[VAR_PICT_TYPE_B]  = AV_PICTURE_TYPE_B;
171     select->var_values[VAR_PICT_TYPE_SI] = AV_PICTURE_TYPE_SI;
172     select->var_values[VAR_PICT_TYPE_SP] = AV_PICTURE_TYPE_SP;
173
174     select->var_values[VAR_INTERLACE_TYPE_P] = INTERLACE_TYPE_P;
175     select->var_values[VAR_INTERLACE_TYPE_T] = INTERLACE_TYPE_T;
176     select->var_values[VAR_INTERLACE_TYPE_B] = INTERLACE_TYPE_B;
177
178     if (select->do_scene_detect) {
179         select->avctx = avcodec_alloc_context3(NULL);
180         if (!select->avctx)
181             return AVERROR(ENOMEM);
182         dsputil_init(&select->c, select->avctx);
183     }
184     return 0;
185 }
186
187 static double get_scene_score(AVFilterContext *ctx, AVFilterBufferRef *picref)
188 {
189     double ret = 0;
190     SelectContext *select = ctx->priv;
191     AVFilterBufferRef *prev_picref = select->prev_picref;
192
193     if (prev_picref &&
194         picref->video->h    == prev_picref->video->h &&
195         picref->video->w    == prev_picref->video->w &&
196         picref->linesize[0] == prev_picref->linesize[0]) {
197         int x, y;
198         int64_t sad;
199         double mafd, diff;
200         uint8_t *p1 =      picref->data[0];
201         uint8_t *p2 = prev_picref->data[0];
202         const int linesize = picref->linesize[0];
203
204         for (sad = y = 0; y < picref->video->h; y += 8)
205             for (x = 0; x < linesize; x += 8)
206                 sad += select->c.sad[1](select,
207                                         p1 + y * linesize + x,
208                                         p2 + y * linesize + x,
209                                         linesize, 8);
210         emms_c();
211         mafd = sad / (picref->video->h * picref->video->w * 3);
212         diff = fabs(mafd - select->prev_mafd);
213         ret  = av_clipf(FFMIN(mafd, diff) / 100., 0, 1);
214         select->prev_mafd = mafd;
215         avfilter_unref_buffer(prev_picref);
216     }
217     select->prev_picref = avfilter_ref_buffer(picref, ~0);
218     return ret;
219 }
220
221 #define D2TS(d)  (isnan(d) ? AV_NOPTS_VALUE : (int64_t)(d))
222 #define TS2D(ts) ((ts) == AV_NOPTS_VALUE ? NAN : (double)(ts))
223
224 static int select_frame(AVFilterContext *ctx, AVFilterBufferRef *picref)
225 {
226     SelectContext *select = ctx->priv;
227     AVFilterLink *inlink = ctx->inputs[0];
228     double res;
229
230     if (select->do_scene_detect)
231         select->var_values[VAR_SCENE] = get_scene_score(ctx, picref);
232     if (isnan(select->var_values[VAR_START_PTS]))
233         select->var_values[VAR_START_PTS] = TS2D(picref->pts);
234     if (isnan(select->var_values[VAR_START_T]))
235         select->var_values[VAR_START_T] = TS2D(picref->pts) * av_q2d(inlink->time_base);
236
237     select->var_values[VAR_PTS] = TS2D(picref->pts);
238     select->var_values[VAR_T  ] = TS2D(picref->pts) * av_q2d(inlink->time_base);
239     select->var_values[VAR_POS] = picref->pos == -1 ? NAN : picref->pos;
240     select->var_values[VAR_PREV_PTS] = TS2D(picref ->pts);
241
242     select->var_values[VAR_INTERLACE_TYPE] =
243         !picref->video->interlaced     ? INTERLACE_TYPE_P :
244         picref->video->top_field_first ? INTERLACE_TYPE_T : INTERLACE_TYPE_B;
245     select->var_values[VAR_PICT_TYPE] = picref->video->pict_type;
246
247     res = av_expr_eval(select->expr, select->var_values, NULL);
248     av_log(inlink->dst, AV_LOG_DEBUG,
249            "n:%d pts:%d t:%f pos:%d interlace_type:%c key:%d pict_type:%c "
250            "-> select:%f\n",
251            (int)select->var_values[VAR_N],
252            (int)select->var_values[VAR_PTS],
253            select->var_values[VAR_T],
254            (int)select->var_values[VAR_POS],
255            select->var_values[VAR_INTERLACE_TYPE] == INTERLACE_TYPE_P ? 'P' :
256            select->var_values[VAR_INTERLACE_TYPE] == INTERLACE_TYPE_T ? 'T' :
257            select->var_values[VAR_INTERLACE_TYPE] == INTERLACE_TYPE_B ? 'B' : '?',
258            (int)select->var_values[VAR_KEY],
259            av_get_picture_type_char(select->var_values[VAR_PICT_TYPE]),
260            res);
261
262     select->var_values[VAR_N] += 1.0;
263
264     if (res) {
265         select->var_values[VAR_PREV_SELECTED_N]   = select->var_values[VAR_N];
266         select->var_values[VAR_PREV_SELECTED_PTS] = select->var_values[VAR_PTS];
267         select->var_values[VAR_PREV_SELECTED_T]   = select->var_values[VAR_T];
268         select->var_values[VAR_SELECTED_N] += 1.0;
269     }
270     return res;
271 }
272
273 static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *picref)
274 {
275     SelectContext *select = inlink->dst->priv;
276
277     select->select = select_frame(inlink->dst, picref);
278     if (select->select) {
279         AVFilterBufferRef *buf_out;
280         /* frame was requested through poll_frame */
281         if (select->cache_frames) {
282             if (!av_fifo_space(select->pending_frames))
283                 av_log(inlink->dst, AV_LOG_ERROR,
284                        "Buffering limit reached, cannot cache more frames\n");
285             else
286                 av_fifo_generic_write(select->pending_frames, &picref,
287                                       sizeof(picref), NULL);
288             return 0;
289         }
290         buf_out = avfilter_ref_buffer(picref, ~0);
291         if (!buf_out)
292             return AVERROR(ENOMEM);
293         return ff_start_frame(inlink->dst->outputs[0], buf_out);
294     }
295
296     return 0;
297 }
298
299 static int draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
300 {
301     SelectContext *select = inlink->dst->priv;
302
303     if (select->select && !select->cache_frames)
304         return ff_draw_slice(inlink->dst->outputs[0], y, h, slice_dir);
305     return 0;
306 }
307
308 static int end_frame(AVFilterLink *inlink)
309 {
310     SelectContext *select = inlink->dst->priv;
311
312     if (select->select) {
313         if (select->cache_frames)
314             return 0;
315         return ff_end_frame(inlink->dst->outputs[0]);
316     }
317     return 0;
318 }
319
320 static int request_frame(AVFilterLink *outlink)
321 {
322     AVFilterContext *ctx = outlink->src;
323     SelectContext *select = ctx->priv;
324     AVFilterLink *inlink = outlink->src->inputs[0];
325     select->select = 0;
326
327     if (av_fifo_size(select->pending_frames)) {
328         AVFilterBufferRef *picref;
329         int ret;
330
331         av_fifo_generic_read(select->pending_frames, &picref, sizeof(picref), NULL);
332         if ((ret = ff_start_frame(outlink, picref)) < 0 ||
333             (ret = ff_draw_slice(outlink, 0, outlink->h, 1)) < 0 ||
334             (ret = ff_end_frame(outlink)) < 0);
335
336         return ret;
337     }
338
339     while (!select->select) {
340         int ret = ff_request_frame(inlink);
341         if (ret < 0)
342             return ret;
343     }
344
345     return 0;
346 }
347
348 static int poll_frame(AVFilterLink *outlink)
349 {
350     SelectContext *select = outlink->src->priv;
351     AVFilterLink *inlink = outlink->src->inputs[0];
352     int count, ret;
353
354     if (!av_fifo_size(select->pending_frames)) {
355         if ((count = ff_poll_frame(inlink)) <= 0)
356             return count;
357         /* request frame from input, and apply select condition to it */
358         select->cache_frames = 1;
359         while (count-- && av_fifo_space(select->pending_frames)) {
360             ret = ff_request_frame(inlink);
361             if (ret < 0)
362                 break;
363         }
364         select->cache_frames = 0;
365     }
366
367     return av_fifo_size(select->pending_frames)/sizeof(AVFilterBufferRef *);
368 }
369
370 static av_cold void uninit(AVFilterContext *ctx)
371 {
372     SelectContext *select = ctx->priv;
373     AVFilterBufferRef *picref;
374
375     av_expr_free(select->expr);
376     select->expr = NULL;
377
378     while (select->pending_frames &&
379            av_fifo_generic_read(select->pending_frames, &picref, sizeof(picref), NULL) == sizeof(picref))
380         avfilter_unref_buffer(picref);
381     av_fifo_free(select->pending_frames);
382     select->pending_frames = NULL;
383
384     if (select->do_scene_detect) {
385         avfilter_unref_bufferp(&select->prev_picref);
386         avcodec_close(select->avctx);
387         av_freep(&select->avctx);
388     }
389 }
390
391 static int query_formats(AVFilterContext *ctx)
392 {
393     SelectContext *select = ctx->priv;
394
395     if (!select->do_scene_detect) {
396         return ff_default_query_formats(ctx);
397     } else {
398         static const enum PixelFormat pix_fmts[] = {
399             PIX_FMT_RGB24, PIX_FMT_BGR24,
400             PIX_FMT_NONE
401         };
402         ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
403     }
404     return 0;
405 }
406
407 AVFilter avfilter_vf_select = {
408     .name      = "select",
409     .description = NULL_IF_CONFIG_SMALL("Select frames to pass in output."),
410     .init      = init,
411     .uninit    = uninit,
412     .query_formats = query_formats,
413
414     .priv_size = sizeof(SelectContext),
415
416     .inputs    = (const AVFilterPad[]) {{ .name             = "default",
417                                           .type             = AVMEDIA_TYPE_VIDEO,
418                                           .get_video_buffer = ff_null_get_video_buffer,
419                                           .min_perms        = AV_PERM_PRESERVE,
420                                           .config_props     = config_input,
421                                           .start_frame      = start_frame,
422                                           .draw_slice       = draw_slice,
423                                           .end_frame        = end_frame },
424                                         { .name = NULL }},
425     .outputs   = (const AVFilterPad[]) {{ .name             = "default",
426                                           .type             = AVMEDIA_TYPE_VIDEO,
427                                           .poll_frame       = poll_frame,
428                                           .request_frame    = request_frame, },
429                                         { .name = NULL}},
430 };