]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_framerate.c
8d16998457ffd4b0edce302c988c2359ca6a64fd
[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
37 #include "avfilter.h"
38 #include "internal.h"
39 #include "video.h"
40 #include "filters.h"
41 #include "framerate.h"
42 #include "scene_sad.h"
43
44 #define OFFSET(x) offsetof(FrameRateContext, x)
45 #define V AV_OPT_FLAG_VIDEO_PARAM
46 #define F AV_OPT_FLAG_FILTERING_PARAM
47 #define FRAMERATE_FLAG_SCD 01
48
49 static const AVOption framerate_options[] = {
50     {"fps",                 "required output frames per second rate", OFFSET(dest_frame_rate), AV_OPT_TYPE_VIDEO_RATE, {.str="50"},             0,       INT_MAX, V|F },
51
52     {"interp_start",        "point to start linear interpolation",    OFFSET(interp_start),    AV_OPT_TYPE_INT,      {.i64=15},                 0,       255,     V|F },
53     {"interp_end",          "point to end linear interpolation",      OFFSET(interp_end),      AV_OPT_TYPE_INT,      {.i64=240},                0,       255,     V|F },
54     {"scene",               "scene change level",                     OFFSET(scene_score),     AV_OPT_TYPE_DOUBLE,   {.dbl=8.2},                0,       100., V|F },
55
56     {"flags",               "set flags",                              OFFSET(flags),           AV_OPT_TYPE_FLAGS,    {.i64=1},                  0,       INT_MAX, V|F, "flags" },
57     {"scene_change_detect", "enable scene change detection",          0,                       AV_OPT_TYPE_CONST,    {.i64=FRAMERATE_FLAG_SCD}, INT_MIN, INT_MAX, V|F, "flags" },
58     {"scd",                 "enable scene change detection",          0,                       AV_OPT_TYPE_CONST,    {.i64=FRAMERATE_FLAG_SCD}, INT_MIN, INT_MAX, V|F, "flags" },
59
60     {NULL}
61 };
62
63 AVFILTER_DEFINE_CLASS(framerate);
64
65 static double get_scene_score(AVFilterContext *ctx, AVFrame *crnt, AVFrame *next)
66 {
67     FrameRateContext *s = ctx->priv;
68     double ret = 0;
69
70     ff_dlog(ctx, "get_scene_score()\n");
71
72     if (crnt->height == next->height &&
73         crnt->width  == next->width) {
74         AVDictionaryEntry *e_mafd = NULL;
75         uint64_t sad;
76         double mafd = HUGE_VAL, diff;
77         char *tail = NULL;
78
79         ff_dlog(ctx, "get_scene_score() process\n");
80         e_mafd = av_dict_get(next->metadata, "lavfi.scd.mafd", NULL, AV_DICT_MATCH_CASE);
81         if (e_mafd)
82             mafd = strtod(e_mafd->value, &tail);
83         if (*tail || mafd == HUGE_VAL) {
84             s->sad(crnt->data[0], crnt->linesize[0], next->data[0], next->linesize[0], crnt->width, crnt->height, &sad);
85             emms_c();
86             mafd = (double)sad * 100.0 / (crnt->width * crnt->height) / (1 << s->bitdepth);
87         }
88         diff = fabs(mafd - s->prev_mafd);
89         ret  = av_clipf(FFMIN(mafd, diff), 0, 100.0);
90         s->prev_mafd = mafd;
91     }
92     ff_dlog(ctx, "get_scene_score() result is:%f\n", ret);
93     return ret;
94 }
95
96 typedef struct ThreadData {
97     AVFrame *copy_src1, *copy_src2;
98     uint16_t src1_factor, src2_factor;
99 } ThreadData;
100
101 static int filter_slice(AVFilterContext *ctx, void *arg, int job, int nb_jobs)
102 {
103     FrameRateContext *s = ctx->priv;
104     ThreadData *td = arg;
105     AVFrame *work = s->work;
106     AVFrame *src1 = td->copy_src1;
107     AVFrame *src2 = td->copy_src2;
108     uint16_t src1_factor = td->src1_factor;
109     uint16_t src2_factor = td->src2_factor;
110     int plane;
111
112     for (plane = 0; plane < 4 && src1->data[plane] && src2->data[plane]; plane++) {
113         const int start = (s->height[plane] *  job   ) / nb_jobs;
114         const int end   = (s->height[plane] * (job+1)) / nb_jobs;
115         uint8_t *src1_data = src1->data[plane] + start * src1->linesize[plane];
116         uint8_t *src2_data = src2->data[plane] + start * src2->linesize[plane];
117         uint8_t *dst_data  = work->data[plane] + start * work->linesize[plane];
118
119         s->blend(src1_data, src1->linesize[plane], src2_data, src2->linesize[plane],
120                  dst_data,  work->linesize[plane], s->line_size[plane], end - start,
121                  src1_factor, src2_factor, s->blend_factor_max >> 1);
122     }
123
124     return 0;
125 }
126
127 static int blend_frames(AVFilterContext *ctx, int interpolate)
128 {
129     FrameRateContext *s = ctx->priv;
130     AVFilterLink *outlink = ctx->outputs[0];
131     double interpolate_scene_score = 0;
132
133     if ((s->flags & FRAMERATE_FLAG_SCD)) {
134         if (s->score >= 0.0)
135             interpolate_scene_score = s->score;
136         else
137             interpolate_scene_score = s->score = get_scene_score(ctx, s->f0, s->f1);
138         ff_dlog(ctx, "blend_frames() interpolate scene score:%f\n", interpolate_scene_score);
139     }
140     // decide if the shot-change detection allows us to blend two frames
141     if (interpolate_scene_score < s->scene_score) {
142         ThreadData td;
143         td.copy_src1 = s->f0;
144         td.copy_src2 = s->f1;
145         td.src2_factor = interpolate;
146         td.src1_factor = s->blend_factor_max - td.src2_factor;
147
148         // get work-space for output frame
149         s->work = ff_get_video_buffer(outlink, outlink->w, outlink->h);
150         if (!s->work)
151             return AVERROR(ENOMEM);
152
153         av_frame_copy_props(s->work, s->f0);
154
155         ff_dlog(ctx, "blend_frames() INTERPOLATE to create work frame\n");
156         ctx->internal->execute(ctx, filter_slice, &td, NULL, FFMIN(FFMAX(1, outlink->h >> 2), ff_filter_get_nb_threads(ctx)));
157         return 1;
158     }
159     return 0;
160 }
161
162 static int process_work_frame(AVFilterContext *ctx)
163 {
164     FrameRateContext *s = ctx->priv;
165     int64_t work_pts;
166     int64_t interpolate, interpolate8;
167     int ret;
168
169     if (!s->f1)
170         return 0;
171     if (!s->f0 && !s->flush)
172         return 0;
173
174     work_pts = s->start_pts + av_rescale_q(s->n, av_inv_q(s->dest_frame_rate), s->dest_time_base);
175
176     if (work_pts >= s->pts1 && !s->flush)
177         return 0;
178
179     if (!s->f0) {
180         s->work = av_frame_clone(s->f1);
181     } else {
182         if (work_pts >= s->pts1 + s->delta && s->flush)
183             return 0;
184
185         interpolate = av_rescale(work_pts - s->pts0, s->blend_factor_max, s->delta);
186         interpolate8 = av_rescale(work_pts - s->pts0, 256, s->delta);
187         ff_dlog(ctx, "process_work_frame() interpolate: %"PRId64"/256\n", interpolate8);
188         if (interpolate >= s->blend_factor_max || interpolate8 > s->interp_end) {
189             s->work = av_frame_clone(s->f1);
190         } else if (interpolate <= 0 || interpolate8 < s->interp_start) {
191             s->work = av_frame_clone(s->f0);
192         } else {
193             ret = blend_frames(ctx, interpolate);
194             if (ret < 0)
195                 return ret;
196             if (ret == 0)
197                 s->work = av_frame_clone(interpolate > (s->blend_factor_max >> 1) ? s->f1 : s->f0);
198         }
199     }
200
201     if (!s->work)
202         return AVERROR(ENOMEM);
203
204     s->work->pts = work_pts;
205     s->n++;
206
207     return 1;
208 }
209
210 static av_cold int init(AVFilterContext *ctx)
211 {
212     FrameRateContext *s = ctx->priv;
213     s->start_pts = AV_NOPTS_VALUE;
214     return 0;
215 }
216
217 static av_cold void uninit(AVFilterContext *ctx)
218 {
219     FrameRateContext *s = ctx->priv;
220     av_frame_free(&s->f0);
221     av_frame_free(&s->f1);
222 }
223
224 static int query_formats(AVFilterContext *ctx)
225 {
226     static const enum AVPixelFormat pix_fmts[] = {
227         AV_PIX_FMT_YUV410P,
228         AV_PIX_FMT_YUV411P, AV_PIX_FMT_YUVJ411P,
229         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVJ420P,
230         AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUVJ422P,
231         AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUVJ440P,
232         AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUVJ444P,
233         AV_PIX_FMT_YUV420P9, AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV420P12,
234         AV_PIX_FMT_YUV422P9, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV422P12,
235         AV_PIX_FMT_YUV444P9, AV_PIX_FMT_YUV444P10, AV_PIX_FMT_YUV444P12,
236         AV_PIX_FMT_NONE
237     };
238
239     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
240     if (!fmts_list)
241         return AVERROR(ENOMEM);
242     return ff_set_common_formats(ctx, fmts_list);
243 }
244
245 #define BLEND_FRAME_FUNC(nbits)                         \
246 static void blend_frames##nbits##_c(BLEND_FUNC_PARAMS)  \
247 {                                                       \
248     int line, pixel;                                    \
249     uint##nbits##_t *dstw  = (uint##nbits##_t *)dst;    \
250     uint##nbits##_t *src1w = (uint##nbits##_t *)src1;   \
251     uint##nbits##_t *src2w = (uint##nbits##_t *)src2;   \
252     int bytes = nbits / 8;                              \
253     width /= bytes;                                     \
254     src1_linesize /= bytes;                             \
255     src2_linesize /= bytes;                             \
256     dst_linesize /= bytes;                              \
257     for (line = 0; line < height; line++) {             \
258         for (pixel = 0; pixel < width; pixel++)         \
259             dstw[pixel] = ((src1w[pixel] * factor1) +   \
260                     (src2w[pixel] * factor2) + half)    \
261                     >> BLEND_FACTOR_DEPTH(nbits);       \
262         src1w += src1_linesize;                         \
263         src2w += src2_linesize;                         \
264         dstw  += dst_linesize;                          \
265     }                                                   \
266 }
267 BLEND_FRAME_FUNC(8)
268 BLEND_FRAME_FUNC(16)
269
270 void ff_framerate_init(FrameRateContext *s)
271 {
272     if (s->bitdepth == 8) {
273         s->blend_factor_max = 1 << BLEND_FACTOR_DEPTH(8);
274         s->blend = blend_frames8_c;
275     } else {
276         s->blend_factor_max = 1 << BLEND_FACTOR_DEPTH(16);
277         s->blend = blend_frames16_c;
278     }
279     if (ARCH_X86)
280         ff_framerate_init_x86(s);
281 }
282
283 static int config_input(AVFilterLink *inlink)
284 {
285     AVFilterContext *ctx = inlink->dst;
286     FrameRateContext *s = ctx->priv;
287     const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
288     int plane;
289
290     s->vsub = pix_desc->log2_chroma_h;
291     for (plane = 0; plane < 4; plane++) {
292         s->line_size[plane] = av_image_get_linesize(inlink->format, inlink->w, plane);
293         s->height[plane] = inlink->h >> ((plane == 1 || plane == 2) ? s->vsub : 0);
294     }
295
296     s->bitdepth = pix_desc->comp[0].depth;
297
298     s->sad = ff_scene_sad_get_fn(s->bitdepth == 8 ? 8 : 16);
299     if (!s->sad)
300         return AVERROR(EINVAL);
301
302     s->srce_time_base = inlink->time_base;
303
304     ff_framerate_init(s);
305
306     return 0;
307 }
308
309 static int activate(AVFilterContext *ctx)
310 {
311     int ret, status;
312     AVFilterLink *inlink = ctx->inputs[0];
313     AVFilterLink *outlink = ctx->outputs[0];
314     FrameRateContext *s = ctx->priv;
315     AVFrame *inpicref;
316     int64_t pts;
317
318     FF_FILTER_FORWARD_STATUS_BACK(outlink, inlink);
319
320 retry:
321     ret = process_work_frame(ctx);
322     if (ret < 0)
323         return ret;
324     else if (ret == 1)
325         return ff_filter_frame(outlink, s->work);
326
327     ret = ff_inlink_consume_frame(inlink, &inpicref);
328     if (ret < 0)
329         return ret;
330
331     if (inpicref) {
332         if (inpicref->interlaced_frame)
333             av_log(ctx, AV_LOG_WARNING, "Interlaced frame found - the output will not be correct.\n");
334
335         if (inpicref->pts == AV_NOPTS_VALUE) {
336             av_log(ctx, AV_LOG_WARNING, "Ignoring frame without PTS.\n");
337             av_frame_free(&inpicref);
338         }
339     }
340
341     if (inpicref) {
342         pts = av_rescale_q(inpicref->pts, s->srce_time_base, s->dest_time_base);
343
344         if (s->f1 && pts == s->pts1) {
345             av_log(ctx, AV_LOG_WARNING, "Ignoring frame with same PTS.\n");
346             av_frame_free(&inpicref);
347         }
348     }
349
350     if (inpicref) {
351         av_frame_free(&s->f0);
352         s->f0 = s->f1;
353         s->pts0 = s->pts1;
354         s->f1 = inpicref;
355         s->pts1 = pts;
356         s->delta = s->pts1 - s->pts0;
357         s->score = -1.0;
358
359         if (s->delta < 0) {
360             av_log(ctx, AV_LOG_WARNING, "PTS discontinuity.\n");
361             s->start_pts = s->pts1;
362             s->n = 0;
363             av_frame_free(&s->f0);
364         }
365
366         if (s->start_pts == AV_NOPTS_VALUE)
367             s->start_pts = s->pts1;
368
369         goto retry;
370     }
371
372     if (ff_inlink_acknowledge_status(inlink, &status, &pts)) {
373         if (!s->flush) {
374             s->flush = 1;
375             goto retry;
376         }
377         ff_outlink_set_status(outlink, status, pts);
378         return 0;
379     }
380
381     FF_FILTER_FORWARD_WANTED(outlink, inlink);
382
383     return FFERROR_NOT_READY;
384 }
385
386 static int config_output(AVFilterLink *outlink)
387 {
388     AVFilterContext *ctx = outlink->src;
389     FrameRateContext *s = ctx->priv;
390     int exact;
391
392     ff_dlog(ctx, "config_output()\n");
393
394     ff_dlog(ctx,
395            "config_output() input time base:%u/%u (%f)\n",
396            ctx->inputs[0]->time_base.num,ctx->inputs[0]->time_base.den,
397            av_q2d(ctx->inputs[0]->time_base));
398
399     // make sure timebase is small enough to hold the framerate
400
401     exact = av_reduce(&s->dest_time_base.num, &s->dest_time_base.den,
402                       av_gcd((int64_t)s->srce_time_base.num * s->dest_frame_rate.num,
403                              (int64_t)s->srce_time_base.den * s->dest_frame_rate.den ),
404                       (int64_t)s->srce_time_base.den * s->dest_frame_rate.num, INT_MAX);
405
406     av_log(ctx, AV_LOG_INFO,
407            "time base:%u/%u -> %u/%u exact:%d\n",
408            s->srce_time_base.num, s->srce_time_base.den,
409            s->dest_time_base.num, s->dest_time_base.den, exact);
410     if (!exact) {
411         av_log(ctx, AV_LOG_WARNING, "Timebase conversion is not exact\n");
412     }
413
414     outlink->frame_rate = s->dest_frame_rate;
415     outlink->time_base = s->dest_time_base;
416
417     ff_dlog(ctx,
418            "config_output() output time base:%u/%u (%f) w:%d h:%d\n",
419            outlink->time_base.num, outlink->time_base.den,
420            av_q2d(outlink->time_base),
421            outlink->w, outlink->h);
422
423
424     av_log(ctx, AV_LOG_INFO, "fps -> fps:%u/%u scene score:%f interpolate start:%d end:%d\n",
425             s->dest_frame_rate.num, s->dest_frame_rate.den,
426             s->scene_score, s->interp_start, s->interp_end);
427
428     return 0;
429 }
430
431 static const AVFilterPad framerate_inputs[] = {
432     {
433         .name         = "default",
434         .type         = AVMEDIA_TYPE_VIDEO,
435         .config_props = config_input,
436     },
437     { NULL }
438 };
439
440 static const AVFilterPad framerate_outputs[] = {
441     {
442         .name          = "default",
443         .type          = AVMEDIA_TYPE_VIDEO,
444         .config_props  = config_output,
445     },
446     { NULL }
447 };
448
449 AVFilter ff_vf_framerate = {
450     .name          = "framerate",
451     .description   = NULL_IF_CONFIG_SMALL("Upsamples or downsamples progressive source between specified frame rates."),
452     .priv_size     = sizeof(FrameRateContext),
453     .priv_class    = &framerate_class,
454     .init          = init,
455     .uninit        = uninit,
456     .query_formats = query_formats,
457     .inputs        = framerate_inputs,
458     .outputs       = framerate_outputs,
459     .flags         = AVFILTER_FLAG_SLICE_THREADS,
460     .activate      = activate,
461 };