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