FFmpeg
Loading...
Searching...
No Matches
vf_mcdeint.c
Go to the documentation of this file.
1/*
2 * Copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
3 *
4 * This file is part of FFmpeg.
5 *
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.
10 *
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.
15 *
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.
19 */
20
21/**
22 * @file
23 * Motion Compensation Deinterlacer
24 * Ported from MPlayer libmpcodecs/vf_mcdeint.c.
25 *
26 * Known Issues:
27 *
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.
35 *
36 * If non iterative ME is used then snow currently ignores the OBMC
37 * window and as a result sometimes creates artifacts.
38 *
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.
43 *
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...
50 */
51
53#include "libavutil/opt.h"
54#include "libavcodec/avcodec.h"
55#include "libavutil/pixdesc.h"
56#include "avfilter.h"
57#include "filters.h"
58#include "video.h"
59
67
69 PARITY_TFF = 0, ///< top field first
70 PARITY_BFF = 1, ///< bottom field first
71};
72
73typedef struct MCDeintContext {
74 const AVClass *class;
75 int mode; ///< MCDeintMode
76 int parity; ///< MCDeintParity
77 int qp;
82
83#define OFFSET(x) offsetof(MCDeintContext, x)
84#define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
85#define CONST(name, help, val, u) { name, help, 0, AV_OPT_TYPE_CONST, {.i64=val}, INT_MIN, INT_MAX, FLAGS, .unit = u }
86
87static const AVOption mcdeint_options[] = {
88 { "mode", "set mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=MODE_FAST}, 0, MODE_NB-1, FLAGS, .unit="mode" },
89 CONST("fast", NULL, MODE_FAST, "mode"),
90 CONST("medium", NULL, MODE_MEDIUM, "mode"),
91 CONST("slow", NULL, MODE_SLOW, "mode"),
92 CONST("extra_slow", NULL, MODE_EXTRA_SLOW, "mode"),
93
94 { "parity", "set the assumed picture field parity", OFFSET(parity), AV_OPT_TYPE_INT, {.i64=PARITY_BFF}, -1, 1, FLAGS, .unit = "parity" },
95 CONST("tff", "assume top field first", PARITY_TFF, "parity"),
96 CONST("bff", "assume bottom field first", PARITY_BFF, "parity"),
97
98 { "qp", "set qp", OFFSET(qp), AV_OPT_TYPE_INT, {.i64=1}, INT_MIN, INT_MAX, FLAGS },
99 { NULL }
100};
101
103
104static int config_props(AVFilterLink *inlink)
105{
106 AVFilterContext *ctx = inlink->dst;
107 MCDeintContext *mcdeint = ctx->priv;
108 const AVCodec *enc;
109 AVCodecContext *enc_ctx;
111 int ret;
112
114 av_log(ctx, AV_LOG_ERROR, "Snow encoder is not enabled in libavcodec\n");
115 return AVERROR(EINVAL);
116 }
117
118 mcdeint->pkt = av_packet_alloc();
119 if (!mcdeint->pkt)
120 return AVERROR(ENOMEM);
121 mcdeint->frame_dec = av_frame_alloc();
122 if (!mcdeint->frame_dec)
123 return AVERROR(ENOMEM);
124 mcdeint->enc_ctx = avcodec_alloc_context3(enc);
125 if (!mcdeint->enc_ctx)
126 return AVERROR(ENOMEM);
127 enc_ctx = mcdeint->enc_ctx;
128 enc_ctx->width = inlink->w;
129 enc_ctx->height = inlink->h;
130 enc_ctx->time_base = (AVRational){1,25}; // meaningless
131 enc_ctx->gop_size = INT_MAX;
132 enc_ctx->max_b_frames = 0;
133 enc_ctx->pix_fmt = inlink->format;
136 enc_ctx->global_quality = 1;
137 enc_ctx->me_cmp = enc_ctx->me_sub_cmp = FF_CMP_SAD;
138 enc_ctx->mb_cmp = FF_CMP_SSE;
139 av_dict_set(&opts, "memc_only", "1", 0);
140 av_dict_set(&opts, "no_bitstream", "1", 0);
141
142 switch (mcdeint->mode) {
143 case MODE_EXTRA_SLOW:
144 enc_ctx->refs = 3;
146 case MODE_SLOW:
147 av_dict_set(&opts, "motion_est", "iter", 0);
149 case MODE_MEDIUM:
150 enc_ctx->flags |= AV_CODEC_FLAG_4MV;
151 enc_ctx->dia_size = 2;
153 case MODE_FAST:
154 enc_ctx->flags |= AV_CODEC_FLAG_QPEL;
155 }
156
157 ret = avcodec_open2(enc_ctx, enc, &opts);
159 if (ret < 0)
160 return ret;
161
162 return 0;
163}
164
166{
167 MCDeintContext *mcdeint = ctx->priv;
168
169 av_packet_free(&mcdeint->pkt);
170 avcodec_free_context(&mcdeint->enc_ctx);
171 av_frame_free(&mcdeint->frame_dec);
172}
173
175{
176 MCDeintContext *mcdeint = inlink->dst->priv;
177 AVFilterLink *outlink = inlink->dst->outputs[0];
178 AVFrame *outpic, *frame_dec = mcdeint->frame_dec;
179 AVPacket *pkt = mcdeint->pkt;
180 const AVPixFmtDescriptor *pix_fmt_desc = av_pix_fmt_desc_get(inlink->format);
181 int x, y, i, ret;
182
183 outpic = ff_get_video_buffer(outlink, outlink->w, outlink->h);
184 if (!outpic) {
186 return AVERROR(ENOMEM);
187 }
188 av_frame_copy_props(outpic, inpic);
189 inpic->quality = mcdeint->qp * FF_QP2LAMBDA;
190
191 ret = avcodec_send_frame(mcdeint->enc_ctx, inpic);
192 if (ret < 0) {
193 av_log(mcdeint->enc_ctx, AV_LOG_ERROR, "Error sending a frame for encoding\n");
194 goto end;
195 }
196 ret = avcodec_receive_packet(mcdeint->enc_ctx, pkt);
197 if (ret < 0) {
198 av_log(mcdeint->enc_ctx, AV_LOG_ERROR, "Error receiving a packet from encoding\n");
199 goto end;
200 }
202 ret = avcodec_receive_frame(mcdeint->enc_ctx, frame_dec);
203 if (ret < 0) {
204 av_log(mcdeint->enc_ctx, AV_LOG_ERROR, "Error receiving a frame from encoding\n");
205 goto end;
206 }
207
208 for (i = 0; i < 3; i++) {
209 int is_chroma = !!i;
210 int w, h;
211 if (is_chroma) {
212 w = AV_CEIL_RSHIFT(inlink->w, pix_fmt_desc->log2_chroma_w);
213 h = AV_CEIL_RSHIFT(inlink->h, pix_fmt_desc->log2_chroma_h);
214 } else {
215 w = inlink->w;
216 h = inlink->h;
217 }
218 int fils = frame_dec->linesize[i];
219 int srcs = inpic ->linesize[i];
220 int dsts = outpic ->linesize[i];
221
222 for (y = 0; y < h; y++) {
223 if ((y ^ mcdeint->parity) & 1) {
224 for (x = 0; x < w; x++) {
225 uint8_t *filp = &frame_dec->data[i][x + y*fils];
226 uint8_t *srcp = &inpic ->data[i][x + y*srcs];
227 uint8_t *dstp = &outpic ->data[i][x + y*dsts];
228
229 if (y > 0 && y < h-1){
230 int is_edge = x < 3 || x > w-4;
231 int diff0 = filp[-fils] - srcp[-srcs];
232 int diff1 = filp[+fils] - srcp[+srcs];
233 int temp = filp[0];
234
235#define DELTA(j) av_clip(j, -x, w-1-x)
236
237#define GET_SCORE_EDGE(j)\
238 FFABS(srcp[-srcs+DELTA(-1+(j))] - srcp[+srcs+DELTA(-1-(j))])+\
239 FFABS(srcp[-srcs+DELTA(j) ] - srcp[+srcs+DELTA( -(j))])+\
240 FFABS(srcp[-srcs+DELTA(1+(j)) ] - srcp[+srcs+DELTA( 1-(j))])
241
242#define GET_SCORE(j)\
243 FFABS(srcp[-srcs-1+(j)] - srcp[+srcs-1-(j)])+\
244 FFABS(srcp[-srcs +(j)] - srcp[+srcs -(j)])+\
245 FFABS(srcp[-srcs+1+(j)] - srcp[+srcs+1-(j)])
246
247#define CHECK_EDGE(j)\
248 { int score = GET_SCORE_EDGE(j);\
249 if (score < spatial_score){\
250 spatial_score = score;\
251 diff0 = filp[-fils+DELTA(j)] - srcp[-srcs+DELTA(j)];\
252 diff1 = filp[+fils+DELTA(-(j))] - srcp[+srcs+DELTA(-(j))];\
253
254#define CHECK(j)\
255 { int score = GET_SCORE(j);\
256 if (score < spatial_score){\
257 spatial_score= score;\
258 diff0 = filp[-fils+(j)] - srcp[-srcs+(j)];\
259 diff1 = filp[+fils-(j)] - srcp[+srcs-(j)];\
260
261 if (is_edge) {
262 int spatial_score = GET_SCORE_EDGE(0) - 1;
263 CHECK_EDGE(-1) CHECK_EDGE(-2) }} }}
264 CHECK_EDGE( 1) CHECK_EDGE( 2) }} }}
265 } else {
266 int spatial_score = GET_SCORE(0) - 1;
267 CHECK(-1) CHECK(-2) }} }}
268 CHECK( 1) CHECK( 2) }} }}
269 }
270
271
272 if (diff0 + diff1 > 0)
273 temp -= (diff0 + diff1 - FFABS(FFABS(diff0) - FFABS(diff1)) / 2) / 2;
274 else
275 temp -= (diff0 + diff1 + FFABS(FFABS(diff0) - FFABS(diff1)) / 2) / 2;
276 *filp = *dstp = temp > 255U ? ~(temp>>31) : temp;
277 } else {
278 *dstp = *filp;
279 }
280 }
281 }
282 }
283
284 for (y = 0; y < h; y++) {
285 if (!((y ^ mcdeint->parity) & 1)) {
286 for (x = 0; x < w; x++) {
287 frame_dec->data[i][x + y*fils] =
288 outpic ->data[i][x + y*dsts] = inpic->data[i][x + y*srcs];
289 }
290 }
291 }
292 }
293 mcdeint->parity ^= 1;
294
295end:
298 if (ret < 0) {
299 av_frame_free(&outpic);
300 return ret;
301 }
302 return ff_filter_frame(outlink, outpic);
303}
304
305static const AVFilterPad mcdeint_inputs[] = {
306 {
307 .name = "default",
308 .type = AVMEDIA_TYPE_VIDEO,
309 .filter_frame = filter_frame,
310 .config_props = config_props,
311 },
312};
313
315 .p.name = "mcdeint",
316 .p.description = NULL_IF_CONFIG_SMALL("Apply motion compensating deinterlacing."),
317 .p.priv_class = &mcdeint_class,
318 .priv_size = sizeof(MCDeintContext),
319 .uninit = uninit,
323};
const FFFilter ff_vf_mcdeint
Definition vf_mcdeint.c:314
#define U(x)
Definition vpx_arith.h:37
Libavcodec external API header.
#define FF_CMP_SSE
Definition avcodec.h:882
#define FF_CMP_SAD
Definition avcodec.h:881
@ MODE_NB
Main libavfilter public API header.
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define FLAGS
Definition cmdutils.c:598
#define AV_CEIL_RSHIFT(a, b)
Definition common.h:60
#define FFABS(a)
Absolute value, Note, INT_MIN / INT64_MIN result in undefined behavior as they are not representable ...
Definition common.h:74
#define NULL
Definition coverity.c:32
#define FF_COMPLIANCE_EXPERIMENTAL
Allow nonstandardized experimental things.
Definition defs.h:62
static AVPacket * pkt
static int filter_frame(DBEDecodeContext *s, AVFrame *frame)
Definition dolby_e.c:1067
@ AV_OPT_TYPE_INT
Underlying C type is int.
Definition opt.h:258
#define AV_CODEC_FLAG_QPEL
Use qpel MC.
Definition avcodec.h:225
int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
Initialize the AVCodecContext to use the given AVCodec.
Definition avcodec.c:144
AVCodecContext * avcodec_alloc_context3(const AVCodec *codec)
Allocate an AVCodecContext and set its fields to default values.
Definition options.c:149
#define AV_CODEC_FLAG_QSCALE
Use fixed qscale.
Definition avcodec.h:213
const AVCodec * avcodec_find_encoder(enum AVCodecID id)
Find a registered encoder with a matching codec ID.
Definition allcodecs.c:985
#define AV_CODEC_FLAG_LOW_DELAY
Force low delay.
Definition avcodec.h:314
#define AV_CODEC_FLAG_4MV
4 MV per MB allowed / advanced prediction for H.263.
Definition avcodec.h:217
void avcodec_free_context(AVCodecContext **avctx)
Free the codec context and everything associated with it and write NULL to the provided pointer.
Definition options.c:164
#define AV_CODEC_FLAG_RECON_FRAME
Request the encoder to output reconstructed frames, i.e. frames that would be produced by decoding th...
Definition avcodec.h:244
@ AV_CODEC_ID_SNOW
Definition codec_id.h:258
int avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
Alias for avcodec_receive_frame_flags(avctx, frame, 0).
Definition avcodec.c:720
int avcodec_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
Read encoded data from the encoder.
Definition encode.c:578
int avcodec_send_frame(AVCodecContext *avctx, const AVFrame *frame)
Supply a raw video or audio frame to the encoder.
Definition encode.c:545
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
Definition packet.c:74
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition packet.c:434
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
Definition packet.c:63
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values.
Definition dict.c:233
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition dict.c:86
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
Definition avutil.h:226
#define AVERROR(e)
Definition error.h:45
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition frame.c:64
int av_frame_copy_props(AVFrame *dst, const AVFrame *src)
Copy only "metadata" fields from src to dst.
Definition frame.c:599
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition frame.c:52
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
@ AVMEDIA_TYPE_VIDEO
Definition avutil.h:200
if(svq3)
static av_cold void uninit(AVBitStreamFilterContext *ctx)
#define CHECK(call)
Definition cbs_apv.c:59
#define FILTER_INPUTS(array)
Definition filters.h:264
#define FILTER_OUTPUTS(array)
Definition filters.h:265
#define FILTER_PIXFMTS(...)
Definition filters.h:250
#define AVFILTER_DEFINE_CLASS(fname)
Definition filters.h:478
Macro definitions for various function/variable attributes.
#define av_fallthrough
Definition attributes.h:67
#define av_cold
Definition attributes.h:117
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition internal.h:88
uint8_t w
Definition llvidencdsp.c:39
AVOptions.
const AVPixFmtDescriptor * av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt)
Definition pixdesc.c:3460
@ AV_PIX_FMT_YUV420P
planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
Definition pixfmt.h:73
@ AV_PIX_FMT_YUV444P
planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples)
Definition pixfmt.h:78
@ MODE_FAST
Definition signature.h:43
static int config_props(AVBitStreamFilterLink *link)
Definition source.c:181
Describe the class of an AVClass context structure.
Definition log.h:76
main external API structure.
Definition avcodec.h:443
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition avcodec.h:643
int width
picture width / height.
Definition avcodec.h:604
int me_cmp
motion estimation comparison function
Definition avcodec.h:862
int global_quality
Global quality for codecs which cannot change it per frame.
Definition avcodec.h:1235
int strict_std_compliance
strictly follow the standard (MPEG-4, ...).
Definition avcodec.h:1375
int max_b_frames
maximum number of B-frames between non-B-frames Note: The output will be delayed by max_b_frames+1 re...
Definition avcodec.h:781
int dia_size
ME diamond size & shape.
Definition avcodec.h:904
int me_sub_cmp
subpixel motion estimation comparison function
Definition avcodec.h:868
int mb_cmp
macroblock comparison function (not supported yet)
Definition avcodec.h:874
int gop_size
the number of pictures in a group of pictures, or 0 for intra_only
Definition avcodec.h:1021
int refs
number of reference frames
Definition avcodec.h:701
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition avcodec.h:547
int flags
AV_CODEC_FLAG_*.
Definition avcodec.h:500
AVCodec.
Definition codec.h:175
An instance of a filter.
Definition avfilter.h:273
void * priv
private data for use by the filter
Definition avfilter.h:288
AVFilterLink ** outputs
array of pointers to output links
Definition avfilter.h:285
A filter pad used for either input or output.
Definition filters.h:40
This structure describes decoded (raw) audio or video data.
Definition frame.h:472
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition frame.h:493
int linesize[AV_NUM_DATA_POINTERS]
For video, a positive or negative value, which is typically indicating the size in bytes of each pict...
Definition frame.h:517
AVOption.
Definition opt.h:428
This structure stores compressed data.
Definition packet.h:580
Descriptor that unambiguously describes how the bits of a pixel are stored in the up to 4 data planes...
Definition pixdesc.h:69
uint8_t log2_chroma_w
Amount to shift the luma width right to find the chroma width.
Definition pixdesc.h:80
uint8_t log2_chroma_h
Amount to shift the luma height right to find the chroma height.
Definition pixdesc.h:89
Rational number (pair of numerator and denominator).
Definition rational.h:58
int mode
MCDeintMode.
Definition vf_mcdeint.c:75
AVPacket * pkt
Definition vf_mcdeint.c:78
int parity
MCDeintParity.
Definition vf_mcdeint.c:76
AVCodecContext * enc_ctx
Definition vf_mcdeint.c:80
AVFrame * frame_dec
Definition vf_mcdeint.c:79
Definition swscale.c:71
#define av_log(a,...)
static AVFormatContext * ctx
Definition movenc.c:49
static AVDictionary * opts
Definition movenc.c:51
else temp
Definition vf_mcdeint.c:275
#define GET_SCORE(j)
#define CHECK(j)
* filp
Definition vf_mcdeint.c:276
static int filter_frame(AVFilterLink *inlink, AVFrame *inpic)
Definition vf_mcdeint.c:174
return ff_filter_frame(outlink, outpic)
MCDeintMode
Definition vf_mcdeint.c:60
@ MODE_EXTRA_SLOW
Definition vf_mcdeint.c:64
@ MODE_SLOW
Definition vf_mcdeint.c:63
@ MODE_MEDIUM
Definition vf_mcdeint.c:62
MCDeintParity
Definition vf_mcdeint.c:68
@ PARITY_BFF
bottom field first
Definition vf_mcdeint.c:70
@ PARITY_TFF
top field first
Definition vf_mcdeint.c:69
av_frame_free & inpic
Definition vf_mcdeint.c:297
#define CHECK_EDGE(j)
static const AVOption mcdeint_options[]
Definition vf_mcdeint.c:87
static const AVFilterPad mcdeint_inputs[]
Definition vf_mcdeint.c:305
#define CONST(name, help, val, u)
Definition vf_mcdeint.c:85
#define GET_SCORE_EDGE(j)
static int config_props(AVFilterLink *inlink)
Definition vf_mcdeint.c:104
static av_cold void uninit(AVFilterContext *ctx)
Definition vf_mcdeint.c:165
mcdeint parity
Definition vf_mcdeint.c:293
#define OFFSET(x)
Definition vf_mcdeint.c:83
const AVFilterPad ff_video_default_filterpad[1]
An AVFilterPad array whose only entry has name "default" and is of type AVMEDIA_TYPE_VIDEO.
Definition video.c:37
AVFrame * ff_get_video_buffer(AVFilterLink *link, int w, int h)
Request a picture buffer with a specific set of permissions.
Definition video.c:89