]> git.sesse.net Git - vlc/blobdiff - modules/video_filter/deinterlace/deinterlace.c
deinterlace: privatize two functions
[vlc] / modules / video_filter / deinterlace / deinterlace.c
index 202220e07335ae78a735cd6aa2ad3deb853c64d8..4735462fabc2e4c4ab316746b1bc1bb6167cfcaf 100644 (file)
 /*****************************************************************************
  * deinterlace.c : deinterlacer plugin for vlc
  *****************************************************************************
- * Copyright (C) 2000, 2001, 2002, 2003 VideoLAN
- * $Id: deinterlace.c,v 1.12 2003/05/15 22:27:37 massiot Exp $
+ * Copyright (C) 2000-2011 VLC authors and VideoLAN
+ * $Id$
  *
- * Authors: Samuel Hocevar <sam@zoy.org>
+ * Author: Sam Hocevar <sam@zoy.org>
+ *         Christophe Massiot <massiot@via.ecp.fr>
+ *         Laurent Aimar <fenrir@videolan.org>
+ *         Juha Jeronen <juha.jeronen@jyu.fi>
+ *         ...and others
  *
- * This program 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
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation; either version 2.1 of the License, or
  * (at your option) any later version.
  *
  * This program 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.
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
  *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
  *****************************************************************************/
 
 /*****************************************************************************
  * Preamble
  *****************************************************************************/
-#include <errno.h>
-#include <stdlib.h>                                      /* malloc(), free() */
-#include <string.h>
 
-#include <vlc/vlc.h>
-#include <vlc/vout.h>
+#ifdef HAVE_CONFIG_H
+# include "config.h"
+#endif
 
-#include "../filter_common.h"
+#include <assert.h>
+#include <stdint.h>
 
-#define DEINTERLACE_DISCARD 1
-#define DEINTERLACE_MEAN    2
-#define DEINTERLACE_BLEND   3
-#define DEINTERLACE_BOB     4
-#define DEINTERLACE_LINEAR  5
+#include <vlc_common.h>
+#include <vlc_plugin.h>
+#include <vlc_filter.h>
+#include <vlc_cpu.h>
+#include <vlc_mouse.h>
 
-/*****************************************************************************
- * Local protypes
- *****************************************************************************/
-static int  Create    ( vlc_object_t * );
-static void Destroy   ( vlc_object_t * );
-
-static int  Init      ( vout_thread_t * );
-static void End       ( vout_thread_t * );
-static void Render    ( vout_thread_t *, picture_t * );
-
-static void RenderDiscard( vout_thread_t *, picture_t *, picture_t *, int );
-static void RenderBob    ( vout_thread_t *, picture_t *, picture_t *, int );
-static void RenderMean   ( vout_thread_t *, picture_t *, picture_t * );
-static void RenderBlend  ( vout_thread_t *, picture_t *, picture_t * );
-static void RenderLinear ( vout_thread_t *, picture_t *, picture_t *, int );
-
-static void Merge        ( void *, const void *, const void *, size_t );
-
-static int  SendEvents   ( vlc_object_t *, char const *,
-                           vlc_value_t, vlc_value_t, void * );
-
-static void SetFilterMethod( vout_thread_t *p_vout, char *psz_method );
-static vout_thread_t *SpawnRealVout( vout_thread_t *p_vout );
-
-/*****************************************************************************
- * Callback prototypes
- *****************************************************************************/
-static int FilterCallback ( vlc_object_t *, char const *,
-                            vlc_value_t, vlc_value_t, void * );
+#include "deinterlace.h"
+#include "helpers.h"
+#include "merge.h"
 
 /*****************************************************************************
  * Module descriptor
  *****************************************************************************/
-#define MODE_TEXT N_("Deinterlace mode")
-#define MODE_LONGTEXT N_("You can choose the default deinterlace mode")
 
-static char *mode_list[] = { "discard", "blend", "mean", "bob", "linear", NULL };
+#define MODE_TEXT N_("Deinterlace mode")
 
-vlc_module_begin();
-    add_category_hint( N_("Deinterlace"), NULL, VLC_FALSE );
-    add_string_from_list( "deinterlace-mode", "discard", mode_list, NULL,
-                          MODE_TEXT, MODE_LONGTEXT, VLC_FALSE );
-    set_description( _("video deinterlacing filter") );
-    set_capability( "video filter", 0 );
-    add_shortcut( "deinterlace" );
-    set_callbacks( Create, Destroy );
-vlc_module_end();
+#define SOUT_MODE_TEXT N_("Streaming deinterlace mode")
+#define SOUT_MODE_LONGTEXT N_("Deinterlace method to use for streaming.")
+
+#define FILTER_CFG_PREFIX "sout-deinterlace-"
+
+/* Tooltips drop linefeeds (at least in the Qt GUI);
+   thus the space before each set of consecutive \n.
+
+   See phosphor.h for phosphor_chroma_list and phosphor_dimmer_list.
+*/
+#define PHOSPHOR_CHROMA_TEXT N_("Phosphor chroma mode for 4:2:0 input")
+#define PHOSPHOR_CHROMA_LONGTEXT N_("Choose handling for colours in those "\
+                                    "output frames that fall across input "\
+                                    "frame boundaries. \n"\
+                                    "\n"\
+                                    "Latest: take chroma from new (bright) "\
+                                    "field only. Good for interlaced input, "\
+                                    "such as videos from a camcorder. \n"\
+                                    "\n"\
+                                    "AltLine: take chroma line 1 from top "\
+                                    "field, line 2 from bottom field, etc. \n"\
+                                    "Default, good for NTSC telecined input "\
+                                    "(anime DVDs, etc.). \n"\
+                                    "\n"\
+                                    "Blend: average input field chromas. "\
+                                    "May distort the colours of the new "\
+                                    "(bright) field, too. \n"\
+                                    "\n"\
+                                    "Upconvert: output in 4:2:2 format "\
+                                    "(independent chroma for each field). "\
+                                    "Best simulation, but requires more CPU "\
+                                    "and memory bandwidth.")
+
+#define PHOSPHOR_DIMMER_TEXT N_("Phosphor old field dimmer strength")
+#define PHOSPHOR_DIMMER_LONGTEXT N_("This controls the strength of the "\
+                                    "darkening filter that simulates CRT TV "\
+                                    "phosphor light decay for the old field "\
+                                    "in the Phosphor framerate doubler. "\
+                                    "Default: Low.")
+
+vlc_module_begin ()
+    set_description( N_("Deinterlacing video filter") )
+    set_shortname( N_("Deinterlace" ))
+    set_capability( "video filter2", 0 )
+    set_category( CAT_VIDEO )
+    set_subcategory( SUBCAT_VIDEO_VFILTER )
+
+    add_string( FILTER_CFG_PREFIX "mode", "blend", SOUT_MODE_TEXT,
+                SOUT_MODE_LONGTEXT, false )
+        change_string_list( mode_list, mode_list_text )
+        change_safe ()
+    add_integer( FILTER_CFG_PREFIX "phosphor-chroma", 2, PHOSPHOR_CHROMA_TEXT,
+                PHOSPHOR_CHROMA_LONGTEXT, true )
+        change_integer_list( phosphor_chroma_list, phosphor_chroma_list_text )
+        change_safe ()
+    add_integer( FILTER_CFG_PREFIX "phosphor-dimmer", 2, PHOSPHOR_DIMMER_TEXT,
+                PHOSPHOR_DIMMER_LONGTEXT, true )
+        change_integer_list( phosphor_dimmer_list, phosphor_dimmer_list_text )
+        change_safe ()
+    add_shortcut( "deinterlace" )
+    set_callbacks( Open, Close )
+vlc_module_end ()
 
 /*****************************************************************************
- * vout_sys_t: Deinterlace video output method descriptor
- *****************************************************************************
- * This structure is part of the video output thread descriptor.
- * It describes the Deinterlace specific properties of an output thread.
+ * Local data
  *****************************************************************************/
