>From 7a1fa3e6855693bdeea434f0147e12bb00bf989e Mon Sep 17 00:00:00 2001
From: Stefano Sabatini <stefano.sabatini-lala@poste.it>
Date: Sat, 25 Jun 2011 13:06:24 +0200
Subject: [PATCH] lavfi: port tinterlace filter from MPlayer

Port MPlayer tinterlace filter from MPlayer, with some ideas taken
from the FFmbc/libavfilter port, with the following main differences:

* added support for full-scale YUVJ formats
* added support for YUVA420P
* request_frame() on the filter is forced to return a frame
* some code factorization (related to the copy_picture_fields() function)
---
 configure                   |    1 +
 doc/filters.texi            |   34 +++++
 libavfilter/Makefile        |    1 +
 libavfilter/allfilters.c    |    1 +
 libavfilter/vf_tinterlace.c |  324 +++++++++++++++++++++++++++++++++++++++++++
 5 files changed, 361 insertions(+), 0 deletions(-)
 create mode 100644 libavfilter/vf_tinterlace.c

diff --git a/configure b/configure
index afa25d9..efd5c98 100755
--- a/configure
+++ b/configure
@@ -1509,6 +1509,7 @@ mp_filter_deps="gpl avcodec"
 negate_filter_deps="lut_filter"
 ocv_filter_deps="libopencv"
 scale_filter_deps="swscale"
+tinterlace_filter_deps="gpl"
 yadif_filter_deps="gpl"
 
 # libraries
diff --git a/doc/filters.texi b/doc/filters.texi
index b4ffcd9..5c29af9 100644
--- a/doc/filters.texi
+++ b/doc/filters.texi
@@ -1633,6 +1633,40 @@ For example:
 will create two separate outputs from the same input, one cropped and
 one padded.
 
+@section tinterlace
+
+Perform temporal field interlacing - merge pairs of frames into an
+interlaced frame, halving the framerate. Even frames are moved into
+the upper field, odd frames to the lower field.
+
+The frames are counted starting from 1, so the first input frame is
+considered odd.
+
+This filter accepts a parameter specifying the mode. Available modes
+are:
+
+@table @samp
+@item 0
+Move odd frames into the upper field of the new frame, even into the
+lower field, generating a double height frame at half framerate.
+
+@item 1
+Only output odd  frames, even frames are dropped; height
+unchanged, half framerate
+
+@item 2
+Only output even frames, odd  frames are dropped; height
+unchanged, half framerate
+
+@item 3
+Expand each frame to full height, but pad alternate lines with
+black; framerate unchanged and double height.
+
+@item 4
+Interleave even lines from even frames with odd lines from odd
+frames. Height unchanged at half framerate.
+@end table
+
 @section transpose
 
 Transpose rows with columns in the input video and optionally flip it.
diff --git a/libavfilter/Makefile b/libavfilter/Makefile
index d2e59f9..83c9add 100644
--- a/libavfilter/Makefile
+++ b/libavfilter/Makefile
@@ -58,6 +58,7 @@ OBJS-$(CONFIG_SETTB_FILTER)                  += vf_settb.o
 OBJS-$(CONFIG_SHOWINFO_FILTER)               += vf_showinfo.o
 OBJS-$(CONFIG_SLICIFY_FILTER)                += vf_slicify.o
 OBJS-$(CONFIG_SPLIT_FILTER)                  += vf_split.o
+OBJS-$(CONFIG_TINTERLACE_FILTER)             += vf_tinterlace.o
 OBJS-$(CONFIG_TRANSPOSE_FILTER)              += vf_transpose.o
 OBJS-$(CONFIG_UNSHARP_FILTER)                += vf_unsharp.o
 OBJS-$(CONFIG_VFLIP_FILTER)                  += vf_vflip.o
diff --git a/libavfilter/allfilters.c b/libavfilter/allfilters.c
index feae239..0395ad8 100644
--- a/libavfilter/allfilters.c
+++ b/libavfilter/allfilters.c
@@ -74,6 +74,7 @@ void avfilter_register_all(void)
     REGISTER_FILTER (SHOWINFO,    showinfo,    vf);
     REGISTER_FILTER (SLICIFY,     slicify,     vf);
     REGISTER_FILTER (SPLIT,       split,       vf);
