2 * Copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
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
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with FFmpeg; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 * Motion Compensation Deinterlacer
24 * Ported from MPlayer libmpcodecs/vf_mcdeint.c.
28 * The motion estimation is somewhat at the mercy of the input, if the
29 * input frames are created purely based on spatial interpolation then
30 * for example a thin black line or another random and not
31 * interpolateable pattern will cause problems.
32 * Note: completely ignoring the "unavailable" lines during motion
33 * estimation did not look any better, so the most obvious solution
34 * would be to improve tfields or penalize problematic motion vectors.
36 * If non iterative ME is used then snow currently ignores the OBMC
37 * window and as a result sometimes creates artifacts.
39 * Only past frames are used, we should ideally use future frames too,
40 * something like filtering the whole movie in forward and then
41 * backward direction seems like an interesting idea but the current
42 * filter framework is FAR from supporting such things.
44 * Combining the motion compensated image with the input image also is
45 * not as trivial as it seems, simple blindly taking even lines from
46 * one and odd ones from the other does not work at all as ME/MC
47 * sometimes has nothing in the previous frames which matches the
48 * current. The current algorithm has been found by trial and error
49 * and almost certainly can be improved...
52 #include "libavutil/opt.h"
53 #include "libavutil/pixdesc.h"
54 #include "libavcodec/avcodec.h"
68 PARITY_TFF = 0, ///< top field first
69 PARITY_BFF = 1, ///< bottom field first
72 typedef struct MCDeintContext {
74 int mode; ///< MCDeintMode
75 int parity; ///< MCDeintParity
78 AVCodecContext *enc_ctx;
81 #define OFFSET(x) offsetof(MCDeintContext, x)
82 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
83 #define CONST(name, help, val, unit) { name, help, 0, AV_OPT_TYPE_CONST, {.i64=val}, INT_MIN, INT_MAX, FLAGS, unit }
85 static const AVOption mcdeint_options[] = {
86 { "mode", "set mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=MODE_FAST}, 0, MODE_NB-1, FLAGS, .unit="mode" },
87 CONST("fast", NULL, MODE_FAST, "mode"),
88 CONST("medium", NULL, MODE_MEDIUM, "mode"),
89 CONST("slow", NULL, MODE_SLOW, "mode"),
90 CONST("extra_slow", NULL, MODE_EXTRA_SLOW, "mode"),
92 { "parity", "set the assumed picture field parity", OFFSET(parity), AV_OPT_TYPE_INT, {.i64=PARITY_BFF}, -1, 1, FLAGS, "parity" },
93 CONST("tff", "assume top field first", PARITY_TFF, "parity"),
94 CONST("bff", "assume bottom field first", PARITY_BFF, "parity"),
96 { "qp", "set qp", OFFSET(qp), AV_OPT_TYPE_INT, {.i64=1}, INT_MIN, INT_MAX, FLAGS },
100 AVFILTER_DEFINE_CLASS(mcdeint);
102 static int config_props(AVFilterLink *inlink)
104 AVFilterContext *ctx = inlink->dst;
105 MCDeintContext *mcdeint = ctx->priv;
107 AVCodecContext *enc_ctx;
108 AVDictionary *opts = NULL;
111 if (!(enc = avcodec_find_encoder(AV_CODEC_ID_SNOW))) {
112 av_log(ctx, AV_LOG_ERROR, "Snow encoder is not enabled in libavcodec\n");
113 return AVERROR(EINVAL);
116 mcdeint->pkt = av_packet_alloc();
118 return AVERROR(ENOMEM);
119 mcdeint->enc_ctx = avcodec_alloc_context3(enc);
120 if (!mcdeint->enc_ctx)
121 return AVERROR(ENOMEM);
122 enc_ctx = mcdeint->enc_ctx;
123 enc_ctx->width = inlink->w;
124 enc_ctx->height = inlink->h;
125 enc_ctx->time_base = (AVRational){1,25}; // meaningless
126 enc_ctx->gop_size = INT_MAX;
127 enc_ctx->max_b_frames = 0;
128 enc_ctx->pix_fmt = AV_PIX_FMT_YUV420P;
129 enc_ctx->flags = AV_CODEC_FLAG_QSCALE | AV_CODEC_FLAG_LOW_DELAY;
130 enc_ctx->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
131 enc_ctx->global_quality = 1;
132 enc_ctx->me_cmp = enc_ctx->me_sub_cmp = FF_CMP_SAD;
133 enc_ctx->mb_cmp = FF_CMP_SSE;
134 av_dict_set(&opts, "memc_only", "1", 0);
135 av_dict_set(&opts, "no_bitstream", "1", 0);
137 switch (mcdeint->mode) {
138 case MODE_EXTRA_SLOW:
141 av_dict_set(&opts, "motion_est", "iter", 0);
143 enc_ctx->flags |= AV_CODEC_FLAG_4MV;
144 enc_ctx->dia_size = 2;
146 enc_ctx->flags |= AV_CODEC_FLAG_QPEL;
149 ret = avcodec_open2(enc_ctx, enc, &opts);
157 static av_cold void uninit(AVFilterContext *ctx)
159 MCDeintContext *mcdeint = ctx->priv;
161 av_packet_free(&mcdeint->pkt);
162 avcodec_free_context(&mcdeint->enc_ctx);
165 static int query_formats(AVFilterContext *ctx)
167 static const enum AVPixelFormat pix_fmts[] = {
168 AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE
170 AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
172 return AVERROR(ENOMEM);
173 return ff_set_common_formats(ctx, fmts_list);
176 static int filter_frame(AVFilterLink *inlink, AVFrame *inpic)
178 MCDeintContext *mcdeint = inlink->dst->priv;
179 AVFilterLink *outlink = inlink->dst->outputs[0];
180 AVFrame *outpic, *frame_dec;
181 AVPacket *pkt = mcdeint->pkt;
182 int x, y, i, ret, got_frame = 0;
184 outpic = ff_get_video_buffer(outlink, outlink->w, outlink->h);
186 av_frame_free(&inpic);
187 return AVERROR(ENOMEM);
189 av_frame_copy_props(outpic, inpic);
190 inpic->quality = mcdeint->qp * FF_QP2LAMBDA;
192 ret = avcodec_encode_video2(mcdeint->enc_ctx, pkt, inpic, &got_frame);
196 frame_dec = mcdeint->enc_ctx->coded_frame;
198 for (i = 0; i < 3; i++) {
200 int w = AV_CEIL_RSHIFT(inlink->w, is_chroma);
201 int h = AV_CEIL_RSHIFT(inlink->h, is_chroma);
202 int fils = frame_dec->linesize[i];
203 int srcs = inpic ->linesize[i];
204 int dsts = outpic ->linesize[i];
206 for (y = 0; y < h; y++) {
207 if ((y ^ mcdeint->parity) & 1) {
208 for (x = 0; x < w; x++) {
209 uint8_t *filp = &frame_dec->data[i][x + y*fils];
210 uint8_t *srcp = &inpic ->data[i][x + y*srcs];
211 uint8_t *dstp = &outpic ->data[i][x + y*dsts];
213 if (y > 0 && y < h-1){
214 int is_edge = x < 3 || x > w-4;
215 int diff0 = filp[-fils] - srcp[-srcs];
216 int diff1 = filp[+fils] - srcp[+srcs];
219 #define DELTA(j) av_clip(j, -x, w-1-x)
221 #define GET_SCORE_EDGE(j)\
222 FFABS(srcp[-srcs+DELTA(-1+(j))] - srcp[+srcs+DELTA(-1-(j))])+\
223 FFABS(srcp[-srcs+DELTA(j) ] - srcp[+srcs+DELTA( -(j))])+\
224 FFABS(srcp[-srcs+DELTA(1+(j)) ] - srcp[+srcs+DELTA( 1-(j))])
226 #define GET_SCORE(j)\
227 FFABS(srcp[-srcs-1+(j)] - srcp[+srcs-1-(j)])+\
228 FFABS(srcp[-srcs +(j)] - srcp[+srcs -(j)])+\
229 FFABS(srcp[-srcs+1+(j)] - srcp[+srcs+1-(j)])
231 #define CHECK_EDGE(j)\
232 { int score = GET_SCORE_EDGE(j);\
233 if (score < spatial_score){\
234 spatial_score = score;\
235 diff0 = filp[-fils+DELTA(j)] - srcp[-srcs+DELTA(j)];\
236 diff1 = filp[+fils+DELTA(-(j))] - srcp[+srcs+DELTA(-(j))];\
239 { int score = GET_SCORE(j);\
240 if (score < spatial_score){\
241 spatial_score= score;\
242 diff0 = filp[-fils+(j)] - srcp[-srcs+(j)];\
243 diff1 = filp[+fils-(j)] - srcp[+srcs-(j)];\
246 int spatial_score = GET_SCORE_EDGE(0) - 1;
247 CHECK_EDGE(-1) CHECK_EDGE(-2) }} }}
248 CHECK_EDGE( 1) CHECK_EDGE( 2) }} }}
250 int spatial_score = GET_SCORE(0) - 1;
251 CHECK(-1) CHECK(-2) }} }}
252 CHECK( 1) CHECK( 2) }} }}
256 if (diff0 + diff1 > 0)
257 temp -= (diff0 + diff1 - FFABS(FFABS(diff0) - FFABS(diff1)) / 2) / 2;
259 temp -= (diff0 + diff1 + FFABS(FFABS(diff0) - FFABS(diff1)) / 2) / 2;
260 *filp = *dstp = temp > 255U ? ~(temp>>31) : temp;
268 for (y = 0; y < h; y++) {
269 if (!((y ^ mcdeint->parity) & 1)) {
270 for (x = 0; x < w; x++) {
271 frame_dec->data[i][x + y*fils] =
272 outpic ->data[i][x + y*dsts] = inpic->data[i][x + y*srcs];
277 mcdeint->parity ^= 1;
280 av_packet_unref(pkt);
281 av_frame_free(&inpic);
283 av_frame_free(&outpic);
286 return ff_filter_frame(outlink, outpic);
289 static const AVFilterPad mcdeint_inputs[] = {
292 .type = AVMEDIA_TYPE_VIDEO,
293 .filter_frame = filter_frame,
294 .config_props = config_props,
299 static const AVFilterPad mcdeint_outputs[] = {
302 .type = AVMEDIA_TYPE_VIDEO,
307 AVFilter ff_vf_mcdeint = {
309 .description = NULL_IF_CONFIG_SMALL("Apply motion compensating deinterlacing."),
310 .priv_size = sizeof(MCDeintContext),
312 .query_formats = query_formats,
313 .inputs = mcdeint_inputs,
314 .outputs = mcdeint_outputs,
315 .priv_class = &mcdeint_class,