-struct vout_sys_t
-{
-    int        i_mode;        /* Deinterlace mode */
-    vlc_bool_t b_double_rate; /* Shall we double the framerate? */
-
-    mtime_t    last_date;
-    mtime_t    next_date;
 
-    vout_thread_t *p_vout;
-
-    vlc_mutex_t filter_lock;
+/**
+ * Available config options for the deinterlacer module.
+ *
+ * Note that also algorithm-specific options must be listed here,
+ * and reading logic for them implemented in Open().
+ */
+static const char *const ppsz_filter_options[] = {
+    "mode", "phosphor-chroma", "phosphor-dimmer",
+    NULL
 };
 
 /*****************************************************************************
- * Create: allocates Deinterlace video thread output method
- *****************************************************************************
- * This function allocates and initializes a Deinterlace vout method.
+ * SetFilterMethod: setup the deinterlace method to use.
  *****************************************************************************/
-static int Create( vlc_object_t *p_this )
-{
-    vout_thread_t *p_vout = (vout_thread_t *)p_this;
-    vlc_value_t val;
 
-    /* Allocate structure */
-    p_vout->p_sys = malloc( sizeof( vout_sys_t ) );
-    if( p_vout->p_sys == NULL )
-    {
-        msg_Err( p_vout, "out of memory" );
-        return VLC_ENOMEM;
-    }
-
-    p_vout->pf_init = Init;
-    p_vout->pf_end = End;
-    p_vout->pf_manage = NULL;
-    p_vout->pf_render = Render;
-    p_vout->pf_display = NULL;
-
-    p_vout->p_sys->i_mode = DEINTERLACE_DISCARD;
-    p_vout->p_sys->b_double_rate = 0;
-    p_vout->p_sys->last_date = 0;
-    vlc_mutex_init( p_vout, &p_vout->p_sys->filter_lock );
+/**
+ * Setup the deinterlace method to use.
+ *
+ * FIXME: extract i_chroma from p_filter automatically?
+ *
+ * @param p_filter The filter instance.
+ * @param psz_method Desired method. See mode_list for available choices.
+ * @see mode_list
+ */
+static void SetFilterMethod( filter_t *p_filter, const char *psz_method )
+{
+    filter_sys_t *p_sys = p_filter->p_sys;
 
-    /* Look what method was requested */
-    val.psz_string = config_GetPsz( p_vout, "deinterlace-mode" );
+    if( !psz_method )
+        psz_method = "";
 
-    var_Create( p_vout, "deinterlace-mode", VLC_VAR_STRING );
+    p_sys->b_double_rate = false;
+    p_sys->b_half_height = false;
+    p_sys->b_use_frame_history = false;
 
-    if( val.psz_string == NULL )
+    if( !strcmp( psz_method, "mean" ) )
     {
-        msg_Err( p_vout, "configuration variable %s empty",
-                         "deinterlace-mode" );
-        msg_Err( p_vout, "no deinterlace mode provided, using \"discard\"" );
-
-        val.psz_string = strdup( "discard" );
+        p_sys->i_mode = DEINTERLACE_MEAN;
+        p_sys->b_half_height = true;
     }
-
-    var_Set( p_vout, "deinterlace-mode", val );
-
-    SetFilterMethod( p_vout, val.psz_string );
-
-    free( val.psz_string );
-
-    var_AddCallback( p_vout, "deinterlace-mode", FilterCallback, NULL );
-
-    return VLC_SUCCESS;
-}
-
-/*****************************************************************************
- * SetFilterMethod: setup the deinterlace method to use.
- *****************************************************************************/
-static void SetFilterMethod( vout_thread_t *p_vout, char *psz_method )
-{
-    if( !strcmp( psz_method, "discard" ) )
+    else if( !strcmp( psz_method, "bob" )
+             || !strcmp( psz_method, "progressive-scan" ) )
     {
-        p_vout->p_sys->i_mode = DEINTERLACE_DISCARD;
-        p_vout->p_sys->b_double_rate = 0;
+        p_sys->i_mode = DEINTERLACE_BOB;
+        p_sys->b_double_rate = true;
     }
-    else if( !strcmp( psz_method, "mean" ) )
+    else if( !strcmp( psz_method, "linear" ) )
     {
-        p_vout->p_sys->i_mode = DEINTERLACE_MEAN;
-        p_vout->p_sys->b_double_rate = 0;
+        p_sys->i_mode = DEINTERLACE_LINEAR;
+        p_sys->b_double_rate = true;
     }
-    else if( !strcmp( psz_method, "blend" )
-             || !strcmp( psz_method, "average" )
-             || !strcmp( psz_method, "combine-fields" ) )
+    else if( !strcmp( psz_method, "x" ) && p_sys->chroma->pixel_size == 1 )
     {
-        p_vout->p_sys->i_mode = DEINTERLACE_BLEND;
-        p_vout->p_sys->b_double_rate = 0;
+        p_sys->i_mode = DEINTERLACE_X;
     }
-    else if( !strcmp( psz_method, "bob" )
-             || !strcmp( psz_method, "progressive-scan" ) )
+    else if( !strcmp( psz_method, "yadif" ) )
     {
-        p_vout->p_sys->i_mode = DEINTERLACE_BOB;
-        p_vout->p_sys->b_double_rate = 1;
+        p_sys->i_mode = DEINTERLACE_YADIF;
+        p_sys->b_use_frame_history = true;
     }
-    else if( !strcmp( psz_method, "linear" ) )
+    else if( !strcmp( psz_method, "yadif2x" ) )
     {
-        p_vout->p_sys->i_mode = DEINTERLACE_LINEAR;
-        p_vout->p_sys->b_double_rate = 1;
+        p_sys->i_mode = DEINTERLACE_YADIF2X;
+        p_sys->b_double_rate = true;
+        p_sys->b_use_frame_history = true;
     }
-    else
+    else if( !strcmp( psz_method, "phosphor" ) && p_sys->chroma->pixel_size == 1 )
     {
-        msg_Err( p_vout, "no valid deinterlace mode provided, "
-                 "using \"discard\"" );
+        p_sys->i_mode = DEINTERLACE_PHOSPHOR;
+        p_sys->b_double_rate = true;
+        p_sys->b_use_frame_history = true;
     }
-
-    msg_Dbg( p_vout, "using %s deinterlace method", psz_method );
-}
-
-/*****************************************************************************
- * Init: initialize Deinterlace video thread output method
- *****************************************************************************/
-static int Init( vout_thread_t *p_vout )
-{
-    int i_index;
-    picture_t *p_pic;
-
-    I_OUTPUTPICTURES = 0;
-
-    /* Initialize the output structure, full of directbuffers since we want
-     * the decoder to output directly to our structures. */
-    switch( p_vout->render.i_chroma )
-    {
-        case VLC_FOURCC('I','4','2','0'):
-        case VLC_FOURCC('I','Y','U','V'):
-        case VLC_FOURCC('Y','V','1','2'):
-        case VLC_FOURCC('I','4','2','2'):
-            p_vout->output.i_chroma = p_vout->render.i_chroma;
-            p_vout->output.i_width  = p_vout->render.i_width;
-            p_vout->output.i_height = p_vout->render.i_height;
-            p_vout->output.i_aspect = p_vout->render.i_aspect;
-            break;
-
-        default:
-            return VLC_EGENERIC; /* unknown chroma */
-            break;
+    else if( !strcmp( psz_method, "ivtc" ) && p_sys->chroma->pixel_size == 1 )
+    {
+        p_sys->i_mode = DEINTERLACE_IVTC;
+        p_sys->b_use_frame_history = true;
     }
-
-    /* Try to open the real video output */
-    p_vout->p_sys->p_vout = SpawnRealVout( p_vout );
-
-    if( p_vout->p_sys->p_vout == NULL )
+    else if( !strcmp( psz_method, "discard" ) )
     {
-        /* Everything failed */
-        msg_Err( p_vout, "cannot open vout, aborting" );
-
-        return VLC_EGENERIC;
+        p_sys->i_mode = DEINTERLACE_DISCARD;
+        p_sys->b_half_height = true;
     }
+    else
+    {
+        if( strcmp( psz_method, "blend" ) )
+            msg_Err( p_filter,
+                     "no valid/compatible deinterlace mode provided, using \"blend\"" );
 
-    ALLOCATE_DIRECTBUFFERS( VOUT_MAX_PICTURES );
+        p_sys->i_mode = DEINTERLACE_BLEND;
+    }
 
-    ADD_CALLBACKS( p_vout->p_sys->p_vout, SendEvents );
+    p_sys->i_frame_offset = 0; /* reset to default when method changes */
 
-    return VLC_SUCCESS;
+    msg_Dbg( p_filter, "using %s deinterlace method", psz_method );
 }
 
-/*****************************************************************************
- * SpawnRealVout: spawn the real video output.
- *****************************************************************************/
-static vout_thread_t *SpawnRealVout( vout_thread_t *p_vout )
+/**
+ * Get the output video format of the chosen deinterlace method
+ * for the given input video format.
+ *
+ * Note that each algorithm is allowed to specify its output format,
+ * which may (for some input formats) differ from the input format.
+ *
+ * @param p_filter The filter instance.
+ * @param[out] p_dst Output video format. The structure must be allocated by ca
+ * @param[in] p_src Input video format.
+ * @see SetFilterMethod()
+ */
+static void GetOutputFormat( filter_t *p_filter,
+                      video_format_t *p_dst, const video_format_t *p_src )
 {
-    vout_thread_t *p_real_vout = NULL;
-
-    msg_Dbg( p_vout, "spawning the real video output" );
+    filter_sys_t *p_sys = p_filter->p_sys;
+    *p_dst = *p_src;
 
-    switch( p_vout->render.i_chroma )
+    if( p_sys->b_half_height )
     {
-    case VLC_FOURCC('I','4','2','0'):
-    case VLC_FOURCC('I','Y','U','V'):
-    case VLC_FOURCC('Y','V','1','2'):
-        switch( p_vout->p_sys->i_mode )
-        {
-        case DEINTERLACE_MEAN:
-        case DEINTERLACE_DISCARD:
-            p_real_vout =
-                vout_Create( p_vout,
-                       p_vout->output.i_width, p_vout->output.i_height / 2,
-                       p_vout->output.i_chroma, p_vout->output.i_aspect );
-            break;
-
-        case DEINTERLACE_BOB:
-        case DEINTERLACE_BLEND:
-        case DEINTERLACE_LINEAR:
-            p_real_vout =
-                vout_Create( p_vout,
-                       p_vout->output.i_width, p_vout->output.i_height,
-                       p_vout->output.i_chroma, p_vout->output.i_aspect );
-            break;
-        }
-        break;
-
-    case VLC_FOURCC('I','4','2','2'):
-        p_real_vout =
-            vout_Create( p_vout,
-                       p_vout->output.i_width, p_vout->output.i_height,
-                       VLC_FOURCC('I','4','2','0'), p_vout->output.i_aspect );
-        break;
-
-    default:
-        break;
+        p_dst->i_height /= 2;
+        p_dst->i_visible_height /= 2;
+        p_dst->i_y_offset /= 2;
+        p_dst->i_sar_den *= 2;
     }
 
-    return p_real_vout;
-}
-
-/*****************************************************************************
- * End: terminate Deinterlace video thread output method
- *****************************************************************************/
-static void End( vout_thread_t *p_vout )
-{
-    int i_index;
+    if( p_sys->b_double_rate )
+    {
+        p_dst->i_frame_rate *= 2;
+    }
 
-    /* Free the fake output buffers we allocated */
-    for( i_index = I_OUTPUTPICTURES ; i_index ; )
+    if( p_sys->i_mode == DEINTERLACE_PHOSPHOR  &&
+        2 * p_sys->chroma->p[1].h.num == p_sys->chroma->p[1].h.den &&
+        2 * p_sys->chroma->p[2].h.num == p_sys->chroma->p[2].h.den &&
+        p_sys->phosphor.i_chroma_for_420 == PC_UPCONVERT )
     {
-        i_index--;
-        free( PP_OUTPUTPICTURE[ i_index ]->p_data_orig );
+        p_dst->i_chroma = p_src->i_chroma == VLC_CODEC_J420 ? VLC_CODEC_J422 :
+                                                              VLC_CODEC_I422;
     }
+    else
+    {
+        p_dst->i_chroma = p_src->i_chroma;
+    }
+
 }
 
 /*****************************************************************************
- * Destroy: destroy Deinterlace video thread output method
- *****************************************************************************
- * Terminate an output method created by DeinterlaceCreateOutputMethod
+ * video filter2 functions
  *****************************************************************************/
-static void Destroy( vlc_object_t *p_this )
-{
-    vout_thread_t *p_vout = (vout_thread_t *)p_this;
-
-    DEL_CALLBACKS( p_vout->p_sys->p_vout, SendEvents );
-
-    vlc_object_detach( p_vout->p_sys->p_vout );
-    vout_Destroy( p_vout->p_sys->p_vout );
 
-    free( p_vout->p_sys );
-}
+#define DEINTERLACE_DST_SIZE 3
 
-/*****************************************************************************
- * Render: displays previously rendered output
- *****************************************************************************
- * This function send the currently rendered image to Deinterlace image,
- * waits until it is displayed and switch the two rendering buffers, preparing
- * next frame.
- *****************************************************************************/
-static void Render ( vout_thread_t *p_vout, picture_t *p_pic )
+/* This is the filter function. See Open(). */
+picture_t *Deinterlace( filter_t *p_filter, picture_t *p_pic )
 {
-    picture_t *pp_outpic[2];
+    filter_sys_t *p_sys = p_filter->p_sys;
+    picture_t *p_dst[DEINTERLACE_DST_SIZE];
 
-    vlc_mutex_lock( &p_vout->p_sys->filter_lock );
+    /* Request output picture */
+    p_dst[0] = filter_NewPicture( p_filter );
+    if( p_dst[0] == NULL )
+    {
+        picture_Release( p_pic );
+        return NULL;
+    }
+    picture_CopyProperties( p_dst[0], p_pic );
+
+    /* Any unused p_dst pointers must be NULL, because they are used to
+       check how many output frames we have. */
+    for( int i = 1; i < DEINTERLACE_DST_SIZE; ++i )
+        p_dst[i] = NULL;
 
-    /* Get a new picture */
-    while( ( pp_outpic[0] = vout_CreatePicture( p_vout->p_sys->p_vout,
-                                             0, 0, 0 ) )
-              == NULL )
+    /* Update the input frame history, if the currently active algorithm
+       needs it. */
+    if( p_sys->b_use_frame_history )
     {
-        if( p_vout->b_die || p_vout->b_error )
-        {
-            vlc_mutex_unlock( &p_vout->p_sys->filter_lock );
-            return;
-        }
-        msleep( VOUT_OUTMEM_SLEEP );
-     }
+        /* Duplicate the picture
+         * TODO when the vout rework is finished, picture_Hold() might be enough
+         * but becarefull, the pitches must match */
+        picture_t *p_dup = picture_NewFromFormat( &p_pic->format );
+        if( p_dup )
+            picture_Copy( p_dup, p_pic );
+
+        /* Slide the history */
+        if( p_sys->pp_history[0] )
+            picture_Release( p_sys->pp_history[0] );
+        for( int i = 1; i < HISTORY_SIZE; i++ )
+            p_sys->pp_history[i-1] = p_sys->pp_history[i];
+        p_sys->pp_history[HISTORY_SIZE-1] = p_dup;
+    }
 
-    vout_DatePicture( p_vout->p_sys->p_vout, pp_outpic[0], p_pic->date );
+    /* Slide the metadata history. */
+    for( int i = 1; i < METADATA_SIZE; i++ )
+    {
+        p_sys->meta.pi_date[i-1]            = p_sys->meta.pi_date[i];
+        p_sys->meta.pi_nb_fields[i-1]       = p_sys->meta.pi_nb_fields[i];
+        p_sys->meta.pb_top_field_first[i-1] = p_sys->meta.pb_top_field_first[i];
+    }
+    /* The last element corresponds to the current input frame. */
+    p_sys->meta.pi_date[METADATA_SIZE-1]            = p_pic->date;
+    p_sys->meta.pi_nb_fields[METADATA_SIZE-1]       = p_pic->i_nb_fields;
+    p_sys->meta.pb_top_field_first[METADATA_SIZE-1] = p_pic->b_top_field_first;
+
+    /* Remember the frame offset that we should use for this frame.
+       The value in p_sys will be updated to reflect the correct value
+       for the *next* frame when we call the renderer. */
+    int i_frame_offset = p_sys->i_frame_offset;
+    int i_meta_idx     = (METADATA_SIZE-1) - i_frame_offset;
+
+    /* These correspond to the current *outgoing* frame. */
+    bool b_top_field_first;
+    int i_nb_fields;
+    if( i_frame_offset != CUSTOM_PTS )
+    {
+        /* Pick the correct values from the history. */
+        b_top_field_first = p_sys->meta.pb_top_field_first[i_meta_idx];
+        i_nb_fields       = p_sys->meta.pi_nb_fields[i_meta_idx];
+    }
+    else
+    {
+        /* Framerate doublers must not request CUSTOM_PTS, as they need the
+           original field timings, and need Deinterlace() to allocate the
+           correct number of output frames. */
+        assert( !p_sys->b_double_rate );
+
+        /* NOTE: i_nb_fields is only used for framerate doublers, so it is
+                 unused in this case. b_top_field_first is only passed to the
+                 algorithm. We assume that algorithms that request CUSTOM_PTS
+                 will, if necessary, extract the TFF/BFF information themselves.
+        */
+        b_top_field_first = p_pic->b_top_field_first; /* this is not guaranteed
+                                                         to be meaningful */
+        i_nb_fields       = p_pic->i_nb_fields;       /* unused */
+    }
 
-    /* If we are using double rate, get an additional new picture */
-    if( p_vout->p_sys->b_double_rate )
+    /* For framerate doublers, determine field duration and allocate
+       output frames. */
+    mtime_t i_field_dur = 0;
+    int i_double_rate_alloc_end = 0; /* One past last for allocated output
+                                        frames in p_dst[]. Used only for
+                                        framerate doublers. Will be inited
+                                        below. Declared here because the
+                                        PTS logic needs the result. */
+    if( p_sys->b_double_rate )
     {
-        while( ( pp_outpic[1] = vout_CreatePicture( p_vout->p_sys->p_vout,
-                                                 0, 0, 0 ) )
-                  == NULL )
+        /* Calculate one field duration. */
+        int i = 0;
+        int iend = METADATA_SIZE-1;
+        /* Find oldest valid logged date.
+           The current input frame doesn't count. */
+        for( ; i < iend; i++ )
+            if( p_sys->meta.pi_date[i] > VLC_TS_INVALID )
+                break;
+        if( i < iend )
         {
-            if( p_vout->b_die || p_vout->b_error )
-            {
-                vout_DestroyPicture( p_vout->p_sys->p_vout, pp_outpic[0] );
-                vlc_mutex_unlock( &p_vout->p_sys->filter_lock );
-                return;
-            }
-           msleep( VOUT_OUTMEM_SLEEP );
+            /* Count how many fields the valid history entries
+               (except the new frame) represent. */
+            int i_fields_total = 0;
+            for( int j = i ; j < iend; j++ )
+                i_fields_total += p_sys->meta.pi_nb_fields[j];
+            /* One field took this long. */
+            i_field_dur = (p_pic->date - p_sys->meta.pi_date[i]) / i_fields_total;
         }
-
-        /* 20ms is a bit arbitrary, but it's only for the first image we get */
-        if( !p_vout->p_sys->last_date )
+        /* Note that we default to field duration 0 if it could not be
+           determined. This behaves the same as the old code - leaving the
+           extra output frame dates the same as p_pic->date if the last cached
+           date was not valid.
+        */
+
+        i_double_rate_alloc_end = i_nb_fields;
+        if( i_nb_fields > DEINTERLACE_DST_SIZE )
         {
-            vout_DatePicture( p_vout->p_sys->p_vout, pp_outpic[1],
-                              p_pic->date + 20000 );
+            /* Note that the effective buffer size depends also on the constant
+               private_picture in vout_wrapper.c, since that determines the
+               maximum number of output pictures filter_NewPicture() will
+               successfully allocate for one input frame.
+            */
+            msg_Err( p_filter, "Framerate doubler: output buffer too small; "\
+                               "fields = %d, buffer size = %d. Dropping the "\
+                               "remaining fields.",
+                               i_nb_fields, DEINTERLACE_DST_SIZE );
+            i_double_rate_alloc_end = DEINTERLACE_DST_SIZE;
         }
-        else
+
+        /* Allocate output frames. */
+        for( int i = 1; i < i_double_rate_alloc_end ; ++i )
         {
-            vout_DatePicture( p_vout->p_sys->p_vout, pp_outpic[1],
-                      (3 * p_pic->date - p_vout->p_sys->last_date) / 2 );
+            p_dst[i-1]->p_next =
+            p_dst[i]           = filter_NewPicture( p_filter );
+            if( p_dst[i] )
+            {
+                picture_CopyProperties( p_dst[i], p_pic );
+            }
+            else
+            {
+                msg_Err( p_filter, "Framerate doubler: could not allocate "\
+                                   "output frame %d", i+1 );
+                i_double_rate_alloc_end = i; /* Inform the PTS logic about the
+                                                correct end position. */
+                break; /* If this happens, the rest of the allocations
+                          aren't likely to work, either... */
+            }
         }
-        p_vout->p_sys->last_date = p_pic->date;
+        /* Now we have allocated *up to* the correct number of frames;
+           normally, exactly the correct number. Upon alloc failure,
+           we may have succeeded in allocating *some* output frames,
+           but fewer than were desired. In such a case, as many will
+           be rendered as were successfully allocated.
+
+           Note that now p_dst[i] != NULL
+           for 0 <= i < i_double_rate_alloc_end. */
     }
+    assert( p_sys->b_double_rate  ||  p_dst[1] == NULL );
+    assert( i_nb_fields > 2  ||  p_dst[2] == NULL );
 
-    switch( p_vout->p_sys->i_mode )
+    /* Render */
+    switch( p_sys->i_mode )
     {
         case DEINTERLACE_DISCARD:
-            RenderDiscard( p_vout, pp_outpic[0], p_pic, 0 );
-            vout_DisplayPicture( p_vout->p_sys->p_vout, pp_outpic[0] );
+            RenderDiscard( p_dst[0], p_pic, 0 );
             break;
 
         case DEINTERLACE_BOB:
-            RenderBob( p_vout, pp_outpic[0], p_pic, 0 );
-            vout_DisplayPicture( p_vout->p_sys->p_vout, pp_outpic[0] );
-            RenderBob( p_vout, pp_outpic[1], p_pic, 1 );
-            vout_DisplayPicture( p_vout->p_sys->p_vout, pp_outpic[1] );
-            break;
+            RenderBob( p_dst[0], p_pic, !b_top_field_first );
+            if( p_dst[1] )
+                RenderBob( p_dst[1], p_pic, b_top_field_first );
+            if( p_dst[2] )
+                RenderBob( p_dst[2], p_pic, !b_top_field_first );
+            break;;
 
         case DEINTERLACE_LINEAR:
-            RenderLinear( p_vout, pp_outpic[0], p_pic, 0 );
-            vout_DisplayPicture( p_vout->p_sys->p_vout, pp_outpic[0] );
-            RenderLinear( p_vout, pp_outpic[1], p_pic, 1 );
-            vout_DisplayPicture( p_vout->p_sys->p_vout, pp_outpic[1] );
+            RenderLinear( p_filter, p_dst[0], p_pic, !b_top_field_first );
+            if( p_dst[1] )
+                RenderLinear( p_filter, p_dst[1], p_pic, b_top_field_first );
+            if( p_dst[2] )
+                RenderLinear( p_filter, p_dst[2], p_pic, !b_top_field_first );
             break;
 
         case DEINTERLACE_MEAN:
-            RenderMean( p_vout, pp_outpic[0], p_pic );
-            vout_DisplayPicture( p_vout->p_sys->p_vout, pp_outpic[0] );
+            RenderMean( p_filter, p_dst[0], p_pic );
             break;
 
         case DEINTERLACE_BLEND:
-            RenderBlend( p_vout, pp_outpic[0], p_pic );
-            vout_DisplayPicture( p_vout->p_sys->p_vout, pp_outpic[0] );
+            RenderBlend( p_filter, p_dst[0], p_pic );
             break;
-    }
-
-    vlc_mutex_unlock( &p_vout->p_sys->filter_lock );
-}
-
-/*****************************************************************************
- * RenderDiscard: only keep TOP or BOTTOM field, discard the other.
- *****************************************************************************/
-static void RenderDiscard( vout_thread_t *p_vout,
-                           picture_t *p_outpic, picture_t *p_pic, int i_field )
-{
-    int i_plane;
-
-    /* Copy image and skip lines */
-    for( i_plane = 0 ; i_plane < p_pic->i_planes ; i_plane++ )
-    {
-        uint8_t *p_in, *p_out_end, *p_out;
-        int i_increment;
 
-        p_in = p_pic->p[i_plane].p_pixels
-                   + i_field * p_pic->p[i_plane].i_pitch;
-
-        p_out = p_outpic->p[i_plane].p_pixels;
-        p_out_end = p_out + p_outpic->p[i_plane].i_pitch
-                             * p_outpic->p[i_plane].i_lines;
-
-        switch( p_vout->render.i_chroma )
-        {
-        case VLC_FOURCC('I','4','2','0'):
-        case VLC_FOURCC('I','Y','U','V'):
-        case VLC_FOURCC('Y','V','1','2'):
-
-            for( ; p_out < p_out_end ; )
-            {
-                p_vout->p_vlc->pf_memcpy( p_out, p_in,
-                                          p_pic->p[i_plane].i_pitch );
-
-                p_out += p_pic->p[i_plane].i_pitch;
-                p_in += 2 * p_pic->p[i_plane].i_pitch;
-            }
+        case DEINTERLACE_X:
+            RenderX( p_dst[0], p_pic );
             break;
 
-        case VLC_FOURCC('I','4','2','2'):
+        case DEINTERLACE_YADIF:
+            if( RenderYadif( p_filter, p_dst[0], p_pic, 0, 0 ) )
+                goto drop;
+            break;
 
-            i_increment = 2 * p_pic->p[i_plane].i_pitch;
+        case DEINTERLACE_YADIF2X:
+            if( RenderYadif( p_filter, p_dst[0], p_pic, 0, !b_top_field_first ) )
+                goto drop;
+            if( p_dst[1] )
+                RenderYadif( p_filter, p_dst[1], p_pic, 1, b_top_field_first );
+            if( p_dst[2] )
+                RenderYadif( p_filter, p_dst[2], p_pic, 2, !b_top_field_first );
+            break;
 
-            if( i_plane == Y_PLANE )
-            {
-                for( ; p_out < p_out_end ; )
-                {
-                    p_vout->p_vlc->pf_memcpy( p_out, p_in,
-                                              p_pic->p[i_plane].i_pitch );
-                    p_out += p_pic->p[i_plane].i_pitch;
-                    p_vout->p_vlc->pf_memcpy( p_out, p_in,
-                                              p_pic->p[i_plane].i_pitch );
-                    p_out += p_pic->p[i_plane].i_pitch;
-                    p_in += i_increment;
-                }
-            }
-            else
-            {
-                for( ; p_out < p_out_end ; )
-                {
-                    p_vout->p_vlc->pf_memcpy( p_out, p_in,
-                                              p_pic->p[i_plane].i_pitch );
-                    p_out += p_pic->p[i_plane].i_pitch;
-                    p_in += i_increment;
-                }
-            }
+        case DEINTERLACE_PHOSPHOR:
+            if( RenderPhosphor( p_filter, p_dst[0], 0,
+                                !b_top_field_first ) )
+                goto drop;
+            if( p_dst[1] )
+                RenderPhosphor( p_filter, p_dst[1], 1,
+                                b_top_field_first );
+            if( p_dst[2] )
+                RenderPhosphor( p_filter, p_dst[2], 2,
+                                !b_top_field_first );
             break;
 
-        default:
+        case DEINTERLACE_IVTC:
+            /* Note: RenderIVTC will automatically drop the duplicate frames
+                     produced by IVTC. This is part of normal operation. */
+            if( RenderIVTC( p_filter, p_dst[0] ) )
+                goto drop;
             break;
-        }
     }
-}
-
-/*****************************************************************************
- * RenderBob: renders a BOB picture - simple copy
- *****************************************************************************/
-static void RenderBob( vout_thread_t *p_vout,
-                       picture_t *p_outpic, picture_t *p_pic, int i_field )
-{
-    int i_plane;
 
-    /* Copy image and skip lines */
-    for( i_plane = 0 ; i_plane < p_pic->i_planes ; i_plane++ )
+    /* Set output timestamps, if the algorithm didn't request CUSTOM_PTS
+       for this frame. */
+    assert( i_frame_offset <= METADATA_SIZE  ||  i_frame_offset == CUSTOM_PTS );
+    if( i_frame_offset != CUSTOM_PTS )
     {
-        uint8_t *p_in, *p_out_end, *p_out;
+        mtime_t i_base_pts = p_sys->meta.pi_date[i_meta_idx];
 
-        p_in = p_pic->p[i_plane].p_pixels;
-        p_out = p_outpic->p[i_plane].p_pixels;
-        p_out_end = p_out + p_outpic->p[i_plane].i_pitch
-                             * p_outpic->p[i_plane].i_lines;
+        /* Note: in the usual case (i_frame_offset = 0  and
+                 b_double_rate = false), this effectively does nothing.
+                 This is needed to correct the timestamp
+                 when i_frame_offset > 0. */
+        p_dst[0]->date = i_base_pts;
 
-        /* For BOTTOM field we need to add the first line */
-        if( i_field == 1 )
+        if( p_sys->b_double_rate )
         {
-            p_vout->p_vlc->pf_memcpy( p_out, p_in, p_pic->p[i_plane].i_pitch );
-            p_in += p_pic->p[i_plane].i_pitch;
-            p_out += p_pic->p[i_plane].i_pitch;
+            /* Processing all actually allocated output frames. */
+            for( int i = 1; i < i_double_rate_alloc_end; ++i )
+            {
+                /* XXX it's not really good especially for the first picture, but
+                 * I don't think that delaying by one frame is worth it */
+                if( i_base_pts > VLC_TS_INVALID )
+                    p_dst[i]->date = i_base_pts + i * i_field_dur;
+                else
+                    p_dst[i]->date = VLC_TS_INVALID;
+            }
         }
+    }
 
-        p_out_end -= 2 * p_outpic->p[i_plane].i_pitch;
-
-        for( ; p_out < p_out_end ; )
+    for( int i = 0; i < DEINTERLACE_DST_SIZE; ++i )
+    {
+        if( p_dst[i] )
         {
-            p_vout->p_vlc->pf_memcpy( p_out, p_in, p_pic->p[i_plane].i_pitch );
-
-            p_out += p_pic->p[i_plane].i_pitch;
-
-            p_vout->p_vlc->pf_memcpy( p_out, p_in, p_pic->p[i_plane].i_pitch );
-
-            p_in += 2 * p_pic->p[i_plane].i_pitch;
-            p_out += p_pic->p[i_plane].i_pitch;
+            p_dst[i]->b_progressive = true;
+            p_dst[i]->i_nb_fields = 2;
         }
+    }
 
-        p_vout->p_vlc->pf_memcpy( p_out, p_in, p_pic->p[i_plane].i_pitch );
+    picture_Release( p_pic );
+    return p_dst[0];
 
-        /* For TOP field we need to add the last line */
-        if( i_field == 0 )
-        {
-            p_in += p_pic->p[i_plane].i_pitch;
-            p_out += p_pic->p[i_plane].i_pitch;
-            p_vout->p_vlc->pf_memcpy( p_out, p_in, p_pic->p[i_plane].i_pitch );
-        }
+drop:
+    picture_Release( p_dst[0] );
+    for( int i = 1; i < DEINTERLACE_DST_SIZE; ++i )
+    {
+        if( p_dst[i] )
+            picture_Release( p_dst[i] );
     }
+    picture_Release( p_pic );
+    return NULL;
 }
 
 /*****************************************************************************
- * RenderLinear: BOB with linear interpolation
+ * Flush
  *****************************************************************************/
-static void RenderLinear( vout_thread_t *p_vout,
-                          picture_t *p_outpic, picture_t *p_pic, int i_field )
+
+void Flush( filter_t *p_filter )
 {
-    int i_plane;
+    filter_sys_t *p_sys = p_filter->p_sys;
 
-    /* Copy image and skip lines */
-    for( i_plane = 0 ; i_plane < p_pic->i_planes ; i_plane++ )
+    for( int i = 0; i < METADATA_SIZE; i++ )
     {
-        uint8_t *p_in, *p_out_end, *p_out;
-
-        p_in = p_pic->p[i_plane].p_pixels;
-        p_out = p_outpic->p[i_plane].p_pixels;
-        p_out_end = p_out + p_outpic->p[i_plane].i_pitch
-                             * p_outpic->p[i_plane].i_lines;
-
-        /* For BOTTOM field we need to add the first line */
-        if( i_field == 1 )
-        {
-            p_vout->p_vlc->pf_memcpy( p_out, p_in,
-                                      p_pic->p[i_plane].i_pitch );
-            p_in += p_pic->p[i_plane].i_pitch;
-            p_out += p_pic->p[i_plane].i_pitch;
-        }
-
-        p_out_end -= 2 * p_outpic->p[i_plane].i_pitch;
-
-        for( ; p_out < p_out_end ; )
-        {
-            p_vout->p_vlc->pf_memcpy( p_out, p_in,
-                                      p_pic->p[i_plane].i_pitch );
-
-            p_out += p_pic->p[i_plane].i_pitch;
-
-            Merge( p_out, p_in, p_in + 2 * p_pic->p[i_plane].i_pitch,
-                   p_pic->p[i_plane].i_pitch );
-
-            p_in += 2 * p_pic->p[i_plane].i_pitch;
-            p_out += p_pic->p[i_plane].i_pitch;
-        }
-
-        p_vout->p_vlc->pf_memcpy( p_out, p_in,
-                                  p_pic->p[i_plane].i_pitch );
-
-        /* For TOP field we need to add the last line */
-        if( i_field == 0 )
-        {
-            p_in += p_pic->p[i_plane].i_pitch;
-            p_out += p_pic->p[i_plane].i_pitch;
-            p_vout->p_vlc->pf_memcpy( p_out, p_in,
-                                      p_pic->p[i_plane].i_pitch );
-        }
+        p_sys->meta.pi_date[i] = VLC_TS_INVALID;
+        p_sys->meta.pi_nb_fields[i] = 2;
+        p_sys->meta.pb_top_field_first[i] = true;
     }
-}
-
-static void RenderMean( vout_thread_t *p_vout,
-                        picture_t *p_outpic, picture_t *p_pic )
-{
-    int i_plane;
-
-    /* Copy image and skip lines */
-    for( i_plane = 0 ; i_plane < p_pic->i_planes ; i_plane++ )
+    p_sys->i_frame_offset = 0; /* reset to default value (first frame after
+                                  flush cannot have offset) */
+    for( int i = 0; i < HISTORY_SIZE; i++ )
     {
-        uint8_t *p_in, *p_out_end, *p_out;
+        if( p_sys->pp_history[i] )
+            picture_Release( p_sys->pp_history[i] );
+        p_sys->pp_history[i] = NULL;
+    }
+    IVTCClearState( p_filter );
+}
 
-        p_in = p_pic->p[i_plane].p_pixels;
+/*****************************************************************************
+ * Mouse event callback
+ *****************************************************************************/
 
-        p_out = p_outpic->p[i_plane].p_pixels;
-        p_out_end = p_out + p_outpic->p[i_plane].i_pitch
-                             * p_outpic->p[i_plane].i_lines;
+int Mouse( filter_t *p_filter,
+           vlc_mouse_t *p_mouse,
+           const vlc_mouse_t *p_old, const vlc_mouse_t *p_new )
+{
+    VLC_UNUSED(p_old);
+    *p_mouse = *p_new;
+    if( p_filter->p_sys->b_half_height )
+        p_mouse->i_y *= 2;
+    return VLC_SUCCESS;
+}
 
-        /* All lines: mean value */
-        for( ; p_out < p_out_end ; )
-        {
-            Merge( p_out, p_in, p_in + p_pic->p[i_plane].i_pitch,
-                   p_pic->p[i_plane].i_pitch );
 
-            p_out += p_pic->p[i_plane].i_pitch;
-            p_in += 2 * p_pic->p[i_plane].i_pitch;
-        }
-    }
-}
+/*****************************************************************************
+ * Open
+ *****************************************************************************/
 
