]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_tinterlace.c
Merge commit 'a41e5e192ed8f79f6607f978dee3205580ba5039'
[ffmpeg] / libavfilter / vf_tinterlace.c
1 /*
2  * Copyright (c) 2011 Stefano Sabatini
3  * Copyright (c) 2010 Baptiste Coudurier
4  * Copyright (c) 2003 Michael Zucchi <notzed@ximian.com>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with FFmpeg if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 /**
24  * @file
25  * temporal field interlace filter, ported from MPlayer/libmpcodecs
26  */
27
28 #include "libavutil/opt.h"
29 #include "libavutil/imgutils.h"
30 #include "libavutil/avassert.h"
31 #include "avfilter.h"
32 #include "internal.h"
33 #include "tinterlace.h"
34
35 #define OFFSET(x) offsetof(TInterlaceContext, x)
36 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
37 #define TINTERLACE_FLAG_VLPF 01
38 #define TINTERLACE_FLAG_EXACT_TB 2
39
40 static const AVOption tinterlace_options[] = {
41     {"mode",              "select interlace mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=MODE_MERGE}, 0, MODE_NB-1, FLAGS, "mode"},
42     {"merge",             "merge fields",                                 0, AV_OPT_TYPE_CONST, {.i64=MODE_MERGE},             INT_MIN, INT_MAX, FLAGS, "mode"},
43     {"drop_even",         "drop even fields",                             0, AV_OPT_TYPE_CONST, {.i64=MODE_DROP_EVEN},         INT_MIN, INT_MAX, FLAGS, "mode"},
44     {"drop_odd",          "drop odd fields",                              0, AV_OPT_TYPE_CONST, {.i64=MODE_DROP_ODD},          INT_MIN, INT_MAX, FLAGS, "mode"},
45     {"pad",               "pad alternate lines with black",               0, AV_OPT_TYPE_CONST, {.i64=MODE_PAD},               INT_MIN, INT_MAX, FLAGS, "mode"},
46     {"interleave_top",    "interleave top and bottom fields",             0, AV_OPT_TYPE_CONST, {.i64=MODE_INTERLEAVE_TOP},    INT_MIN, INT_MAX, FLAGS, "mode"},
47     {"interleave_bottom", "interleave bottom and top fields",             0, AV_OPT_TYPE_CONST, {.i64=MODE_INTERLEAVE_BOTTOM}, INT_MIN, INT_MAX, FLAGS, "mode"},
48     {"interlacex2",       "interlace fields from two consecutive frames", 0, AV_OPT_TYPE_CONST, {.i64=MODE_INTERLACEX2},       INT_MIN, INT_MAX, FLAGS, "mode"},
49
50     {"flags",             "set flags", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, 0, INT_MAX, 0, "flags" },
51     {"low_pass_filter",   "enable vertical low-pass filter",              0, AV_OPT_TYPE_CONST, {.i64 = TINTERLACE_FLAG_VLPF}, INT_MIN, INT_MAX, FLAGS, "flags" },
52     {"vlpf",              "enable vertical low-pass filter",              0, AV_OPT_TYPE_CONST, {.i64 = TINTERLACE_FLAG_VLPF}, INT_MIN, INT_MAX, FLAGS, "flags" },
53     {"exact_tb",          "force a timebase which can represent timestamps exactly", 0, AV_OPT_TYPE_CONST, {.i64 = TINTERLACE_FLAG_EXACT_TB}, INT_MIN, INT_MAX, FLAGS, "flags" },
54
55     {NULL}
56 };
57
58 AVFILTER_DEFINE_CLASS(tinterlace);
59
60 #define FULL_SCALE_YUVJ_FORMATS \
61     AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ440P
62
63 static const enum AVPixelFormat full_scale_yuvj_pix_fmts[] = {
64     FULL_SCALE_YUVJ_FORMATS, AV_PIX_FMT_NONE
65 };
66
67 static const AVRational standard_tbs[] = {
68     {1, 25},
69     {1, 30},
70     {1001, 30000},
71 };
72
73 static int query_formats(AVFilterContext *ctx)
74 {
75     static const enum AVPixelFormat pix_fmts[] = {
76         AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
77         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
78         AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P,
79         AV_PIX_FMT_YUVA420P, AV_PIX_FMT_YUVA422P, AV_PIX_FMT_YUVA444P,
80         AV_PIX_FMT_GRAY8, FULL_SCALE_YUVJ_FORMATS,
81         AV_PIX_FMT_NONE
82     };
83
84     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
85     if (!fmts_list)
86         return AVERROR(ENOMEM);
87     return ff_set_common_formats(ctx, fmts_list);
88 }
89
90 static void lowpass_line_c(uint8_t *dstp, ptrdiff_t width, const uint8_t *srcp,
91                            const uint8_t *srcp_above, const uint8_t *srcp_below)
92 {
93     int i;
94     for (i = 0; i < width; i++) {
95         // this calculation is an integer representation of
96         // '0.5 * current + 0.25 * above + 0.25 * below'
97         // '1 +' is for rounding.
98         dstp[i] = (1 + srcp[i] + srcp[i] + srcp_above[i] + srcp_below[i]) >> 2;
99     }
100 }
101
102 static av_cold void uninit(AVFilterContext *ctx)
103 {
104     TInterlaceContext *tinterlace = ctx->priv;
105
106     av_frame_free(&tinterlace->cur );
107     av_frame_free(&tinterlace->next);
108     av_freep(&tinterlace->black_data[0]);
109 }
110
111 static int config_out_props(AVFilterLink *outlink)
112 {
113     AVFilterContext *ctx = outlink->src;
114     AVFilterLink *inlink = outlink->src->inputs[0];
115     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(outlink->format);
116     TInterlaceContext *tinterlace = ctx->priv;
117     int i;
118
119     tinterlace->vsub = desc->log2_chroma_h;
120     outlink->w = inlink->w;
121     outlink->h = tinterlace->mode == MODE_MERGE || tinterlace->mode == MODE_PAD ?
122         inlink->h*2 : inlink->h;
123     if (tinterlace->mode == MODE_MERGE || tinterlace->mode == MODE_PAD)
124         outlink->sample_aspect_ratio = av_mul_q(inlink->sample_aspect_ratio,
125                                                 av_make_q(2, 1));
126
127     if (tinterlace->mode == MODE_PAD) {
128         uint8_t black[4] = { 16, 128, 128, 16 };
129         int i, ret;
130         if (ff_fmt_is_in(outlink->format, full_scale_yuvj_pix_fmts))
131             black[0] = black[3] = 0;
132         ret = av_image_alloc(tinterlace->black_data, tinterlace->black_linesize,
133                              outlink->w, outlink->h, outlink->format, 1);
134         if (ret < 0)
135             return ret;
136
137         /* fill black picture with black */
138         for (i = 0; i < 4 && tinterlace->black_data[i]; i++) {
139             int h = i == 1 || i == 2 ? FF_CEIL_RSHIFT(outlink->h, desc->log2_chroma_h) : outlink->h;
140             memset(tinterlace->black_data[i], black[i],
141                    tinterlace->black_linesize[i] * h);
142         }
143     }
144     if ((tinterlace->flags & TINTERLACE_FLAG_VLPF)
145             && !(tinterlace->mode == MODE_INTERLEAVE_TOP
146               || tinterlace->mode == MODE_INTERLEAVE_BOTTOM)) {
147         av_log(ctx, AV_LOG_WARNING, "low_pass_filter flag ignored with mode %d\n",
148                 tinterlace->mode);
149         tinterlace->flags &= ~TINTERLACE_FLAG_VLPF;
150     }
151     tinterlace->preout_time_base = inlink->time_base;
152     if (tinterlace->mode == MODE_INTERLACEX2) {
153         tinterlace->preout_time_base.den *= 2;
154         outlink->frame_rate = av_mul_q(inlink->frame_rate, (AVRational){2,1});
155         outlink->time_base  = av_mul_q(inlink->time_base , (AVRational){1,2});
156     } else if (tinterlace->mode != MODE_PAD) {
157         outlink->frame_rate = av_mul_q(inlink->frame_rate, (AVRational){1,2});
158         outlink->time_base  = av_mul_q(inlink->time_base , (AVRational){2,1});
159     }
160
161     for (i = 0; i<FF_ARRAY_ELEMS(standard_tbs); i++){
162         if (!av_cmp_q(standard_tbs[i], outlink->time_base))
163             break;
164     }
165     if (i == FF_ARRAY_ELEMS(standard_tbs) ||
166         (tinterlace->flags & TINTERLACE_FLAG_EXACT_TB))
167         outlink->time_base = tinterlace->preout_time_base;
168
169     if (tinterlace->flags & TINTERLACE_FLAG_VLPF) {
170         tinterlace->lowpass_line = lowpass_line_c;
171         if (ARCH_X86)
172             ff_tinterlace_init_x86(tinterlace);
173     }
174
175     av_log(ctx, AV_LOG_VERBOSE, "mode:%d filter:%s h:%d -> h:%d\n",
176            tinterlace->mode, (tinterlace->flags & TINTERLACE_FLAG_VLPF) ? "on" : "off",
177            inlink->h, outlink->h);
178
179     return 0;
180 }
181
182 #define FIELD_UPPER           0
183 #define FIELD_LOWER           1
184 #define FIELD_UPPER_AND_LOWER 2
185
186 /**
187  * Copy picture field from src to dst.
188  *
189  * @param src_field copy from upper, lower field or both
190  * @param interleave leave a padding line between each copied line
191  * @param dst_field copy to upper or lower field,
192  *        only meaningful when interleave is selected
193  * @param flags context flags
194  */
195 static inline
196 void copy_picture_field(TInterlaceContext *tinterlace,
197                         uint8_t *dst[4], int dst_linesize[4],
198                         const uint8_t *src[4], int src_linesize[4],
199                         enum AVPixelFormat format, int w, int src_h,
200                         int src_field, int interleave, int dst_field,
201                         int flags)
202 {
203     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
204     int hsub = desc->log2_chroma_w;
205     int plane, vsub = desc->log2_chroma_h;
206     int k = src_field == FIELD_UPPER_AND_LOWER ? 1 : 2;
207     int h;
208
209     for (plane = 0; plane < desc->nb_components; plane++) {
210         int lines = plane == 1 || plane == 2 ? FF_CEIL_RSHIFT(src_h, vsub) : src_h;
211         int cols  = plane == 1 || plane == 2 ? FF_CEIL_RSHIFT(    w, hsub) : w;
212         uint8_t *dstp = dst[plane];
213         const uint8_t *srcp = src[plane];
214
215         lines = (lines + (src_field == FIELD_UPPER)) / k;
216         if (src_field == FIELD_LOWER)
217             srcp += src_linesize[plane];
218         if (interleave && dst_field == FIELD_LOWER)
219             dstp += dst_linesize[plane];
220         if (flags & TINTERLACE_FLAG_VLPF) {
221             // Low-pass filtering is required when creating an interlaced destination from
222             // a progressive source which contains high-frequency vertical detail.
223             // Filtering will reduce interlace 'twitter' and Moire patterning.
224             int srcp_linesize = src_linesize[plane] * k;
225             int dstp_linesize = dst_linesize[plane] * (interleave ? 2 : 1);
226             for (h = lines; h > 0; h--) {
227                 const uint8_t *srcp_above = srcp - src_linesize[plane];
228                 const uint8_t *srcp_below = srcp + src_linesize[plane];
229                 if (h == lines) srcp_above = srcp; // there is no line above
230                 if (h == 1) srcp_below = srcp;     // there is no line below
231
232                 tinterlace->lowpass_line(dstp, cols, srcp, srcp_above, srcp_below);
233                 dstp += dstp_linesize;
234                 srcp += srcp_linesize;
235             }
236         } else {
237             av_image_copy_plane(dstp, dst_linesize[plane] * (interleave ? 2 : 1),
238                                 srcp, src_linesize[plane]*k, cols, lines);
239         }
240     }
241 }
242
243 static int filter_frame(AVFilterLink *inlink, AVFrame *picref)
244 {
245     AVFilterContext *ctx = inlink->dst;
246     AVFilterLink *outlink = ctx->outputs[0];
247     TInterlaceContext *tinterlace = ctx->priv;
248     AVFrame *cur, *next, *out;
249     int field, tff, ret;
250
251     av_frame_free(&tinterlace->cur);
252     tinterlace->cur  = tinterlace->next;
253     tinterlace->next = picref;
254
255     cur = tinterlace->cur;
256     next = tinterlace->next;
257     /* we need at least two frames */
258     if (!tinterlace->cur)
259         return 0;
260
261     switch (tinterlace->mode) {
262     case MODE_MERGE: /* move the odd frame into the upper field of the new image, even into
263              * the lower field, generating a double-height video at half framerate */
264         out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
265         if (!out)
266             return AVERROR(ENOMEM);
267         av_frame_copy_props(out, cur);
268         out->height = outlink->h;
269         out->interlaced_frame = 1;
270         out->top_field_first = 1;
271         out->sample_aspect_ratio = av_mul_q(cur->sample_aspect_ratio, av_make_q(2, 1));
272
273         /* write odd frame lines into the upper field of the new frame */
274         copy_picture_field(tinterlace, out->data, out->linesize,
275                            (const uint8_t **)cur->data, cur->linesize,
276                            inlink->format, inlink->w, inlink->h,
277                            FIELD_UPPER_AND_LOWER, 1, FIELD_UPPER, tinterlace->flags);
278         /* write even frame lines into the lower field of the new frame */
279         copy_picture_field(tinterlace, out->data, out->linesize,
280                            (const uint8_t **)next->data, next->linesize,
281                            inlink->format, inlink->w, inlink->h,
282                            FIELD_UPPER_AND_LOWER, 1, FIELD_LOWER, tinterlace->flags);
283         av_frame_free(&tinterlace->next);
284         break;
285
286     case MODE_DROP_ODD:  /* only output even frames, odd  frames are dropped; height unchanged, half framerate */
287     case MODE_DROP_EVEN: /* only output odd  frames, even frames are dropped; height unchanged, half framerate */
288         out = av_frame_clone(tinterlace->mode == MODE_DROP_EVEN ? cur : next);
289         if (!out)
290             return AVERROR(ENOMEM);
291         av_frame_free(&tinterlace->next);
292         break;
293
294     case MODE_PAD: /* expand each frame to double height, but pad alternate
295                     * lines with black; framerate unchanged */
296         out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
297         if (!out)
298             return AVERROR(ENOMEM);
299         av_frame_copy_props(out, cur);
300         out->height = outlink->h;
301         out->sample_aspect_ratio = av_mul_q(cur->sample_aspect_ratio, av_make_q(2, 1));
302
303         field = (1 + tinterlace->frame) & 1 ? FIELD_UPPER : FIELD_LOWER;
304         /* copy upper and lower fields */
305         copy_picture_field(tinterlace, out->data, out->linesize,
306                            (const uint8_t **)cur->data, cur->linesize,
307                            inlink->format, inlink->w, inlink->h,
308                            FIELD_UPPER_AND_LOWER, 1, field, tinterlace->flags);
309         /* pad with black the other field */
310         copy_picture_field(tinterlace, out->data, out->linesize,
311                            (const uint8_t **)tinterlace->black_data, tinterlace->black_linesize,
312                            inlink->format, inlink->w, inlink->h,
313                            FIELD_UPPER_AND_LOWER, 1, !field, tinterlace->flags);
314         break;
315
316         /* interleave upper/lower lines from odd frames with lower/upper lines from even frames,
317          * halving the frame rate and preserving image height */
318     case MODE_INTERLEAVE_TOP:    /* top    field first */
319     case MODE_INTERLEAVE_BOTTOM: /* bottom field first */
320         tff = tinterlace->mode == MODE_INTERLEAVE_TOP;
321         out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
322         if (!out)
323             return AVERROR(ENOMEM);
324         av_frame_copy_props(out, cur);
325         out->interlaced_frame = 1;
326         out->top_field_first = tff;
327
328         /* copy upper/lower field from cur */
329         copy_picture_field(tinterlace, out->data, out->linesize,
330                            (const uint8_t **)cur->data, cur->linesize,
331                            inlink->format, inlink->w, inlink->h,
332                            tff ? FIELD_UPPER : FIELD_LOWER, 1, tff ? FIELD_UPPER : FIELD_LOWER,
333                            tinterlace->flags);
334         /* copy lower/upper field from next */
335         copy_picture_field(tinterlace, out->data, out->linesize,
336                            (const uint8_t **)next->data, next->linesize,
337                            inlink->format, inlink->w, inlink->h,
338                            tff ? FIELD_LOWER : FIELD_UPPER, 1, tff ? FIELD_LOWER : FIELD_UPPER,
339                            tinterlace->flags);
340         av_frame_free(&tinterlace->next);
341         break;
342     case MODE_INTERLACEX2: /* re-interlace preserving image height, double frame rate */
343         /* output current frame first */
344         out = av_frame_clone(cur);
345         if (!out)
346             return AVERROR(ENOMEM);
347         out->interlaced_frame = 1;
348         if (cur->pts != AV_NOPTS_VALUE)
349             out->pts = cur->pts*2;
350
351         out->pts = av_rescale_q(out->pts, tinterlace->preout_time_base, outlink->time_base);
352         if ((ret = ff_filter_frame(outlink, out)) < 0)
353             return ret;
354
355         /* output mix of current and next frame */
356         tff = next->top_field_first;
357         out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
358         if (!out)
359             return AVERROR(ENOMEM);
360         av_frame_copy_props(out, next);
361         out->interlaced_frame = 1;
362         out->top_field_first = !tff;
363
364         if (next->pts != AV_NOPTS_VALUE && cur->pts != AV_NOPTS_VALUE)
365             out->pts = cur->pts + next->pts;
366         else
367             out->pts = AV_NOPTS_VALUE;
368         /* write current frame second field lines into the second field of the new frame */
369         copy_picture_field(tinterlace, out->data, out->linesize,
370                            (const uint8_t **)cur->data, cur->linesize,
371                            inlink->format, inlink->w, inlink->h,
372                            tff ? FIELD_LOWER : FIELD_UPPER, 1, tff ? FIELD_LOWER : FIELD_UPPER,
373                            tinterlace->flags);
374         /* write next frame first field lines into the first field of the new frame */
375         copy_picture_field(tinterlace, out->data, out->linesize,
376                            (const uint8_t **)next->data, next->linesize,
377                            inlink->format, inlink->w, inlink->h,
378                            tff ? FIELD_UPPER : FIELD_LOWER, 1, tff ? FIELD_UPPER : FIELD_LOWER,
379                            tinterlace->flags);
380         break;
381     default:
382         av_assert0(0);
383     }
384
385     out->pts = av_rescale_q(out->pts, tinterlace->preout_time_base, outlink->time_base);
386     ret = ff_filter_frame(outlink, out);
387     tinterlace->frame++;
388
389     return ret;
390 }
391
392 static const AVFilterPad tinterlace_inputs[] = {
393     {
394         .name         = "default",
395         .type         = AVMEDIA_TYPE_VIDEO,
396         .filter_frame = filter_frame,
397     },
398     { NULL }
399 };
400
401 static const AVFilterPad tinterlace_outputs[] = {
402     {
403         .name         = "default",
404         .type         = AVMEDIA_TYPE_VIDEO,
405         .config_props = config_out_props,
406     },
407     { NULL }
408 };
409
410 AVFilter ff_vf_tinterlace = {
411     .name          = "tinterlace",
412     .description   = NULL_IF_CONFIG_SMALL("Perform temporal field interlacing."),
413     .priv_size     = sizeof(TInterlaceContext),
414     .uninit        = uninit,
415     .query_formats = query_formats,
416     .inputs        = tinterlace_inputs,
417     .outputs       = tinterlace_outputs,
418     .priv_class    = &tinterlace_class,
419 };