]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_framerate.c
It has been replaced by C11 stdatomic.h and is now unused.
[ffmpeg] / libavfilter / vf_framerate.c
1 /*
2  * Copyright (C) 2012 Mark Himsley
3  *
4  * get_scene_score() Copyright (c) 2011 Stefano Sabatini
5  * taken from libavfilter/vf_select.c
6  *
7  * This file is part of FFmpeg.
8  *
9  * FFmpeg is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * FFmpeg is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with FFmpeg; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 /**
25  * @file
26  * filter for upsampling or downsampling a progressive source
27  */
28
29 #define DEBUG
30
31 #include "libavutil/avassert.h"
32 #include "libavutil/imgutils.h"
33 #include "libavutil/internal.h"
34 #include "libavutil/opt.h"
35 #include "libavutil/pixdesc.h"
36 #include "libavutil/pixelutils.h"
37
38 #include "avfilter.h"
39 #include "internal.h"
40 #include "video.h"
41
42 #define N_SRCE 3
43
44 typedef struct FrameRateContext {
45     const AVClass *class;
46     // parameters
47     AVRational dest_frame_rate;         ///< output frames per second
48     int flags;                          ///< flags affecting frame rate conversion algorithm
49     double scene_score;                 ///< score that denotes a scene change has happened
50     int interp_start;                   ///< start of range to apply linear interpolation (same bitdepth as input)
51     int interp_end;                     ///< end of range to apply linear interpolation (same bitdepth as input)
52     int interp_start_param;             ///< start of range to apply linear interpolation
53     int interp_end_param;               ///< end of range to apply linear interpolation
54
55     int line_size[4];                   ///< bytes of pixel data per line for each plane
56     int vsub;
57
58     int frst, next, prev, crnt, last;
59     int pending_srce_frames;            ///< how many input frames are still waiting to be processed
60     int flush;                          ///< are we flushing final frames
61     int pending_end_frame;              ///< flag indicating we are waiting to call filter_frame()
62
63     AVRational srce_time_base;          ///< timebase of source
64
65     AVRational dest_time_base;          ///< timebase of destination
66     int32_t dest_frame_num;
67     int64_t last_dest_frame_pts;        ///< pts of the last frame output
68     int64_t average_srce_pts_dest_delta;///< average input pts delta converted from input rate to output rate
69     int64_t average_dest_pts_delta;     ///< calculated average output pts delta
70
71     av_pixelutils_sad_fn sad;           ///< Sum of the absolute difference function (scene detect only)
72     double prev_mafd;                   ///< previous MAFD                           (scene detect only)
73
74     AVFrame *srce[N_SRCE];              ///< buffered source frames
75     int64_t srce_pts_dest[N_SRCE];      ///< pts for source frames scaled to output timebase
76     double srce_score[N_SRCE];          ///< scene change score compared to the next srce frame
77     int64_t pts;                        ///< pts of frame we are working on
78
79     int max;
80     int bitdepth;
81     AVFrame *work;
82 } FrameRateContext;
83
84 #define OFFSET(x) offsetof(FrameRateContext, x)
85 #define V AV_OPT_FLAG_VIDEO_PARAM
86 #define F AV_OPT_FLAG_FILTERING_PARAM
87 #define FRAMERATE_FLAG_SCD 01
88
89 static const AVOption framerate_options[] = {
90     {"fps",                 "required output frames per second rate", OFFSET(dest_frame_rate), AV_OPT_TYPE_VIDEO_RATE, {.str="50"},             0,       INT_MAX, V|F },
91
92     {"interp_start",        "point to start linear interpolation",    OFFSET(interp_start_param),AV_OPT_TYPE_INT,    {.i64=15},                 0,       255,     V|F },
93     {"interp_end",          "point to end linear interpolation",      OFFSET(interp_end_param),  AV_OPT_TYPE_INT,    {.i64=240},                0,       255,     V|F },
94     {"scene",               "scene change level",                     OFFSET(scene_score),     AV_OPT_TYPE_DOUBLE,   {.dbl=8.2},                0,       INT_MAX, V|F },
95
96     {"flags",               "set flags",                              OFFSET(flags),           AV_OPT_TYPE_FLAGS,    {.i64=1},                  0,       INT_MAX, V|F, "flags" },
97     {"scene_change_detect", "enable scene change detection",          0,                       AV_OPT_TYPE_CONST,    {.i64=FRAMERATE_FLAG_SCD}, INT_MIN, INT_MAX, V|F, "flags" },
98     {"scd",                 "enable scene change detection",          0,                       AV_OPT_TYPE_CONST,    {.i64=FRAMERATE_FLAG_SCD}, INT_MIN, INT_MAX, V|F, "flags" },
99
100     {NULL}
101 };
102
103 AVFILTER_DEFINE_CLASS(framerate);
104
105 static void next_source(AVFilterContext *ctx)
106 {
107     FrameRateContext *s = ctx->priv;
108     int i;
109
110     ff_dlog(ctx,  "next_source()\n");
111
112     if (s->srce[s->last] && s->srce[s->last] != s->srce[s->last-1]) {
113         ff_dlog(ctx, "next_source() unlink %d\n", s->last);
114         av_frame_free(&s->srce[s->last]);
115     }
116     for (i = s->last; i > s->frst; i--) {
117         ff_dlog(ctx, "next_source() copy %d to %d\n", i - 1, i);
118         s->srce[i] = s->srce[i - 1];
119         s->srce_score[i] = s->srce_score[i - 1];
120     }
121     ff_dlog(ctx, "next_source() make %d null\n", s->frst);
122     s->srce[s->frst] = NULL;
123     s->srce_score[s->frst] = -1.0;
124 }
125
126 static av_always_inline int64_t sad_8x8_16(const uint16_t *src1, ptrdiff_t stride1,
127                                            const uint16_t *src2, ptrdiff_t stride2)
128 {
129     int sum = 0;
130     int x, y;
131
132     for (y = 0; y < 8; y++) {
133         for (x = 0; x < 8; x++)
134             sum += FFABS(src1[x] - src2[x]);
135         src1 += stride1;
136         src2 += stride2;
137     }
138     return sum;
139 }
140
141 static int64_t scene_sad16(FrameRateContext *s, const uint16_t *p1, int p1_linesize, const uint16_t* p2, int p2_linesize, const int width, const int height)
142 {
143     int64_t sad;
144     int x, y;
145     for (sad = y = 0; y < height - 7; y += 8) {
146         for (x = 0; x < width - 7; x += 8) {
147             sad += sad_8x8_16(p1 + y * p1_linesize + x,
148                               p1_linesize,
149                               p2 + y * p2_linesize + x,
150                               p2_linesize);
151         }
152     }
153     return sad;
154 }
155
156 static int64_t scene_sad8(FrameRateContext *s, uint8_t *p1, int p1_linesize, uint8_t* p2, int p2_linesize, const int width, const int height)
157 {
158     int64_t sad;
159     int x, y;
160     for (sad = y = 0; y < height - 7; y += 8) {
161         for (x = 0; x < width - 7; x += 8) {
162             sad += s->sad(p1 + y * p1_linesize + x,
163                           p1_linesize,
164                           p2 + y * p2_linesize + x,
165                           p2_linesize);
166         }
167     }
168     emms_c();
169     return sad;
170 }
171
172 static double get_scene_score(AVFilterContext *ctx, AVFrame *crnt, AVFrame *next)
173 {
174     FrameRateContext *s = ctx->priv;
175     double ret = 0;
176
177     ff_dlog(ctx, "get_scene_score()\n");
178
179     if (crnt->height == next->height &&
180         crnt->width  == next->width) {
181         int64_t sad;
182         double mafd, diff;
183
184         ff_dlog(ctx, "get_scene_score() process\n");
185         if (s->bitdepth == 8)
186             sad = scene_sad8(s, crnt->data[0], crnt->linesize[0], next->data[0], next->linesize[0], crnt->width, crnt->height);
187         else
188             sad = scene_sad16(s, (const uint16_t*)crnt->data[0], crnt->linesize[0] / 2, (const uint16_t*)next->data[0], next->linesize[0] / 2, crnt->width, crnt->height);
189
190         mafd = (double)sad * 100.0 / FFMAX(1, (crnt->height & ~7) * (crnt->width & ~7)) / (1 << s->bitdepth);
191         diff = fabs(mafd - s->prev_mafd);
192         ret  = av_clipf(FFMIN(mafd, diff), 0, 100.0);
193         s->prev_mafd = mafd;
194     }
195     ff_dlog(ctx, "get_scene_score() result is:%f\n", ret);
196     return ret;
197 }
198
199 typedef struct ThreadData {
200     AVFrame *copy_src1, *copy_src2;
201     uint16_t src1_factor, src2_factor;
202 } ThreadData;
203
204 static int filter_slice8(AVFilterContext *ctx, void *arg, int job, int nb_jobs)
205 {
206     FrameRateContext *s = ctx->priv;
207     ThreadData *td = arg;
208     uint16_t src1_factor = td->src1_factor;
209     uint16_t src2_factor = td->src2_factor;
210     int plane, line, pixel;
211
212     for (plane = 0; plane < 4 && td->copy_src1->data[plane] && td->copy_src2->data[plane]; plane++) {
213         int cpy_line_width = s->line_size[plane];
214         uint8_t *cpy_src1_data = td->copy_src1->data[plane];
215         int cpy_src1_line_size = td->copy_src1->linesize[plane];
216         uint8_t *cpy_src2_data = td->copy_src2->data[plane];
217         int cpy_src2_line_size = td->copy_src2->linesize[plane];
218         int cpy_src_h = (plane > 0 && plane < 3) ? (td->copy_src1->height >> s->vsub) : (td->copy_src1->height);
219         uint8_t *cpy_dst_data = s->work->data[plane];
220         int cpy_dst_line_size = s->work->linesize[plane];
221         const int start = (cpy_src_h *  job   ) / nb_jobs;
222         const int end   = (cpy_src_h * (job+1)) / nb_jobs;
223         cpy_src1_data += start * cpy_src1_line_size;
224         cpy_src2_data += start * cpy_src2_line_size;
225         cpy_dst_data += start * cpy_dst_line_size;
226
227         if (plane <1 || plane >2) {
228             // luma or alpha
229             for (line = start; line < end; line++) {
230                 for (pixel = 0; pixel < cpy_line_width; pixel++) {
231                     // integer version of (src1 * src1_factor) + (src2 + src2_factor) + 0.5
232                     // 0.5 is for rounding
233                     // 128 is the integer representation of 0.5 << 8
234                     cpy_dst_data[pixel] = ((cpy_src1_data[pixel] * src1_factor) + (cpy_src2_data[pixel] * src2_factor) + 128) >> 8;
235                 }
236                 cpy_src1_data += cpy_src1_line_size;
237                 cpy_src2_data += cpy_src2_line_size;
238                 cpy_dst_data += cpy_dst_line_size;
239             }
240         } else {
241             // chroma
242             for (line = start; line < end; line++) {
243                 for (pixel = 0; pixel < cpy_line_width; pixel++) {
244                     // as above
245                     // because U and V are based around 128 we have to subtract 128 from the components.
246                     // 32896 is the integer representation of 128.5 << 8
247                     cpy_dst_data[pixel] = (((cpy_src1_data[pixel] - 128) * src1_factor) + ((cpy_src2_data[pixel] - 128) * src2_factor) + 32896) >> 8;
248                 }
249                 cpy_src1_data += cpy_src1_line_size;
250                 cpy_src2_data += cpy_src2_line_size;
251                 cpy_dst_data += cpy_dst_line_size;
252             }
253         }
254     }
255
256     return 0;
257 }
258
259 static int filter_slice16(AVFilterContext *ctx, void *arg, int job, int nb_jobs)
260 {
261     FrameRateContext *s = ctx->priv;
262     ThreadData *td = arg;
263     uint16_t src1_factor = td->src1_factor;
264     uint16_t src2_factor = td->src2_factor;
265     const int half = s->max / 2;
266     const int uv = (s->max + 1) * half;
267     const int shift = s->bitdepth;
268     int plane, line, pixel;
269
270     for (plane = 0; plane < 4 && td->copy_src1->data[plane] && td->copy_src2->data[plane]; plane++) {
271         int cpy_line_width = s->line_size[plane];
272         const uint16_t *cpy_src1_data = (const uint16_t *)td->copy_src1->data[plane];
273         int cpy_src1_line_size = td->copy_src1->linesize[plane] / 2;
274         const uint16_t *cpy_src2_data = (const uint16_t *)td->copy_src2->data[plane];
275         int cpy_src2_line_size = td->copy_src2->linesize[plane] / 2;
276         int cpy_src_h = (plane > 0 && plane < 3) ? (td->copy_src1->height >> s->vsub) : (td->copy_src1->height);
277         uint16_t *cpy_dst_data = (uint16_t *)s->work->data[plane];
278         int cpy_dst_line_size = s->work->linesize[plane] / 2;
279         const int start = (cpy_src_h *  job   ) / nb_jobs;
280         const int end   = (cpy_src_h * (job+1)) / nb_jobs;
281         cpy_src1_data += start * cpy_src1_line_size;
282         cpy_src2_data += start * cpy_src2_line_size;
283         cpy_dst_data += start * cpy_dst_line_size;
284
285         if (plane <1 || plane >2) {
286             // luma or alpha
287             for (line = start; line < end; line++) {
288                 for (pixel = 0; pixel < cpy_line_width; pixel++)
289                     cpy_dst_data[pixel] = ((cpy_src1_data[pixel] * src1_factor) + (cpy_src2_data[pixel] * src2_factor) + half) >> shift;
290                 cpy_src1_data += cpy_src1_line_size;
291                 cpy_src2_data += cpy_src2_line_size;
292                 cpy_dst_data += cpy_dst_line_size;
293             }
294         } else {
295             // chroma
296             for (line = start; line < end; line++) {
297                 for (pixel = 0; pixel < cpy_line_width; pixel++) {
298                     cpy_dst_data[pixel] = (((cpy_src1_data[pixel] - half) * src1_factor) + ((cpy_src2_data[pixel] - half) * src2_factor) + uv) >> shift;
299                 }
300                 cpy_src1_data += cpy_src1_line_size;
301                 cpy_src2_data += cpy_src2_line_size;
302                 cpy_dst_data += cpy_dst_line_size;
303             }
304         }
305     }
306
307     return 0;
308 }
309
310 static int blend_frames(AVFilterContext *ctx, int interpolate,
311                         int src1, int src2)
312 {
313     FrameRateContext *s = ctx->priv;
314     AVFilterLink *outlink = ctx->outputs[0];
315     double interpolate_scene_score = 0;
316
317     if ((s->flags & FRAMERATE_FLAG_SCD) && s->srce[src1] && s->srce[src2]) {
318         int i1 = src1 < src2 ? src1 : src2;
319         int i2 = src1 < src2 ? src2 : src1;
320         if (i2 == i1 + 1 && s->srce_score[i1] >= 0.0)
321             interpolate_scene_score = s->srce_score[i1];
322         else
323             interpolate_scene_score = s->srce_score[i1] = get_scene_score(ctx, s->srce[i1], s->srce[i2]);
324         ff_dlog(ctx, "blend_frames() interpolate scene score:%f\n", interpolate_scene_score);
325     }
326     // decide if the shot-change detection allows us to blend two frames
327     if (interpolate_scene_score < s->scene_score && s->srce[src2]) {
328         ThreadData td;
329         td.copy_src1 = s->srce[src1];
330         td.copy_src2 = s->srce[src2];
331         td.src2_factor = FFABS(interpolate);
332         td.src1_factor = s->max - td.src2_factor;
333
334         // get work-space for output frame
335         s->work = ff_get_video_buffer(outlink, outlink->w, outlink->h);
336         if (!s->work)
337             return AVERROR(ENOMEM);
338
339         av_frame_copy_props(s->work, s->srce[s->crnt]);
340
341         ff_dlog(ctx, "blend_frames() INTERPOLATE to create work frame\n");
342         ctx->internal->execute(ctx, s->bitdepth == 8 ? filter_slice8 : filter_slice16, &td, NULL, FFMIN(outlink->h, ff_filter_get_nb_threads(ctx)));
343         return 1;
344     }
345     return 0;
346 }
347
348 static int process_work_frame(AVFilterContext *ctx, int stop)
349 {
350     FrameRateContext *s = ctx->priv;
351     int64_t work_next_pts;
352     int interpolate;
353     int src1, src2;
354
355     ff_dlog(ctx, "process_work_frame()\n");
356
357     ff_dlog(ctx, "process_work_frame() pending_input_frames %d\n", s->pending_srce_frames);
358
359     if (s->srce[s->prev]) ff_dlog(ctx, "process_work_frame() srce prev pts:%"PRId64"\n", s->srce[s->prev]->pts);
360     if (s->srce[s->crnt]) ff_dlog(ctx, "process_work_frame() srce crnt pts:%"PRId64"\n", s->srce[s->crnt]->pts);
361     if (s->srce[s->next]) ff_dlog(ctx, "process_work_frame() srce next pts:%"PRId64"\n", s->srce[s->next]->pts);
362
363     if (!s->srce[s->crnt]) {
364         // the filter cannot do anything
365         ff_dlog(ctx, "process_work_frame() no current frame cached: move on to next frame, do not output a frame\n");
366         next_source(ctx);
367         return 0;
368     }
369
370     work_next_pts = s->pts + s->average_dest_pts_delta;
371
372     ff_dlog(ctx, "process_work_frame() work crnt pts:%"PRId64"\n", s->pts);
373     ff_dlog(ctx, "process_work_frame() work next pts:%"PRId64"\n", work_next_pts);
374     if (s->srce[s->prev])
375         ff_dlog(ctx, "process_work_frame() srce prev pts:%"PRId64" at dest time base:%u/%u\n",
376             s->srce_pts_dest[s->prev], s->dest_time_base.num, s->dest_time_base.den);
377     if (s->srce[s->crnt])
378         ff_dlog(ctx, "process_work_frame() srce crnt pts:%"PRId64" at dest time base:%u/%u\n",
379             s->srce_pts_dest[s->crnt], s->dest_time_base.num, s->dest_time_base.den);
380     if (s->srce[s->next])
381         ff_dlog(ctx, "process_work_frame() srce next pts:%"PRId64" at dest time base:%u/%u\n",
382             s->srce_pts_dest[s->next], s->dest_time_base.num, s->dest_time_base.den);
383
384     av_assert0(s->srce[s->next]);
385
386     // should filter be skipping input frame (output frame rate is lower than input frame rate)
387     if (!s->flush && s->pts >= s->srce_pts_dest[s->next]) {
388         ff_dlog(ctx, "process_work_frame() work crnt pts >= srce next pts: SKIP FRAME, move on to next frame, do not output a frame\n");
389         next_source(ctx);
390         s->pending_srce_frames--;
391         return 0;
392     }
393
394     // calculate interpolation
395     interpolate = av_rescale(s->pts - s->srce_pts_dest[s->crnt], s->max, s->average_srce_pts_dest_delta);
396     ff_dlog(ctx, "process_work_frame() interpolate:%d/%d\n", interpolate, s->max);
397     src1 = s->crnt;
398     if (interpolate > s->interp_end) {
399         ff_dlog(ctx, "process_work_frame() source is:NEXT\n");
400         src1 = s->next;
401     }
402     if (s->srce[s->prev] && interpolate < -s->interp_end) {
403         ff_dlog(ctx, "process_work_frame() source is:PREV\n");
404         src1 = s->prev;
405     }
406
407     // decide whether to blend two frames
408     if ((interpolate >= s->interp_start && interpolate <= s->interp_end) || (interpolate <= -s->interp_start && interpolate >= -s->interp_end)) {
409         if (interpolate > 0) {
410             ff_dlog(ctx, "process_work_frame() interpolate source is:NEXT\n");
411             src2 = s->next;
412         } else {
413             ff_dlog(ctx, "process_work_frame() interpolate source is:PREV\n");
414             src2 = s->prev;
415         }
416         if (blend_frames(ctx, interpolate, src1, src2))
417             goto copy_done;
418         else
419             ff_dlog(ctx, "process_work_frame() CUT - DON'T INTERPOLATE\n");
420     }
421
422     ff_dlog(ctx, "process_work_frame() COPY to the work frame\n");
423     // copy the frame we decided is our base source
424     s->work = av_frame_clone(s->srce[src1]);
425     if (!s->work)
426         return AVERROR(ENOMEM);
427
428 copy_done:
429     s->work->pts = s->pts;
430
431     // should filter be re-using input frame (output frame rate is higher than input frame rate)
432     if (!s->flush && (work_next_pts + s->average_dest_pts_delta) < (s->srce_pts_dest[s->crnt] + s->average_srce_pts_dest_delta)) {
433         ff_dlog(ctx, "process_work_frame() REPEAT FRAME\n");
434     } else {
435         ff_dlog(ctx, "process_work_frame() CONSUME FRAME, move to next frame\n");
436         s->pending_srce_frames--;
437         next_source(ctx);
438     }
439     ff_dlog(ctx, "process_work_frame() output a frame\n");
440     s->dest_frame_num++;
441     if (stop)
442         s->pending_end_frame = 0;
443     s->last_dest_frame_pts = s->work->pts;
444
445     return 1;
446 }
447
448 static void set_srce_frame_dest_pts(AVFilterContext *ctx)
449 {
450     FrameRateContext *s = ctx->priv;
451
452     ff_dlog(ctx, "set_srce_frame_output_pts()\n");
453
454     // scale the input pts from the timebase difference between input and output
455     if (s->srce[s->prev])
456         s->srce_pts_dest[s->prev] = av_rescale_q(s->srce[s->prev]->pts, s->srce_time_base, s->dest_time_base);
457     if (s->srce[s->crnt])
458         s->srce_pts_dest[s->crnt] = av_rescale_q(s->srce[s->crnt]->pts, s->srce_time_base, s->dest_time_base);
459     if (s->srce[s->next])
460         s->srce_pts_dest[s->next] = av_rescale_q(s->srce[s->next]->pts, s->srce_time_base, s->dest_time_base);
461 }
462
463 static void set_work_frame_pts(AVFilterContext *ctx)
464 {
465     FrameRateContext *s = ctx->priv;
466     int64_t pts, average_srce_pts_delta = 0;
467
468     ff_dlog(ctx, "set_work_frame_pts()\n");
469
470     av_assert0(s->srce[s->next]);
471     av_assert0(s->srce[s->crnt]);
472
473     ff_dlog(ctx, "set_work_frame_pts() srce crnt pts:%"PRId64"\n", s->srce[s->crnt]->pts);
474     ff_dlog(ctx, "set_work_frame_pts() srce next pts:%"PRId64"\n", s->srce[s->next]->pts);
475     if (s->srce[s->prev])
476         ff_dlog(ctx, "set_work_frame_pts() srce prev pts:%"PRId64"\n", s->srce[s->prev]->pts);
477
478     average_srce_pts_delta = s->average_srce_pts_dest_delta;
479     ff_dlog(ctx, "set_work_frame_pts() initial average srce pts:%"PRId64"\n", average_srce_pts_delta);
480
481     set_srce_frame_dest_pts(ctx);
482
483     // calculate the PTS delta
484     if ((pts = (s->srce_pts_dest[s->next] - s->srce_pts_dest[s->crnt]))) {
485         average_srce_pts_delta = average_srce_pts_delta?((average_srce_pts_delta+pts)>>1):pts;
486     } else if (s->srce[s->prev] && (pts = (s->srce_pts_dest[s->crnt] - s->srce_pts_dest[s->prev]))) {
487         average_srce_pts_delta = average_srce_pts_delta?((average_srce_pts_delta+pts)>>1):pts;
488     }
489
490     s->average_srce_pts_dest_delta = average_srce_pts_delta;
491     ff_dlog(ctx, "set_work_frame_pts() average srce pts:%"PRId64"\n", average_srce_pts_delta);
492     ff_dlog(ctx, "set_work_frame_pts() average srce pts:%"PRId64" at dest time base:%u/%u\n",
493             s->average_srce_pts_dest_delta, s->dest_time_base.num, s->dest_time_base.den);
494
495     if (ctx->inputs[0] && !s->average_dest_pts_delta) {
496         int64_t d = av_q2d(av_inv_q(av_mul_q(s->dest_time_base, s->dest_frame_rate)));
497         s->average_dest_pts_delta = d;
498         ff_dlog(ctx, "set_work_frame_pts() average dest pts delta:%"PRId64"\n", s->average_dest_pts_delta);
499     }
500
501     if (!s->dest_frame_num) {
502         s->pts = s->last_dest_frame_pts = s->srce_pts_dest[s->crnt];
503     } else {
504         s->pts = s->last_dest_frame_pts + s->average_dest_pts_delta;
505     }
506
507     ff_dlog(ctx, "set_work_frame_pts() calculated pts:%"PRId64" at dest time base:%u/%u\n",
508             s->pts, s->dest_time_base.num, s->dest_time_base.den);
509 }
510
511 static av_cold int init(AVFilterContext *ctx)
512 {
513     FrameRateContext *s = ctx->priv;
514     int i;
515
516     s->dest_frame_num = 0;
517
518     s->crnt = (N_SRCE)>>1;
519     s->last = N_SRCE - 1;
520
521     s->next = s->crnt - 1;
522     s->prev = s->crnt + 1;
523
524     for (i = 0; i < N_SRCE; i++)
525         s->srce_score[i] = -1.0;
526
527     return 0;
528 }
529
530 static av_cold void uninit(AVFilterContext *ctx)
531 {
532     FrameRateContext *s = ctx->priv;
533     int i;
534
535     for (i = s->frst; i < s->last; i++) {
536         if (s->srce[i] && (s->srce[i] != s->srce[i + 1]))
537             av_frame_free(&s->srce[i]);
538     }
539     av_frame_free(&s->srce[s->last]);
540 }
541
542 static int query_formats(AVFilterContext *ctx)
543 {
544     static const enum AVPixelFormat pix_fmts[] = {
545         AV_PIX_FMT_YUV410P,
546         AV_PIX_FMT_YUV411P, AV_PIX_FMT_YUVJ411P,
547         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVJ420P,
548         AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUVJ422P,
549         AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUVJ440P,
550         AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUVJ444P,
551         AV_PIX_FMT_YUV420P9, AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV420P12,
552         AV_PIX_FMT_YUV422P9, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV422P12,
553         AV_PIX_FMT_YUV444P9, AV_PIX_FMT_YUV444P10, AV_PIX_FMT_YUV444P12,
554         AV_PIX_FMT_NONE
555     };
556
557     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
558     if (!fmts_list)
559         return AVERROR(ENOMEM);
560     return ff_set_common_formats(ctx, fmts_list);
561 }
562
563 static int config_input(AVFilterLink *inlink)
564 {
565     AVFilterContext *ctx = inlink->dst;
566     FrameRateContext *s = ctx->priv;
567     const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
568     int plane;
569
570     for (plane = 0; plane < 4; plane++) {
571         s->line_size[plane] = av_image_get_linesize(inlink->format, inlink->w,
572                                                     plane);
573     }
574
575     s->bitdepth = pix_desc->comp[0].depth;
576     s->vsub = pix_desc->log2_chroma_h;
577     s->interp_start = s->interp_start_param << (s->bitdepth - 8);
578     s->interp_end = s->interp_end_param << (s->bitdepth - 8);
579
580     s->sad = av_pixelutils_get_sad_fn(3, 3, 2, s); // 8x8 both sources aligned
581     if (!s->sad)
582         return AVERROR(EINVAL);
583
584     s->srce_time_base = inlink->time_base;
585
586     s->max = 1 << (s->bitdepth);
587
588     return 0;
589 }
590
591 static int filter_frame(AVFilterLink *inlink, AVFrame *inpicref)
592 {
593     int ret;
594     AVFilterContext *ctx = inlink->dst;
595     FrameRateContext *s = ctx->priv;
596
597     // we have one new frame
598     s->pending_srce_frames++;
599
600     if (inpicref->interlaced_frame)
601         av_log(ctx, AV_LOG_WARNING, "Interlaced frame found - the output will not be correct.\n");
602
603     // store the pointer to the new frame
604     av_frame_free(&s->srce[s->frst]);
605     s->srce[s->frst] = inpicref;
606
607     if (!s->pending_end_frame && s->srce[s->crnt]) {
608         set_work_frame_pts(ctx);
609         s->pending_end_frame = 1;
610     } else {
611         set_srce_frame_dest_pts(ctx);
612     }
613
614     ret = process_work_frame(ctx, 1);
615     if (ret < 0)
616         return ret;
617     return ret ? ff_filter_frame(ctx->outputs[0], s->work) : 0;
618 }
619
620 static int config_output(AVFilterLink *outlink)
621 {
622     AVFilterContext *ctx = outlink->src;
623     FrameRateContext *s = ctx->priv;
624     int exact;
625
626     ff_dlog(ctx, "config_output()\n");
627
628     ff_dlog(ctx,
629            "config_output() input time base:%u/%u (%f)\n",
630            ctx->inputs[0]->time_base.num,ctx->inputs[0]->time_base.den,
631            av_q2d(ctx->inputs[0]->time_base));
632
633     // make sure timebase is small enough to hold the framerate
634
635     exact = av_reduce(&s->dest_time_base.num, &s->dest_time_base.den,
636                       av_gcd((int64_t)s->srce_time_base.num * s->dest_frame_rate.num,
637                              (int64_t)s->srce_time_base.den * s->dest_frame_rate.den ),
638                       (int64_t)s->srce_time_base.den * s->dest_frame_rate.num, INT_MAX);
639
640     av_log(ctx, AV_LOG_INFO,
641            "time base:%u/%u -> %u/%u exact:%d\n",
642            s->srce_time_base.num, s->srce_time_base.den,
643            s->dest_time_base.num, s->dest_time_base.den, exact);
644     if (!exact) {
645         av_log(ctx, AV_LOG_WARNING, "Timebase conversion is not exact\n");
646     }
647
648     outlink->frame_rate = s->dest_frame_rate;
649     outlink->time_base = s->dest_time_base;
650
651     ff_dlog(ctx,
652            "config_output() output time base:%u/%u (%f) w:%d h:%d\n",
653            outlink->time_base.num, outlink->time_base.den,
654            av_q2d(outlink->time_base),
655            outlink->w, outlink->h);
656
657
658     av_log(ctx, AV_LOG_INFO, "fps -> fps:%u/%u scene score:%f interpolate start:%d end:%d\n",
659             s->dest_frame_rate.num, s->dest_frame_rate.den,
660             s->scene_score, s->interp_start, s->interp_end);
661
662     return 0;
663 }
664
665 static int request_frame(AVFilterLink *outlink)
666 {
667     AVFilterContext *ctx = outlink->src;
668     FrameRateContext *s = ctx->priv;
669     int ret, i;
670
671     ff_dlog(ctx, "request_frame()\n");
672
673     // if there is no "next" frame AND we are not in flush then get one from our input filter
674     if (!s->srce[s->frst] && !s->flush)
675         goto request;
676
677     ff_dlog(ctx, "request_frame() REPEAT or FLUSH\n");
678
679     if (s->pending_srce_frames <= 0) {
680         ff_dlog(ctx, "request_frame() nothing else to do, return:EOF\n");
681         return AVERROR_EOF;
682     }
683
684     // otherwise, make brand-new frame and pass to our output filter
685     ff_dlog(ctx, "request_frame() FLUSH\n");
686
687     // back fill at end of file when source has no more frames
688     for (i = s->last; i > s->frst; i--) {
689         if (!s->srce[i - 1] && s->srce[i]) {
690             ff_dlog(ctx, "request_frame() copy:%d to:%d\n", i, i - 1);
691             s->srce[i - 1] = s->srce[i];
692         }
693     }
694
695     set_work_frame_pts(ctx);
696     ret = process_work_frame(ctx, 0);
697     if (ret < 0)
698         return ret;
699     if (ret)
700         return ff_filter_frame(ctx->outputs[0], s->work);
701
702 request:
703     ff_dlog(ctx, "request_frame() call source's request_frame()\n");
704     ret = ff_request_frame(ctx->inputs[0]);
705     if (ret < 0 && (ret != AVERROR_EOF)) {
706         ff_dlog(ctx, "request_frame() source's request_frame() returned error:%d\n", ret);
707         return ret;
708     } else if (ret == AVERROR_EOF) {
709         s->flush = 1;
710     }
711     ff_dlog(ctx, "request_frame() source's request_frame() returned:%d\n", ret);
712     return 0;
713 }
714
715 static const AVFilterPad framerate_inputs[] = {
716     {
717         .name         = "default",
718         .type         = AVMEDIA_TYPE_VIDEO,
719         .config_props = config_input,
720         .filter_frame = filter_frame,
721     },
722     { NULL }
723 };
724
725 static const AVFilterPad framerate_outputs[] = {
726     {
727         .name          = "default",
728         .type          = AVMEDIA_TYPE_VIDEO,
729         .request_frame = request_frame,
730         .config_props  = config_output,
731     },
732     { NULL }
733 };
734
735 AVFilter ff_vf_framerate = {
736     .name          = "framerate",
737     .description   = NULL_IF_CONFIG_SMALL("Upsamples or downsamples progressive source between specified frame rates."),
738     .priv_size     = sizeof(FrameRateContext),
739     .priv_class    = &framerate_class,
740     .init          = init,
741     .uninit        = uninit,
742     .query_formats = query_formats,
743     .inputs        = framerate_inputs,
744     .outputs       = framerate_outputs,
745     .flags         = AVFILTER_FLAG_SLICE_THREADS,
746 };