-static void RenderBlend( vout_thread_t *p_vout,
-                         picture_t *p_outpic, picture_t *p_pic )
+int Open( vlc_object_t *p_this )
 {
-    int i_plane;
+    filter_t *p_filter = (filter_t*)p_this;
+    filter_sys_t *p_sys;
 
-    /* Copy image and skip lines */
-    for( i_plane = 0 ; i_plane < p_pic->i_planes ; i_plane++ )
+    const vlc_fourcc_t fourcc = p_filter->fmt_in.video.i_chroma;
+    const vlc_chroma_description_t *chroma = vlc_fourcc_GetChromaDescription( fourcc );
+    if( !vlc_fourcc_IsYUV( fourcc ) ||
+        !chroma || chroma->plane_count != 3 || chroma->pixel_size > 2 )
     {
-        uint8_t *p_in, *p_out_end, *p_out;
-
-        p_in = p_pic->p[i_plane].p_pixels;
-
-        p_out = p_outpic->p[i_plane].p_pixels;
-        p_out_end = p_out + p_outpic->p[i_plane].i_pitch
-                             * p_outpic->p[i_plane].i_lines;
+        msg_Err( p_filter, "Unsupported chroma (%4.4s)", (char*)&fourcc );
+        return VLC_EGENERIC;
+    }
 
-        /* First line: simple copy */
-        p_vout->p_vlc->pf_memcpy( p_out, p_in,
-                                  p_pic->p[i_plane].i_pitch );
-        p_out += p_pic->p[i_plane].i_pitch;
+    /* */
+    p_sys = p_filter->p_sys = malloc( sizeof( *p_sys ) );
+    if( !p_sys )
+        return VLC_ENOMEM;
 
-        /* Remaining lines: mean value */
-        for( ; p_out < p_out_end ; )
-        {
-            Merge( p_out, p_in, p_in + p_pic->p[i_plane].i_pitch,
-                   p_pic->p[i_plane].i_pitch );
+    config_ChainParse( p_filter, FILTER_CFG_PREFIX, ppsz_filter_options,
+                       p_filter->p_cfg );
+    char *psz_mode = var_InheritString( p_filter, FILTER_CFG_PREFIX "mode" );
+    SetFilterMethod( p_filter, psz_mode );
+    free( psz_mode );
 
-            p_out += p_pic->p[i_plane].i_pitch;
-            p_in += p_pic->p[i_plane].i_pitch;
-        }
+    p_sys->chroma = chroma;
+    for( int i = 0; i < METADATA_SIZE; i++ )
+    {
+        p_sys->meta.pi_date[i] = VLC_TS_INVALID;
+        p_sys->meta.pi_nb_fields[i] = 2;
+        p_sys->meta.pb_top_field_first[i] = true;
     }
-}
+    p_sys->i_frame_offset = 0; /* start with default value (first-ever frame
+                                  cannot have offset) */
+    for( int i = 0; i < HISTORY_SIZE; i++ )
+        p_sys->pp_history[i] = NULL;
 
