]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_fps.c
vf_fps: when reading EOF, using current_pts to duplicate the last frame if needed.
[ffmpeg] / libavfilter / vf_fps.c
1 /*
2  * Copyright 2007 Bobby Bingham
3  * Copyright 2012 Robert Nagy <ronag89 gmail com>
4  * Copyright 2012 Anton Khirnov <anton khirnov net>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * a filter enforcing given constant framerate
26  */
27
28 #include <float.h>
29 #include <stdint.h>
30
31 #include "libavutil/common.h"
32 #include "libavutil/fifo.h"
33 #include "libavutil/mathematics.h"
34 #include "libavutil/opt.h"
35 #include "libavutil/parseutils.h"
36
37 #define FF_INTERNAL_FIELDS 1
38 #include "framequeue.h"
39 #include "avfilter.h"
40 #include "internal.h"
41 #include "video.h"
42
43 typedef struct FPSContext {
44     const AVClass *class;
45
46     AVFifoBuffer *fifo;     ///< store frames until we get two successive timestamps
47
48     /* timestamps in input timebase */
49     int64_t first_pts;      ///< pts of the first frame that arrived on this filter
50
51     double start_time;      ///< pts, in seconds, of the expected first frame
52
53     AVRational framerate;   ///< target framerate
54     int rounding;           ///< AVRounding method for timestamps
55
56     /* statistics */
57     int frames_in;             ///< number of frames on input
58     int frames_out;            ///< number of frames on output
59     int dup;                   ///< number of frames duplicated
60     int drop;                  ///< number of framed dropped
61 } FPSContext;
62
63 #define OFFSET(x) offsetof(FPSContext, x)
64 #define V AV_OPT_FLAG_VIDEO_PARAM
65 #define F AV_OPT_FLAG_FILTERING_PARAM
66 static const AVOption fps_options[] = {
67     { "fps", "A string describing desired output framerate", OFFSET(framerate), AV_OPT_TYPE_VIDEO_RATE, { .str = "25" }, 0, INT_MAX, V|F },
68     { "start_time", "Assume the first PTS should be this value.", OFFSET(start_time), AV_OPT_TYPE_DOUBLE, { .dbl = DBL_MAX}, -DBL_MAX, DBL_MAX, V },
69     { "round", "set rounding method for timestamps", OFFSET(rounding), AV_OPT_TYPE_INT, { .i64 = AV_ROUND_NEAR_INF }, 0, 5, V|F, "round" },
70     { "zero", "round towards 0",      OFFSET(rounding), AV_OPT_TYPE_CONST, { .i64 = AV_ROUND_ZERO     }, 0, 5, V|F, "round" },
71     { "inf",  "round away from 0",    OFFSET(rounding), AV_OPT_TYPE_CONST, { .i64 = AV_ROUND_INF      }, 0, 5, V|F, "round" },
72     { "down", "round towards -infty", OFFSET(rounding), AV_OPT_TYPE_CONST, { .i64 = AV_ROUND_DOWN     }, 0, 5, V|F, "round" },
73     { "up",   "round towards +infty", OFFSET(rounding), AV_OPT_TYPE_CONST, { .i64 = AV_ROUND_UP       }, 0, 5, V|F, "round" },
74     { "near", "round to nearest",     OFFSET(rounding), AV_OPT_TYPE_CONST, { .i64 = AV_ROUND_NEAR_INF }, 0, 5, V|F, "round" },
75     { NULL }
76 };
77
78 AVFILTER_DEFINE_CLASS(fps);
79
80 static av_cold int init(AVFilterContext *ctx)
81 {
82     FPSContext *s = ctx->priv;
83
84     if (!(s->fifo = av_fifo_alloc_array(2, sizeof(AVFrame*))))
85         return AVERROR(ENOMEM);
86
87     s->first_pts    = AV_NOPTS_VALUE;
88
89     av_log(ctx, AV_LOG_VERBOSE, "fps=%d/%d\n", s->framerate.num, s->framerate.den);
90     return 0;
91 }
92
93 static void flush_fifo(AVFifoBuffer *fifo)
94 {
95     while (av_fifo_size(fifo)) {
96         AVFrame *tmp;
97         av_fifo_generic_read(fifo, &tmp, sizeof(tmp), NULL);
98         av_frame_free(&tmp);
99     }
100 }
101
102 static av_cold void uninit(AVFilterContext *ctx)
103 {
104     FPSContext *s = ctx->priv;
105     if (s->fifo) {
106         s->drop += av_fifo_size(s->fifo) / sizeof(AVFrame*);
107         flush_fifo(s->fifo);
108         av_fifo_freep(&s->fifo);
109     }
110
111     av_log(ctx, AV_LOG_VERBOSE, "%d frames in, %d frames out; %d frames dropped, "
112            "%d frames duplicated.\n", s->frames_in, s->frames_out, s->drop, s->dup);
113 }
114
115 static int config_props(AVFilterLink* link)
116 {
117     FPSContext   *s = link->src->priv;
118
119     link->time_base = av_inv_q(s->framerate);
120     link->frame_rate= s->framerate;
121     link->w         = link->src->inputs[0]->w;
122     link->h         = link->src->inputs[0]->h;
123
124     return 0;
125 }
126
127 static int request_frame(AVFilterLink *outlink)
128 {
129     AVFilterContext *ctx = outlink->src;
130     FPSContext        *s = ctx->priv;
131     int ret;
132
133     ret = ff_request_frame(ctx->inputs[0]);
134
135     /* flush the fifo */
136     if (ret == AVERROR_EOF && av_fifo_size(s->fifo)) {
137         int i;
138         for (i = 0; av_fifo_size(s->fifo); i++) {
139             AVFrame *buf;
140
141             av_fifo_generic_read(s->fifo, &buf, sizeof(buf), NULL);
142             if (av_fifo_size(s->fifo)) {
143                 buf->pts = av_rescale_q(s->first_pts, ctx->inputs[0]->time_base,
144                                         outlink->time_base) + s->frames_out;
145
146                 if ((ret = ff_filter_frame(outlink, buf)) < 0)
147                     return ret;
148
149                 s->frames_out++;
150             } else {
151                 /* This is the last frame, we may have to duplicate it to match
152                  * the last frame duration */
153                 int j;
154                 int delta = av_rescale_q_rnd(ctx->inputs[0]->current_pts - s->first_pts,
155                                              ctx->inputs[0]->time_base,
156                                              outlink->time_base, s->rounding) - s->frames_out ;
157                 /* if the delta is equal to 1, it means we just need to output
158                  * the last frame. Greater than 1 means we will need duplicate
159                  * delta-1 frames */
160                 if (delta > 0 ) {
161                     for (j = 0; j < delta; j++) {
162                         AVFrame *dup = av_frame_clone(buf);
163
164                         av_log(ctx, AV_LOG_DEBUG, "Duplicating frame.\n");
165                         dup->pts = av_rescale_q(s->first_pts, ctx->inputs[0]->time_base,
166                                                 outlink->time_base) + s->frames_out;
167
168                         if ((ret = ff_filter_frame(outlink, dup)) < 0)
169                             return ret;
170
171                         s->frames_out++;
172                         if (j > 0) s->dup++;
173                     }
174                 } else {
175                     /* for delta less or equal to 0, we should drop the frame,
176                      * otherwise, we will have one or more extra frames */
177                     av_frame_free(&buf);
178                     s->drop++;
179                 }
180             }
181         }
182         return 0;
183     }
184
185     return ret;
186 }
187
188 static int write_to_fifo(AVFifoBuffer *fifo, AVFrame *buf)
189 {
190     int ret;
191
192     if (!av_fifo_space(fifo) &&
193         (ret = av_fifo_realloc2(fifo, 2*av_fifo_size(fifo)))) {
194         av_frame_free(&buf);
195         return ret;
196     }
197
198     av_fifo_generic_write(fifo, &buf, sizeof(buf), NULL);
199     return 0;
200 }
201
202 static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
203 {
204     AVFilterContext    *ctx = inlink->dst;
205     FPSContext           *s = ctx->priv;
206     AVFilterLink   *outlink = ctx->outputs[0];
207     int64_t delta;
208     int i, ret;
209
210     s->frames_in++;
211     /* discard frames until we get the first timestamp */
212     if (s->first_pts == AV_NOPTS_VALUE) {
213         if (buf->pts != AV_NOPTS_VALUE) {
214             ret = write_to_fifo(s->fifo, buf);
215             if (ret < 0)
216                 return ret;
217
218             if (s->start_time != DBL_MAX && s->start_time != AV_NOPTS_VALUE) {
219                 double first_pts = s->start_time * AV_TIME_BASE;
220                 first_pts = FFMIN(FFMAX(first_pts, INT64_MIN), INT64_MAX);
221                 s->first_pts = av_rescale_q(first_pts, AV_TIME_BASE_Q,
222                                                      inlink->time_base);
223                 av_log(ctx, AV_LOG_VERBOSE, "Set first pts to (in:%"PRId64" out:%"PRId64")\n",
224                        s->first_pts, av_rescale_q(first_pts, AV_TIME_BASE_Q,
225                                                   outlink->time_base));
226             } else {
227                 s->first_pts = buf->pts;
228             }
229         } else {
230             av_log(ctx, AV_LOG_WARNING, "Discarding initial frame(s) with no "
231                    "timestamp.\n");
232             av_frame_free(&buf);
233             s->drop++;
234         }
235         return 0;
236     }
237
238     /* now wait for the next timestamp */
239     if (buf->pts == AV_NOPTS_VALUE || av_fifo_size(s->fifo) <= 0) {
240         return write_to_fifo(s->fifo, buf);
241     }
242
243     /* number of output frames */
244     delta = av_rescale_q_rnd(buf->pts - s->first_pts, inlink->time_base,
245                              outlink->time_base, s->rounding) - s->frames_out ;
246
247     if (delta < 1) {
248         /* drop everything buffered except the last */
249         int drop = av_fifo_size(s->fifo)/sizeof(AVFrame*);
250
251         av_log(ctx, AV_LOG_DEBUG, "Dropping %d frame(s).\n", drop);
252         s->drop += drop;
253
254         flush_fifo(s->fifo);
255         ret = write_to_fifo(s->fifo, buf);
256
257         return ret;
258     }
259
260     /* can output >= 1 frames */
261     for (i = 0; i < delta; i++) {
262         AVFrame *buf_out;
263         av_fifo_generic_read(s->fifo, &buf_out, sizeof(buf_out), NULL);
264
265         /* duplicate the frame if needed */
266         if (!av_fifo_size(s->fifo) && i < delta - 1) {
267             AVFrame *dup = av_frame_clone(buf_out);
268
269             av_log(ctx, AV_LOG_DEBUG, "Duplicating frame.\n");
270             if (dup)
271                 ret = write_to_fifo(s->fifo, dup);
272             else
273                 ret = AVERROR(ENOMEM);
274
275             if (ret < 0) {
276                 av_frame_free(&buf_out);
277                 av_frame_free(&buf);
278                 return ret;
279             }
280
281             s->dup++;
282         }
283
284         buf_out->pts = av_rescale_q(s->first_pts, inlink->time_base,
285                                     outlink->time_base) + s->frames_out;
286
287         if ((ret = ff_filter_frame(outlink, buf_out)) < 0) {
288             av_frame_free(&buf);
289             return ret;
290         }
291
292         s->frames_out++;
293     }
294     flush_fifo(s->fifo);
295
296     ret = write_to_fifo(s->fifo, buf);
297
298     return ret;
299 }
300
301 static const AVFilterPad avfilter_vf_fps_inputs[] = {
302     {
303         .name         = "default",
304         .type         = AVMEDIA_TYPE_VIDEO,
305         .filter_frame = filter_frame,
306     },
307     { NULL }
308 };
309
310 static const AVFilterPad avfilter_vf_fps_outputs[] = {
311     {
312         .name          = "default",
313         .type          = AVMEDIA_TYPE_VIDEO,
314         .request_frame = request_frame,
315         .config_props  = config_props
316     },
317     { NULL }
318 };
319
320 AVFilter ff_vf_fps = {
321     .name        = "fps",
322     .description = NULL_IF_CONFIG_SMALL("Force constant framerate."),
323     .init        = init,
324     .uninit      = uninit,
325     .priv_size   = sizeof(FPSContext),
326     .priv_class  = &fps_class,
327     .inputs      = avfilter_vf_fps_inputs,
328     .outputs     = avfilter_vf_fps_outputs,
329 };