+    REGISTER_FILTER (TINTERLACE,  tinterlace,  vf);
     REGISTER_FILTER (TRANSPOSE,   transpose,   vf);
     REGISTER_FILTER (UNSHARP,     unsharp,     vf);
     REGISTER_FILTER (VFLIP,       vflip,       vf);
diff --git a/libavfilter/vf_tinterlace.c b/libavfilter/vf_tinterlace.c
new file mode 100644
index 0000000..beaefde
--- /dev/null
+++ b/libavfilter/vf_tinterlace.c
@@ -0,0 +1,324 @@
+/*
+ * Copyright (c) 2011 Stefano Sabatini
+ * Copyright (c) 2010 Baptiste Coudurier
+ * Copyright (c) 2003 Michael Zucchi <notzed@ximian.com>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with FFmpeg if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+/**
+ * @file
+ * temporal field interlace filter, ported from MPlayer/libmpcodecs
+ */
+
+#include "libavutil/imgutils.h"
+#include "avfilter.h"
+#include "internal.h"
+
+typedef struct {
+    int mode;                   ///< interlace mode selected
+    int nb_frame;               ///< number of the output frame
+    int vsub;                   ///< chroma vertical subsampling
+    AVFilterBufferRef *cur;
+    AVFilterBufferRef *next;
+    uint8_t *black_data[4];     ///< buffer used to fill padded lines
+    int black_linesize[4];
+} TInterlaceContext;
+
+#define FULL_SCALE_YUVJ_FORMATS \
+        PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, \
+        PIX_FMT_YUVJ440P, PIX_FMT_GRAY8
+
+static enum PixelFormat full_scale_yuvj_pix_fmts[] = {
+    FULL_SCALE_YUVJ_FORMATS, PIX_FMT_NONE
+};
+
+static int query_formats(AVFilterContext *ctx)
+{
+    static const enum PixelFormat pix_fmts[] = {
+        PIX_FMT_YUV420P,  PIX_FMT_YUV422P,  PIX_FMT_YUV444P,
+        PIX_FMT_YUV444P,  PIX_FMT_YUV410P,  PIX_FMT_YUVA420P,
+        FULL_SCALE_YUVJ_FORMATS,
+        PIX_FMT_NONE
+    };
+
+    avfilter_set_common_pixel_formats(ctx, avfilter_make_format_list(pix_fmts));
+
+    return 0;
+}
+
+static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    TInterlaceContext *tinterlace = ctx->priv;
+    int n;
+    tinterlace->mode = 0;
+
+    if (args)
+        n = sscanf(args, "%d", &tinterlace->mode);
+
+    if (n != 1 || tinterlace->mode < 0 || tinterlace->mode > 4) {
+        av_log(ctx, AV_LOG_ERROR,
+               "Invalid mode '%s', use an integer between 0 and 4\n", args);
+        return AVERROR(EINVAL);
+    }
+
+    return 0;
+}
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+    TInterlaceContext *tinterlace = ctx->priv;
+
+    if (tinterlace->cur ) avfilter_unref_buffer(tinterlace->cur );
+    if (tinterlace->next) avfilter_unref_buffer(tinterlace->next);
+
+    av_freep(&tinterlace->black_data[0]);
+}
+
+static int config_out_props(AVFilterLink *outlink)
+{
+    AVFilterContext *ctx = outlink->src;
+    AVFilterLink *inlink = outlink->src->inputs[0];
+    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[outlink->format];
+    TInterlaceContext *tinterlace = ctx->priv;
+
+    tinterlace->vsub = desc->log2_chroma_h;
+    outlink->w = inlink->w;
+    outlink->h = tinterlace->mode == 0 || tinterlace->mode == 3 ?
+        inlink->h*2 : inlink->h;
+
+    if (tinterlace->mode == 3) {
+        uint8_t black[4] = { 16, 128, 128, 16 };
+        int i, ret;
+        if (ff_fmt_is_in(outlink->format, full_scale_yuvj_pix_fmts))
+            black[0] = black[3] = 0;
+        ret = av_image_alloc(tinterlace->black_data, tinterlace->black_linesize,
+                             outlink->w, outlink->h, outlink->format, 1);
+        if (ret < 0)
+            return ret;
+
+        /* fill black picture with black */
+        for (i = 0; i < 4 && tinterlace->black_data[i]; i++) {
+            int h = i == 1 || i == 2 ? outlink->h >> desc->log2_chroma_h : outlink->h;
+            memset(tinterlace->black_data[i], black[i],
+                   tinterlace->black_linesize[i] * h);
+        }
+    }
+    av_log(ctx, AV_LOG_INFO, "mode:%d h:%d -> h:%d\n",
+           tinterlace->mode, inlink->h, outlink->h);
+
+    return 0;
+}
+
+/**
+ * Copy picture fields from src to dst.
+ *
+ * @param dst_lower_fields     copy to lower fields if non-zero, to higher
+ *                             fields otherwise
+ * @param only_half_src_fields copy only half of the source fields
+ * @param src_lower_fields     if only_half_src_fields,
+ *                             copy from lower fields if non-zero,
+ *                             copy from higher fields otherwise
+ */
+static void copy_picture_fields(uint8_t *dst[4], int dst_linesize[4],
+                                uint8_t *src[4], int src_linesize[4],
+                                enum PixelFormat format, int w, int src_h,
+                                int dst_lower_fields,
+                                int only_half_src_fields, int src_lower_fields)
+{
+    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[format];
+    int plane, k = 1, vsub = desc->log2_chroma_h;
+    if (only_half_src_fields) {
+        src_h /= 2;
+        k = 2;
+    }
+
+    for (plane = 0; plane < desc->nb_components; plane++) {
+        int h = plane == 1 || plane == 2 ? src_h >> vsub : src_h;
+        int linesize = av_image_get_linesize(format, w, plane);
+        uint8_t *p = dst[plane];
+
+        if (dst_lower_fields)
+            p += dst_linesize[plane];
+        if (only_half_src_fields && src_lower_fields)
+            src[plane] += src_linesize[plane];
+        av_image_copy_plane(p, dst_linesize[plane]*2,
+                            src[plane], src_linesize[plane]*k, linesize, h);
+    }
+}
+
+static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *picref)
+{
+    AVFilterContext *ctx = inlink->dst;
+    TInterlaceContext *tinterlace = ctx->priv;
+
+    if (tinterlace->cur)
+        avfilter_unref_buffer(tinterlace->cur);
+    tinterlace->cur  = tinterlace->next;
+    tinterlace->next = picref;
+}
+
+static void end_frame(AVFilterLink *inlink)
+{
+    AVFilterContext *ctx = inlink->dst;
+    AVFilterLink *outlink = ctx->outputs[0];
+    TInterlaceContext *tinterlace = ctx->priv;
+    AVFilterBufferRef *cur  = tinterlace->cur;
+    AVFilterBufferRef *next = tinterlace->next;
+    AVFilterBufferRef *out  = NULL;
+
+    /* we need at least two frames */
+    if (!tinterlace->cur)
+        return;
+
+    switch (tinterlace->mode) {
+    case 0: /* Move odd frames into the upper field of the new image, even into
+             * the lower field, generating a double-height video at half framerate */
+        out = avfilter_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
+        avfilter_copy_buffer_ref_props(out, cur);
+        out->video->interlaced = 1;
+        out->video->top_field_first = 1;
+
+        /* write odd frame fields into the upper fields of the new frame */
+        copy_picture_fields(out->data, out->linesize,
+                            cur->data, cur->linesize,
+                            inlink->format, inlink->w, inlink->h,
+                            0, 0, 0);
+        /* and even frame fields into the lower fields of the new frame */
+        copy_picture_fields(out->data, out->linesize,
+                            next->data, next->linesize,
+                            inlink->format, inlink->w, inlink->h,
+                            1, 0, 0);
+        avfilter_unref_buffer(tinterlace->next);
+        tinterlace->next = NULL;
+        break;
+
+    case 1: /* only output odd  frames, even frames are dropped; height unchanged, half framerate */
+    case 2: /* only output even frames, odd  frames are dropped; height unchanged, half framerate */
+        out = avfilter_ref_buffer(tinterlace->mode == 1 ? cur : next,  AV_PERM_READ);
+        avfilter_unref_buffer(tinterlace->next);
+        tinterlace->next = NULL;
+        break;
+
+    case 3: /* Expand each frame to double height, but pad alternate
+             * lines with black; framerate unchanged */
+        out = avfilter_get_video_buffer(outlink,
+                                        AV_PERM_WRITE | AV_PERM_PRESERVE | AV_PERM_REUSE,
+                                        outlink->w, outlink->h);
+        avfilter_copy_buffer_ref_props(out, cur);
+        out->video->interlaced = 1;
+        out->video->top_field_first = tinterlace->nb_frame & 1;
+
+        /* copy higer fields */
+        copy_picture_fields(out->data, out->linesize,
+                            cur->data, cur->linesize,
+                            inlink->format, inlink->w, inlink->h,
+                            0, 0, 0);
+        /* pad with black the destination picture lower fields */
+        copy_picture_fields(out->data, out->linesize,
+                            tinterlace->black_data, tinterlace->black_linesize,
+                            inlink->format, inlink->w, inlink->h,
+                            1, 0, 0);
+        break;
+
+    case 4: /* Interleave even lines from even frames with odd lines from odd frames,
+             * halving the frame rate and preserving image height */
+        out = avfilter_get_video_buffer(outlink,
+                                        AV_PERM_WRITE | AV_PERM_PRESERVE | AV_PERM_REUSE,
+                                        outlink->w, outlink->h);
+        avfilter_copy_buffer_ref_props(out, cur);
+        out->video->interlaced = 1;
+
+        /* copy higer fields from cur */
+        copy_picture_fields(out->data, out->linesize,
+                            cur->data, cur->linesize,
+                            inlink->format, inlink->w, inlink->h,
+                            0, 1, 0);
+        /* copy lower fields from next */
+        copy_picture_fields(out->data, out->linesize,
+                            next->data, next->linesize,
+                            inlink->format, inlink->w, inlink->h,
+                            1, 1, 1);
+        avfilter_unref_buffer(tinterlace->next);
+        tinterlace->next = NULL;
+        break;
+    }
+
+    avfilter_start_frame(outlink, out);
+    avfilter_draw_slice(outlink, 0, outlink->h, 1);
+    avfilter_end_frame(outlink);
+
+    tinterlace->nb_frame++;
+}
+
+static int poll_frame(AVFilterLink *outlink)
+{
+    TInterlaceContext *tinterlace = outlink->src->priv;
+    AVFilterLink *inlink = outlink->src->inputs[0];
+    int ret, val;
+
+    val = avfilter_poll_frame(inlink);
+
+    if (val == 1 && !tinterlace->next) { //FIXME change API to not requre this red tape
+        if ((ret = avfilter_request_frame(inlink)) < 0)
+            return ret;
+        val = avfilter_poll_frame(inlink);
+    }
+    assert(tinterlace->next);
+
+    return val;
+}
+
+static int request_frame(AVFilterLink *outlink)
+{
+    TInterlaceContext *tinterlace = outlink->src->priv;
+    AVFilterLink *inlink = outlink->src->inputs[0];
+
+    do {
+        int ret;
+
+        if ((ret = avfilter_request_frame(inlink)) < 0)
+            return ret;
+    } while (!tinterlace->cur);
+
+    return 0;
+}
+
+static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
+
+AVFilter avfilter_vf_tinterlace = {
+    .name          = "tinterlace",
+    .description   = NULL_IF_CONFIG_SMALL("Perform temporal field interlacing."),
+    .priv_size     = sizeof(TInterlaceContext),
+    .init          = init,
+    .uninit        = uninit,
+    .query_formats = query_formats,
+
+    .inputs    = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO,
+                                    .start_frame      = start_frame,
+                                    .draw_slice       = null_draw_slice,
+                                    .end_frame        = end_frame, },
+                                  { .name = NULL}},
+
+    .outputs   = (AVFilterPad[]) {{ .name             = "default",
+                                    .type             = AVMEDIA_TYPE_VIDEO,
+                                    .config_props     = config_out_props,
+                                    .poll_frame       = poll_frame,
+                                    .request_frame    = request_frame },
+                                  { .name = NULL}},
+};
-- 
1.7.2.5