-static void Merge( void *_p_dest, const void *_p_s1,
-                   const void *_p_s2, size_t i_bytes )
-{
-    uint8_t* p_dest = (uint8_t*)_p_dest;
-    const uint8_t *p_s1 = (const uint8_t *)_p_s1;
-    const uint8_t *p_s2 = (const uint8_t *)_p_s2;
-    uint8_t* p_end = p_dest + i_bytes - 8;
+    IVTCClearState( p_filter );
 
-    while( p_dest < p_end )
+#if defined(CAN_COMPILE_C_ALTIVEC)
+    if( chroma->pixel_size == 1 && vlc_CPU_ALTIVEC() )
+        p_sys->pf_merge = MergeAltivec;
+    else
+#endif
+#if defined(CAN_COMPILE_SSE2)
+    if( vlc_CPU_SSE2() )
     {
-        *p_dest++ = ( (uint16_t)(*p_s1++) + (uint16_t)(*p_s2++) ) >> 1;
-        *p_dest++ = ( (uint16_t)(*p_s1++) + (uint16_t)(*p_s2++) ) >> 1;
-        *p_dest++ = ( (uint16_t)(*p_s1++) + (uint16_t)(*p_s2++) ) >> 1;
-        *p_dest++ = ( (uint16_t)(*p_s1++) + (uint16_t)(*p_s2++) ) >> 1;
-        *p_dest++ = ( (uint16_t)(*p_s1++) + (uint16_t)(*p_s2++) ) >> 1;
-        *p_dest++ = ( (uint16_t)(*p_s1++) + (uint16_t)(*p_s2++) ) >> 1;
-        *p_dest++ = ( (uint16_t)(*p_s1++) + (uint16_t)(*p_s2++) ) >> 1;
-        *p_dest++ = ( (uint16_t)(*p_s1++) + (uint16_t)(*p_s2++) ) >> 1;
+        p_sys->pf_merge = chroma->pixel_size == 1 ? Merge8BitSSE2 : Merge16BitSSE2;
+        p_sys->pf_end_merge = EndMMX;
     }
-
-    p_end += 8;
-
-    while( p_dest < p_end )
+    else
+#endif
+#if defined(CAN_COMPILE_MMXEXT)
+    if( chroma->pixel_size == 1 && vlc_CPU_MMXEXT() )
     {
-        *p_dest++ = ( (uint16_t)(*p_s1++) + (uint16_t)(*p_s2++) ) >> 1;
+        p_sys->pf_merge = MergeMMXEXT;
+        p_sys->pf_end_merge = EndMMX;
     }
-}
-
-/*****************************************************************************
- * SendEvents: forward mouse and keyboard events to the parent p_vout
- *****************************************************************************/
-static int SendEvents( vlc_object_t *p_this, char const *psz_var,
-                       vlc_value_t oldval, vlc_value_t newval, void *_p_vout )
-{
-    vout_thread_t *p_vout = (vout_thread_t *)_p_vout;
-    vlc_value_t sentval = newval;
-
-    if( !strcmp( psz_var, "mouse-y" ) )
+    else
+#endif
+#if defined(CAN_COMPILE_3DNOW)
+    if( chroma->pixel_size == 1 && vlc_CPU_3dNOW() )
     {
-        switch( p_vout->p_sys->i_mode )
-        {
-            case DEINTERLACE_MEAN:
-            case DEINTERLACE_DISCARD:
-                sentval.i_int *= 2;
-                break;
-        }
+        p_sys->pf_merge = Merge3DNow;
+        p_sys->pf_end_merge = End3DNow;
     }
-
-    var_Set( p_vout, psz_var, sentval );
-
-    return VLC_SUCCESS;
-}
-
-/*****************************************************************************
- * FilterCallback: called when changing the deinterlace method on the fly.
- *****************************************************************************/
-static int FilterCallback( vlc_object_t *p_this, char const *psz_cmd,
-                           vlc_value_t oldval, vlc_value_t newval,
-                           void *p_data )
-{
-    vout_thread_t * p_vout = (vout_thread_t *)p_this;
-    int i_old_mode = p_vout->p_sys->i_mode;
-
-    vlc_mutex_lock( &p_vout->p_sys->filter_lock );
-
-    SetFilterMethod( p_vout, newval.psz_string );
-
-    switch( p_vout->render.i_chroma )
+    else
+#endif
+#if defined(CAN_COMPILE_ARM)
+    if( vlc_CPU_ARM_NEON() )
+        p_sys->pf_merge =
+            (chroma->pixel_size == 1) ? merge8_arm_neon : merge16_arm_neon;
+    else
+    if( vlc_CPU_ARMv6() )
+        p_sys->pf_merge =
+            (chroma->pixel_size == 1) ? merge8_armv6 : merge16_armv6;
+    else
+#endif
     {
-    case VLC_FOURCC('I','4','2','2'):
-        vlc_mutex_unlock( &p_vout->p_sys->filter_lock );
-        return VLC_SUCCESS;
-        break;
+        p_sys->pf_merge = chroma->pixel_size == 1 ? Merge8BitGeneric : Merge16BitGeneric;
+#if defined(__i386__) || defined(__x86_64__)
+        p_sys->pf_end_merge = NULL;
+#endif
+    }
 
-    case VLC_FOURCC('I','4','2','0'):
-    case VLC_FOURCC('I','Y','U','V'):
-    case VLC_FOURCC('Y','V','1','2'):
-        switch( p_vout->p_sys->i_mode )
+    /* */
+    if( p_sys->i_mode == DEINTERLACE_PHOSPHOR )
+    {
+        int i_c420 = var_GetInteger( p_filter,
+                                     FILTER_CFG_PREFIX "phosphor-chroma" );
+        if( i_c420 != PC_LATEST  &&  i_c420 != PC_ALTLINE  &&
+            i_c420 != PC_BLEND   && i_c420 != PC_UPCONVERT )
         {
-        case DEINTERLACE_MEAN:
-        case DEINTERLACE_DISCARD:
-            if( ( i_old_mode == DEINTERLACE_MEAN )
-                || ( i_old_mode == DEINTERLACE_DISCARD ) )
-            {
-                vlc_mutex_unlock( &p_vout->p_sys->filter_lock );
-                return VLC_SUCCESS;
-            }
-            break;
-
-        case DEINTERLACE_BOB:
-        case DEINTERLACE_BLEND:
-        case DEINTERLACE_LINEAR:
-            if( ( i_old_mode == DEINTERLACE_BOB )
-                || ( i_old_mode == DEINTERLACE_BLEND )
-                || ( i_old_mode == DEINTERLACE_LINEAR ) )
-            {
-                vlc_mutex_unlock( &p_vout->p_sys->filter_lock );
-                return VLC_SUCCESS;
-            }
-            break;
+            msg_Dbg( p_filter, "Phosphor 4:2:0 input chroma mode not set"\
+                               "or out of range (valid: 1, 2, 3 or 4), "\
+                               "using default" );
+            i_c420 = PC_ALTLINE;
         }
-        break;
-
-    default:
-        break;
+        msg_Dbg( p_filter, "using Phosphor 4:2:0 input chroma mode %d",
+                           i_c420 );
+        /* This maps directly to the phosphor_chroma_t enum. */
+        p_sys->phosphor.i_chroma_for_420 = i_c420;
+
+        int i_dimmer = var_GetInteger( p_filter,
+                                       FILTER_CFG_PREFIX "phosphor-dimmer" );
+        if( i_dimmer < 1  ||  i_dimmer > 4 )
+        {
+            msg_Dbg( p_filter, "Phosphor dimmer strength not set "\
+                               "or out of range (valid: 1, 2, 3 or 4), "\
+                               "using default" );
+            i_dimmer = 2; /* low */
+        }
+        msg_Dbg( p_filter, "using Phosphor dimmer strength %d", i_dimmer );
+        /* The internal value ranges from 0 to 3. */
+        p_sys->phosphor.i_dimmer_strength = i_dimmer - 1;
     }
-
-    /* We need to kill the old vout */
-
-    DEL_CALLBACKS( p_vout->p_sys->p_vout, SendEvents );
-
-    vlc_object_detach( p_vout->p_sys->p_vout );
-    vout_Destroy( p_vout->p_sys->p_vout );
-
-    /* Try to open a new video output */
-    p_vout->p_sys->p_vout = SpawnRealVout( p_vout );
-
-    if( p_vout->p_sys->p_vout == NULL )
+    else
     {
-        /* Everything failed */
-        msg_Err( p_vout, "cannot open vout, aborting" );
+        p_sys->phosphor.i_chroma_for_420 = PC_ALTLINE;
+        p_sys->phosphor.i_dimmer_strength = 1;
+    }
 
-        vlc_mutex_unlock( &p_vout->p_sys->filter_lock );
+    /* */
+    video_format_t fmt;
+    GetOutputFormat( p_filter, &fmt, &p_filter->fmt_in.video );
+    if( !p_filter->b_allow_fmt_out_change &&
+        ( fmt.i_chroma != p_filter->fmt_in.video.i_chroma ||
+          fmt.i_height != p_filter->fmt_in.video.i_height ) )
+    {
+        Close( VLC_OBJECT(p_filter) );
         return VLC_EGENERIC;
     }
+    p_filter->fmt_out.video = fmt;
+    p_filter->fmt_out.i_codec = fmt.i_chroma;
+    p_filter->pf_video_filter = Deinterlace;
+    p_filter->pf_video_flush  = Flush;
+    p_filter->pf_video_mouse  = Mouse;
 
-    ADD_CALLBACKS( p_vout->p_sys->p_vout, SendEvents );
+    msg_Dbg( p_filter, "deinterlacing" );
 
-    vlc_mutex_unlock( &p_vout->p_sys->filter_lock );
     return VLC_SUCCESS;
 }
+
+/*****************************************************************************
+ * Close: clean up the filter
+ *****************************************************************************/
+
+void Close( vlc_object_t *p_this )
+{
+    filter_t *p_filter = (filter_t*)p_this;
+
+    Flush( p_filter );
+    free( p_filter->p_sys );
+}