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