]> git.sesse.net Git - vlc/blob - src/video_output/video_output.c
Fixed :drop-late-frames= inheritance in vout.
[vlc] / src / video_output / video_output.c
1 /*****************************************************************************
2  * video_output.c : video output thread
3  *
4  * This module describes the programming interface for video output threads.
5  * It includes functions allowing to open a new thread, send pictures to a
6  * thread, and destroy a previously oppened video output thread.
7  *****************************************************************************
8  * Copyright (C) 2000-2007 the VideoLAN team
9  * $Id$
10  *
11  * Authors: Vincent Seguin <seguin@via.ecp.fr>
12  *          Gildas Bazin <gbazin@videolan.org>
13  *          Laurent Aimar <fenrir _AT_ videolan _DOT_ org>
14  *
15  * This program is free software; you can redistribute it and/or modify
16  * it under the terms of the GNU General Public License as published by
17  * the Free Software Foundation; either version 2 of the License, or
18  * (at your option) any later version.
19  *
20  * This program is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23  * GNU General Public License for more details.
24  *
25  * You should have received a copy of the GNU General Public License
26  * along with this program; if not, write to the Free Software
27  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
28  *****************************************************************************/
29
30 /*****************************************************************************
31  * Preamble
32  *****************************************************************************/
33 #ifdef HAVE_CONFIG_H
34 # include "config.h"
35 #endif
36
37 #include <vlc_common.h>
38
39 #include <stdlib.h>                                                /* free() */
40 #include <string.h>
41 #include <assert.h>
42
43 #include <vlc_vout.h>
44
45 #include <vlc_filter.h>
46 #include <vlc_osd.h>
47
48 #include <libvlc.h>
49 #include <vlc_input.h>
50 #include "vout_pictures.h"
51 #include "vout_internal.h"
52
53 /*****************************************************************************
54  * Local prototypes
55  *****************************************************************************/
56 static void     *Thread(void *);
57 static void     vout_Destructor(vlc_object_t *);
58
59 /* Object variables callbacks */
60 static int FilterCallback( vlc_object_t *, char const *,
61                            vlc_value_t, vlc_value_t, void * );
62 static int VideoFilter2Callback( vlc_object_t *, char const *,
63                                  vlc_value_t, vlc_value_t, void * );
64
65 /* */
66 static void PostProcessEnable( vout_thread_t * );
67 static void PostProcessDisable( vout_thread_t * );
68 static void PostProcessSetFilterQuality( vout_thread_t *p_vout );
69 static int  PostProcessCallback( vlc_object_t *, char const *,
70                                  vlc_value_t, vlc_value_t, void * );
71 /* */
72 static void DeinterlaceEnable( vout_thread_t * );
73 static void DeinterlaceNeeded( vout_thread_t *, bool );
74
75 /* Display media title in OSD */
76 static void DisplayTitleOnOSD( vout_thread_t *p_vout );
77
78 /* */
79 static void PrintVideoFormat(vout_thread_t *, const char *, const video_format_t *);
80
81 /* Maximum delay between 2 displayed pictures.
82  * XXX it is needed for now but should be removed in the long term.
83  */
84 #define VOUT_REDISPLAY_DELAY (INT64_C(80000))
85
86 /**
87  * Late pictures having a delay higher than this value are thrashed.
88  */
89 #define VOUT_DISPLAY_LATE_THRESHOLD (INT64_C(20000))
90
91 /* Better be in advance when awakening than late... */
92 #define VOUT_MWAIT_TOLERANCE (INT64_C(1000))
93
94 /*****************************************************************************
95  * Video Filter2 functions
96  *****************************************************************************/
97 static picture_t *video_new_buffer_filter( filter_t *p_filter )
98 {
99     vout_thread_t *p_vout = (vout_thread_t*)p_filter->p_owner;
100     return picture_pool_Get(p_vout->p->private_pool);
101 }
102
103 static void video_del_buffer_filter( filter_t *p_filter, picture_t *p_pic )
104 {
105     VLC_UNUSED(p_filter);
106     picture_Release(p_pic);
107 }
108
109 static int video_filter_buffer_allocation_init( filter_t *p_filter, void *p_data )
110 {
111     p_filter->pf_video_buffer_new = video_new_buffer_filter;
112     p_filter->pf_video_buffer_del = video_del_buffer_filter;
113     p_filter->p_owner = p_data; /* p_vout */
114     return VLC_SUCCESS;
115 }
116
117 #undef vout_Request
118 /*****************************************************************************
119  * vout_Request: find a video output thread, create one, or destroy one.
120  *****************************************************************************
121  * This function looks for a video output thread matching the current
122  * properties. If not found, it spawns a new one.
123  *****************************************************************************/
124 vout_thread_t *vout_Request( vlc_object_t *p_this, vout_thread_t *p_vout,
125                              video_format_t *p_fmt )
126 {
127     if( !p_fmt )
128     {
129         /* Video output is no longer used.
130          * TODO: support for reusing video outputs with proper _thread-safe_
131          * reference handling. */
132         if( p_vout )
133             vout_CloseAndRelease( p_vout );
134         return NULL;
135     }
136
137     /* If a video output was provided, lock it, otherwise look for one. */
138     if( p_vout )
139     {
140         vlc_object_hold( p_vout );
141     }
142
143     /* TODO: find a suitable unused video output */
144
145     /* If we now have a video output, check it has the right properties */
146     if( p_vout )
147     {
148         vlc_mutex_lock( &p_vout->p->change_lock );
149
150         /* We don't directly check for the "vout-filter" variable for obvious
151          * performance reasons. */
152         if( p_vout->p->b_filter_change )
153         {
154             char *psz_filter_chain = var_GetString( p_vout, "vout-filter" );
155
156             if( psz_filter_chain && !*psz_filter_chain )
157             {
158                 free( psz_filter_chain );
159                 psz_filter_chain = NULL;
160             }
161             if( p_vout->p->psz_filter_chain && !*p_vout->p->psz_filter_chain )
162             {
163                 free( p_vout->p->psz_filter_chain );
164                 p_vout->p->psz_filter_chain = NULL;
165             }
166
167             if( !psz_filter_chain && !p_vout->p->psz_filter_chain )
168             {
169                 p_vout->p->b_filter_change = false;
170             }
171
172             free( psz_filter_chain );
173         }
174
175 #warning "FIXME: Check RGB masks in vout_Request"
176         /* FIXME: check RGB masks */
177         if( p_vout->fmt_render.i_chroma != vlc_fourcc_GetCodec( VIDEO_ES, p_fmt->i_chroma ) ||
178             p_vout->fmt_render.i_width != p_fmt->i_width ||
179             p_vout->fmt_render.i_height != p_fmt->i_height ||
180             p_vout->p->b_filter_change )
181         {
182             vlc_mutex_unlock( &p_vout->p->change_lock );
183
184             /* We are not interested in this format, close this vout */
185             vout_CloseAndRelease( p_vout );
186             vlc_object_release( p_vout );
187             p_vout = NULL;
188         }
189         else
190         {
191             /* This video output is cool! Hijack it. */
192             /* Correct aspect ratio on change
193              * FIXME factorize this code with other aspect ration related code */
194             unsigned int i_sar_num;
195             unsigned int i_sar_den;
196             vlc_ureduce( &i_sar_num, &i_sar_den,
197                          p_fmt->i_sar_num, p_fmt->i_sar_den, 50000 );
198 #if 0
199             /* What's that, it does not seems to be used correcly everywhere */
200             if( p_vout->i_par_num > 0 && p_vout->i_par_den > 0 )
201             {
202                 i_sar_num *= p_vout->i_par_den;
203                 i_sar_den *= p_vout->i_par_num;
204             }
205 #endif
206
207             if( i_sar_num > 0 && i_sar_den > 0 &&
208                 ( i_sar_num != p_vout->fmt_render.i_sar_num ||
209                   i_sar_den != p_vout->fmt_render.i_sar_den ) )
210             {
211                 p_vout->fmt_in.i_sar_num = i_sar_num;
212                 p_vout->fmt_in.i_sar_den = i_sar_den;
213
214                 p_vout->fmt_render.i_sar_num = i_sar_num;
215                 p_vout->fmt_render.i_sar_den = i_sar_den;
216                 p_vout->p->i_changes |= VOUT_ASPECT_CHANGE;
217             }
218             vlc_mutex_unlock( &p_vout->p->change_lock );
219
220             vlc_object_release( p_vout );
221         }
222
223         if( p_vout )
224         {
225             msg_Dbg( p_this, "reusing provided vout" );
226
227             spu_Attach( p_vout->p->p_spu, VLC_OBJECT(p_vout), false );
228             vlc_object_detach( p_vout );
229
230             vlc_object_attach( p_vout, p_this );
231             spu_Attach( p_vout->p->p_spu, VLC_OBJECT(p_vout), true );
232         }
233     }
234
235     if( !p_vout )
236     {
237         msg_Dbg( p_this, "no usable vout present, spawning one" );
238
239         p_vout = vout_Create( p_this, p_fmt );
240     }
241
242     return p_vout;
243 }
244
245 /*****************************************************************************
246  * vout_Create: creates a new video output thread
247  *****************************************************************************
248  * This function creates a new video output thread, and returns a pointer
249  * to its description. On error, it returns NULL.
250  *****************************************************************************/
251 vout_thread_t * (vout_Create)( vlc_object_t *p_parent, video_format_t *p_fmt )
252 {
253     vout_thread_t  *p_vout;                            /* thread descriptor */
254     vlc_value_t     text;
255
256
257     config_chain_t *p_cfg;
258     char *psz_parser;
259     char *psz_name;
260
261     if( p_fmt->i_width <= 0 || p_fmt->i_height <= 0 )
262         return NULL;
263     const vlc_fourcc_t i_chroma = vlc_fourcc_GetCodec( VIDEO_ES, p_fmt->i_chroma );
264
265     vlc_ureduce( &p_fmt->i_sar_num, &p_fmt->i_sar_den,
266                  p_fmt->i_sar_num, p_fmt->i_sar_den, 50000 );
267     if( p_fmt->i_sar_num <= 0 || p_fmt->i_sar_den <= 0 )
268         return NULL;
269
270     /* Allocate descriptor */
271     static const char typename[] = "video output";
272     p_vout = vlc_custom_create( p_parent, sizeof( *p_vout ), VLC_OBJECT_VOUT,
273                                 typename );
274     if( p_vout == NULL )
275         return NULL;
276
277     /* */
278     p_vout->p = calloc( 1, sizeof(*p_vout->p) );
279     if( !p_vout->p )
280     {
281         vlc_object_release( p_vout );
282         return NULL;
283     }
284
285     /* */
286     p_vout->fmt_render        = *p_fmt;   /* FIXME palette */
287     p_vout->fmt_in            = *p_fmt;   /* FIXME palette */
288
289     p_vout->fmt_render.i_chroma = 
290     p_vout->fmt_in.i_chroma     = i_chroma;
291     video_format_FixRgb( &p_vout->fmt_render );
292     video_format_FixRgb( &p_vout->fmt_in );
293
294     /* Initialize misc stuff */
295     p_vout->p->i_changes    = 0;
296     p_vout->p->b_fullscreen = 0;
297     vout_chrono_Init( &p_vout->p->render, 5, 10000 ); /* Arbitrary initial time */
298     vout_statistic_Init( &p_vout->p->statistic );
299     p_vout->p->b_filter_change = 0;
300     p_vout->p->i_par_num =
301     p_vout->p->i_par_den = 1;
302     p_vout->p->b_picture_empty = false;
303     p_vout->p->displayed.date = VLC_TS_INVALID;
304     p_vout->p->displayed.decoded = NULL;
305     p_vout->p->displayed.timestamp = VLC_TS_INVALID;
306     p_vout->p->displayed.qtype = QTYPE_NONE;
307     p_vout->p->displayed.is_interlaced = false;
308
309     p_vout->p->step.is_requested = false;
310     p_vout->p->step.last         = VLC_TS_INVALID;
311     p_vout->p->step.timestamp    = VLC_TS_INVALID;
312
313     p_vout->p->pause.is_on  = false;
314     p_vout->p->pause.date   = VLC_TS_INVALID;
315
316     p_vout->p->decoder_fifo = picture_fifo_New();
317     p_vout->p->decoder_pool = NULL;
318
319     vlc_mouse_Init( &p_vout->p->mouse );
320
321     vout_snapshot_Init( &p_vout->p->snapshot );
322
323     /* Initialize locks */
324     vlc_mutex_init( &p_vout->p->picture_lock );
325     vlc_cond_init( &p_vout->p->picture_wait );
326     vlc_mutex_init( &p_vout->p->change_lock );
327     vlc_mutex_init( &p_vout->p->vfilter_lock );
328
329     /* Mouse coordinates */
330     var_Create( p_vout, "mouse-button-down", VLC_VAR_INTEGER );
331     var_Create( p_vout, "mouse-moved", VLC_VAR_COORDS );
332     var_Create( p_vout, "mouse-clicked", VLC_VAR_COORDS );
333     /* Mouse object (area of interest in a video filter) */
334     var_Create( p_vout, "mouse-object", VLC_VAR_BOOL );
335
336     /* Attach the new object now so we can use var inheritance below */
337     vlc_object_attach( p_vout, p_parent );
338
339     /* Initialize subpicture unit */
340     p_vout->p->p_spu = spu_Create( p_vout );
341
342     /* */
343     spu_Init( p_vout->p->p_spu );
344
345     spu_Attach( p_vout->p->p_spu, VLC_OBJECT(p_vout), true );
346
347     p_vout->p->is_late_dropped = var_InheritBool( p_vout, "drop-late-frames" );
348
349     /* Take care of some "interface/control" related initialisations */
350     vout_IntfInit( p_vout );
351
352     /* If the parent is not a VOUT object, that means we are at the start of
353      * the video output pipe */
354     if( vlc_internals( p_parent )->i_object_type != VLC_OBJECT_VOUT )
355     {
356         /* Look for the default filter configuration */
357         p_vout->p->psz_filter_chain =
358             var_CreateGetStringCommand( p_vout, "vout-filter" );
359
360         /* Apply video filter2 objects on the first vout */
361         p_vout->p->psz_vf2 =
362             var_CreateGetStringCommand( p_vout, "video-filter" );
363
364         p_vout->p->b_first_vout = true;
365     }
366     else
367     {
368         /* continue the parent's filter chain */
369         char *psz_tmp;
370
371         /* Ugly hack to jump to our configuration chain */
372         p_vout->p->psz_filter_chain
373             = ((vout_thread_t *)p_parent)->p->psz_filter_chain;
374         p_vout->p->psz_filter_chain
375             = config_ChainCreate( &psz_tmp, &p_cfg, p_vout->p->psz_filter_chain );
376         config_ChainDestroy( p_cfg );
377         free( psz_tmp );
378
379         /* Create a video filter2 var ... but don't inherit values */
380         var_Create( p_vout, "video-filter",
381                     VLC_VAR_STRING | VLC_VAR_ISCOMMAND );
382         p_vout->p->psz_vf2 = var_GetString( p_vout, "video-filter" );
383
384         /* */
385         p_vout->p->b_first_vout = false;
386     }
387
388     var_AddCallback( p_vout, "video-filter", VideoFilter2Callback, NULL );
389     p_vout->p->p_vf2_chain = filter_chain_New( p_vout, "video filter2",
390         false, video_filter_buffer_allocation_init, NULL, p_vout );
391
392     /* Choose the video output module */
393     if( !p_vout->p->psz_filter_chain || !*p_vout->p->psz_filter_chain )
394     {
395         psz_parser = NULL;
396     }
397     else
398     {
399         psz_parser = strdup( p_vout->p->psz_filter_chain );
400         p_vout->p->title.show = false;
401     }
402
403     /* Create the vout thread */
404     char *psz_tmp = config_ChainCreate( &psz_name, &p_cfg, psz_parser );
405     free( psz_parser );
406     free( psz_tmp );
407     p_vout->p->p_cfg = p_cfg;
408
409     /* Create a few object variables for interface interaction */
410     var_Create( p_vout, "vout-filter", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
411     text.psz_string = _("Filters");
412     var_Change( p_vout, "vout-filter", VLC_VAR_SETTEXT, &text, NULL );
413     var_AddCallback( p_vout, "vout-filter", FilterCallback, NULL );
414
415     /* */
416     DeinterlaceEnable( p_vout );
417
418     if( p_vout->p->psz_filter_chain && *p_vout->p->psz_filter_chain )
419     {
420         char *psz_tmp;
421         if( asprintf( &psz_tmp, "%s,none", psz_name ) < 0 )
422             psz_tmp = strdup( "" );
423         free( psz_name );
424         psz_name = psz_tmp;
425     }
426     p_vout->p->psz_module_name = psz_name;
427
428     /* */
429     vlc_object_set_destructor( p_vout, vout_Destructor );
430
431     /* */
432     vlc_cond_init( &p_vout->p->change_wait );
433     if( vlc_clone( &p_vout->p->thread, Thread, p_vout,
434                    VLC_THREAD_PRIORITY_OUTPUT ) )
435     {
436         spu_Attach( p_vout->p->p_spu, VLC_OBJECT(p_vout), false );
437         spu_Destroy( p_vout->p->p_spu );
438         p_vout->p->p_spu = NULL;
439         vlc_object_release( p_vout );
440         return NULL;
441     }
442
443     vlc_mutex_lock( &p_vout->p->change_lock );
444     while( !p_vout->p->b_ready )
445     {   /* We are (ab)using the same condition in opposite directions for
446          * b_ready and b_done. This works because of the strict ordering. */
447         assert( !p_vout->p->b_done );
448         vlc_cond_wait( &p_vout->p->change_wait, &p_vout->p->change_lock );
449     }
450     vlc_mutex_unlock( &p_vout->p->change_lock );
451
452     if( p_vout->p->b_error )
453     {
454         msg_Err( p_vout, "video output creation failed" );
455         vout_CloseAndRelease( p_vout );
456         return NULL;
457     }
458
459     return p_vout;
460 }
461
462 /*****************************************************************************
463  * vout_Close: Close a vout created by vout_Create.
464  *****************************************************************************
465  * You HAVE to call it on vout created by vout_Create before vlc_object_release.
466  * You should NEVER call it on vout not obtained through vout_Create
467  * (like with vout_Request or vlc_object_find.)
468  * You can use vout_CloseAndRelease() as a convenience method.
469  *****************************************************************************/
470 void vout_Close( vout_thread_t *p_vout )
471 {
472     assert( p_vout );
473
474     vlc_mutex_lock( &p_vout->p->change_lock );
475     p_vout->p->b_done = true;
476     vlc_cond_signal( &p_vout->p->change_wait );
477     vlc_mutex_unlock( &p_vout->p->change_lock );
478
479     vout_snapshot_End( &p_vout->p->snapshot );
480
481     vlc_join( p_vout->p->thread, NULL );
482 }
483
484 /* */
485 static void vout_Destructor( vlc_object_t * p_this )
486 {
487     vout_thread_t *p_vout = (vout_thread_t *)p_this;
488
489     /* Make sure the vout was stopped first */
490     //assert( !p_vout->p_module );
491
492     free( p_vout->p->psz_module_name );
493
494     /* */
495     if( p_vout->p->p_spu )
496         spu_Destroy( p_vout->p->p_spu );
497
498     vout_chrono_Clean( &p_vout->p->render );
499
500     if( p_vout->p->decoder_fifo )
501         picture_fifo_Delete( p_vout->p->decoder_fifo );
502     assert( !p_vout->p->decoder_pool );
503
504     /* Destroy the locks */
505     vlc_cond_destroy( &p_vout->p->change_wait );
506     vlc_cond_destroy( &p_vout->p->picture_wait );
507     vlc_mutex_destroy( &p_vout->p->picture_lock );
508     vlc_mutex_destroy( &p_vout->p->change_lock );
509     vlc_mutex_destroy( &p_vout->p->vfilter_lock );
510
511     /* */
512     vout_statistic_Clean( &p_vout->p->statistic );
513
514     /* */
515     vout_snapshot_Clean( &p_vout->p->snapshot );
516
517     /* */
518     free( p_vout->p->psz_filter_chain );
519     free( p_vout->p->title.value );
520
521     config_ChainDestroy( p_vout->p->p_cfg );
522
523     free( p_vout->p );
524
525 }
526
527 /* */
528 void vout_ChangePause( vout_thread_t *p_vout, bool b_paused, mtime_t i_date )
529 {
530     vlc_mutex_lock( &p_vout->p->change_lock );
531
532     assert( !p_vout->p->pause.is_on || !b_paused );
533
534     vlc_mutex_lock( &p_vout->p->picture_lock );
535
536     if( p_vout->p->pause.is_on )
537     {
538         const mtime_t i_duration = i_date - p_vout->p->pause.date;
539
540         if (p_vout->p->step.timestamp > VLC_TS_INVALID)
541             p_vout->p->step.timestamp += i_duration;
542         if (!b_paused)
543             p_vout->p->step.last = p_vout->p->step.timestamp;
544         picture_fifo_OffsetDate( p_vout->p->decoder_fifo, i_duration );
545         if (p_vout->p->displayed.decoded)
546             p_vout->p->displayed.decoded->date += i_duration;
547
548         vlc_cond_signal( &p_vout->p->picture_wait );
549         vlc_mutex_unlock( &p_vout->p->picture_lock );
550
551         spu_OffsetSubtitleDate( p_vout->p->p_spu, i_duration );
552     }
553     else
554     {
555         if (b_paused)
556             p_vout->p->step.last = p_vout->p->step.timestamp;
557         vlc_mutex_unlock( &p_vout->p->picture_lock );
558     }
559     p_vout->p->pause.is_on = b_paused;
560     p_vout->p->pause.date  = i_date;
561
562     vlc_mutex_unlock( &p_vout->p->change_lock );
563 }
564
565 void vout_GetResetStatistic( vout_thread_t *p_vout, int *pi_displayed, int *pi_lost )
566 {
567     vout_statistic_GetReset( &p_vout->p->statistic,
568                              pi_displayed, pi_lost );
569 }
570
571 static void Flush(vout_thread_t *vout, mtime_t date, bool reset, bool below)
572 {
573     vlc_assert_locked(&vout->p->picture_lock);
574     vout->p->step.timestamp = VLC_TS_INVALID;
575     vout->p->step.last      = VLC_TS_INVALID;
576
577     picture_t *last = vout->p->displayed.decoded;
578     if (last) {
579         if (reset) {
580             picture_Release(last);
581             vout->p->displayed.decoded = NULL;
582         } else if (( below  && last->date <= date) ||
583                    (!below && last->date >= date)) {
584             vout->p->step.is_requested = true;
585         }
586     }
587     picture_fifo_Flush( vout->p->decoder_fifo, date, below );
588 }
589
590 void vout_Flush(vout_thread_t *vout, mtime_t date)
591 {
592     vlc_mutex_lock(&vout->p->picture_lock);
593
594     Flush(vout, date, false, false);
595
596     vlc_cond_signal(&vout->p->picture_wait);
597     vlc_mutex_unlock(&vout->p->picture_lock);
598 }
599
600 void vout_Reset(vout_thread_t *vout)
601 {
602     vlc_mutex_lock(&vout->p->picture_lock);
603
604     Flush(vout, INT64_MAX, true, true);
605     if (vout->p->decoder_pool)
606         picture_pool_NonEmpty(vout->p->decoder_pool, true);
607     vout->p->pause.is_on = false;
608     vout->p->pause.date  = mdate();
609
610     vlc_cond_signal( &vout->p->picture_wait );
611     vlc_mutex_unlock(&vout->p->picture_lock);
612 }
613
614 void vout_FixLeaks( vout_thread_t *vout )
615 {
616     vlc_mutex_lock(&vout->p->picture_lock);
617
618     picture_t *picture = picture_fifo_Peek(vout->p->decoder_fifo);
619     if (!picture) {
620         picture = picture_pool_Get(vout->p->decoder_pool);
621     }
622
623     if (picture) {
624         picture_Release(picture);
625         /* Not all pictures has been displayed yet or some are
626          * free */
627         vlc_mutex_unlock(&vout->p->picture_lock);
628         return;
629     }
630
631     /* There is no reason that no pictures are available, force one
632      * from the pool, becarefull with it though */
633     msg_Err(vout, "pictures leaked, trying to workaround");
634
635     /* */
636     picture_pool_NonEmpty(vout->p->decoder_pool, false);
637
638     vlc_cond_signal(&vout->p->picture_wait);
639     vlc_mutex_unlock(&vout->p->picture_lock);
640 }
641 void vout_NextPicture(vout_thread_t *vout, mtime_t *duration)
642 {
643     vlc_mutex_lock(&vout->p->picture_lock);
644
645     vout->p->b_picture_empty = false;
646     vout->p->step.is_requested = true;
647
648     /* FIXME I highly doubt that it can works with only one cond_t FIXME */
649     vlc_cond_signal(&vout->p->picture_wait);
650
651     while (vout->p->step.is_requested && !vout->p->b_picture_empty)
652         vlc_cond_wait(&vout->p->picture_wait, &vout->p->picture_lock);
653
654     if (vout->p->step.last > VLC_TS_INVALID &&
655         vout->p->step.timestamp > vout->p->step.last) {
656         *duration = vout->p->step.timestamp - vout->p->step.last;
657         vout->p->step.last = vout->p->step.timestamp;
658     } else {
659         *duration = 0;
660     }
661
662     /* TODO advance subpicture by the duration ... */
663     vlc_mutex_unlock(&vout->p->picture_lock);
664 }
665
666 void vout_DisplayTitle( vout_thread_t *p_vout, const char *psz_title )
667 {
668     assert( psz_title );
669
670     if( !var_InheritBool( p_vout, "osd" ) )
671         return;
672
673     vlc_mutex_lock( &p_vout->p->change_lock );
674     free( p_vout->p->title.value );
675     p_vout->p->title.value = strdup( psz_title );
676     vlc_mutex_unlock( &p_vout->p->change_lock );
677 }
678
679 spu_t *vout_GetSpu( vout_thread_t *p_vout )
680 {
681     return p_vout->p->p_spu;
682 }
683
684 /*****************************************************************************
685  * InitThread: initialize video output thread
686  *****************************************************************************
687  * This function is called from Thread and performs the second step of the
688  * initialization. It returns 0 on success. Note that the thread's flag are not
689  * modified inside this function.
690  * XXX You have to enter it with change_lock taken.
691  *****************************************************************************/
692 static int ThreadInit(vout_thread_t *vout)
693 {
694     /* Initialize output method, it allocates direct buffers for us */
695     if (vout_InitWrapper(vout))
696         return VLC_EGENERIC;
697     assert(vout->p->decoder_pool);
698
699     vout->p->displayed.decoded = NULL;
700
701     /* print some usefull debug info about different vout formats
702      */
703     PrintVideoFormat(vout, "pic render", &vout->fmt_render);
704     PrintVideoFormat(vout, "pic in",     &vout->fmt_in);
705     PrintVideoFormat(vout, "pic out",    &vout->fmt_out);
706
707     assert(vout->fmt_out.i_width  == vout->fmt_render.i_width &&
708            vout->fmt_out.i_height == vout->fmt_render.i_height &&
709            vout->fmt_out.i_chroma == vout->fmt_render.i_chroma);
710     return VLC_SUCCESS;
711 }
712
713 /*****************************************************************************
714  * CleanThread: clean up after InitThread
715  *****************************************************************************
716  * This function is called after a sucessful
717  * initialization. It frees all resources allocated by InitThread.
718  * XXX You have to enter it with change_lock taken.
719  *****************************************************************************/
720 static void ThreadClean(vout_thread_t *vout)
721 {
722     /* Destroy translation tables */
723     if (!vout->p->b_error) {
724         picture_fifo_Flush(vout->p->decoder_fifo, INT64_MAX, false);
725         vout_EndWrapper(vout);
726     }
727 }
728
729 static int ThreadDisplayPicture(vout_thread_t *vout,
730                                 bool now, mtime_t *deadline)
731 {
732     int displayed_count = 0;
733     int lost_count = 0;
734
735     for (;;) {
736         const mtime_t date = mdate();
737         const bool is_paused = vout->p->pause.is_on;
738         bool redisplay = is_paused && !now;
739         bool is_forced;
740
741         /* FIXME/XXX we must redisplay the last decoded picture (because
742          * of potential vout updated, or filters update or SPU update)
743          * For now a high update period is needed but it coulmd be removed
744          * if and only if:
745          * - vout module emits events from theselves.
746          * - *and* SPU is modified to emit an event or a deadline when needed.
747          *
748          * So it will be done latter.
749          */
750         if (!redisplay) {
751             picture_t *peek = picture_fifo_Peek(vout->p->decoder_fifo);
752             if (peek) {
753                 is_forced = peek->b_force || is_paused || now;
754                 *deadline = (is_forced ? date : peek->date) - vout_chrono_GetHigh(&vout->p->render);
755                 picture_Release(peek);
756             } else {
757                 redisplay = true;
758             }
759         }
760         if (redisplay) {
761              /* FIXME a better way for this delay is needed */
762             const mtime_t date_update = vout->p->displayed.date + VOUT_REDISPLAY_DELAY;
763             if (date_update > date || !vout->p->displayed.decoded) {
764                 *deadline = vout->p->displayed.decoded ? date_update : VLC_TS_INVALID;
765                 break;
766             }
767             /* */
768             is_forced = true;
769             *deadline = date - vout_chrono_GetHigh(&vout->p->render);
770         }
771         if (*deadline > VOUT_MWAIT_TOLERANCE)
772             *deadline -= VOUT_MWAIT_TOLERANCE;
773
774         /* If we are too early and can wait, do it */
775         if (date < *deadline && !now)
776             break;
777
778         picture_t *decoded;
779         if (redisplay) {
780             decoded = vout->p->displayed.decoded;
781             vout->p->displayed.decoded = NULL;
782         } else {
783             decoded = picture_fifo_Pop(vout->p->decoder_fifo);
784             assert(decoded);
785             if (!is_forced && !vout->p->is_late_dropped) {
786                 const mtime_t predicted = date + vout_chrono_GetLow(&vout->p->render);
787                 const mtime_t late = predicted - decoded->date;
788                 if (late > 0) {
789                     msg_Dbg(vout, "picture might be displayed late (missing %d ms)", (int)(late/1000));
790                     if (late > VOUT_DISPLAY_LATE_THRESHOLD) {
791                         msg_Warn(vout, "rejected picture because of render time");
792                         /* TODO */
793                         picture_Release(decoded);
794                         lost_count++;
795                         break;
796                     }
797                 }
798             }
799
800             vout->p->displayed.is_interlaced = !decoded->b_progressive;
801             vout->p->displayed.qtype         = decoded->i_qtype;
802         }
803         vout->p->displayed.timestamp = decoded->date;
804
805         /* */
806         if (vout->p->displayed.decoded)
807             picture_Release(vout->p->displayed.decoded);
808         picture_Hold(decoded);
809         vout->p->displayed.decoded = decoded;
810
811         /* */
812         vout_chrono_Start(&vout->p->render);
813
814         picture_t *filtered = NULL;
815         if (decoded) {
816             vlc_mutex_lock(&vout->p->vfilter_lock);
817             filtered = filter_chain_VideoFilter(vout->p->p_vf2_chain, decoded);
818             //assert(filtered == decoded); // TODO implement
819             vlc_mutex_unlock(&vout->p->vfilter_lock);
820             if (!filtered)
821                 continue;
822         }
823
824         /*
825          * Check for subpictures to display
826          */
827         const bool do_snapshot = vout_snapshot_IsRequested(&vout->p->snapshot);
828         mtime_t spu_render_time = is_forced ? mdate() : filtered->date;
829         if (vout->p->pause.is_on)
830             spu_render_time = vout->p->pause.date;
831         else
832             spu_render_time = filtered->date > 1 ? filtered->date : mdate();
833
834         subpicture_t *subpic = spu_SortSubpictures(vout->p->p_spu,
835                                                    spu_render_time,
836                                                    do_snapshot);
837         /*
838          * Perform rendering
839          *
840          * We have to:
841          * - be sure to end up with a direct buffer.
842          * - blend subtitles, and in a fast access buffer
843          */
844         picture_t *direct = NULL;
845         if (filtered &&
846             (vout->p->decoder_pool != vout->p->display_pool || subpic)) {
847             picture_t *render;
848             if (vout->p->is_decoder_pool_slow)
849                 render = picture_NewFromFormat(&vout->fmt_out);
850             else if (vout->p->decoder_pool != vout->p->display_pool)
851                 render = picture_pool_Get(vout->p->display_pool);
852             else
853                 render = picture_pool_Get(vout->p->private_pool);
854
855             if (render) {
856                 picture_Copy(render, filtered);
857
858                 spu_RenderSubpictures(vout->p->p_spu,
859                                       render, &vout->fmt_out,
860                                       subpic, &vout->fmt_in, spu_render_time);
861             }
862             if (vout->p->is_decoder_pool_slow) {
863                 direct = picture_pool_Get(vout->p->display_pool);
864                 if (direct)
865                     picture_Copy(direct, render);
866                 picture_Release(render);
867
868             } else {
869                 direct = render;
870             }
871             picture_Release(filtered);
872             filtered = NULL;
873         } else {
874             direct = filtered;
875         }
876
877         /*
878          * Take a snapshot if requested
879          */
880         if (direct && do_snapshot)
881             vout_snapshot_Set(&vout->p->snapshot, &vout->fmt_out, direct);
882
883         /* Render the direct buffer returned by vout_RenderPicture */
884         if (direct) {
885             vout_RenderWrapper(vout, direct);
886
887             vout_chrono_Stop(&vout->p->render);
888 #if 0
889             {
890             static int i = 0;
891             if (((i++)%10) == 0)
892                 msg_Info(vout, "render: avg %d ms var %d ms",
893                          (int)(vout->p->render.avg/1000), (int)(vout->p->render.var/1000));
894             }
895 #endif
896         }
897
898         /* Wait the real date (for rendering jitter) */
899         if (!is_forced)
900             mwait(decoded->date);
901
902         /* Display the direct buffer returned by vout_RenderPicture */
903         vout->p->displayed.date = mdate();
904         if (direct)
905             vout_DisplayWrapper(vout, direct);
906
907         displayed_count++;
908         break;
909     }
910
911     vout_statistic_Update(&vout->p->statistic, displayed_count, lost_count);
912     if (displayed_count <= 0)
913         return VLC_EGENERIC;
914     return VLC_SUCCESS;
915 }
916
917 /*****************************************************************************
918  * Thread: video output thread
919  *****************************************************************************
920  * Video output thread. This function does only returns when the thread is
921  * terminated. It handles the pictures arriving in the video heap and the
922  * display device events.
923  *****************************************************************************/
924 static void *Thread(void *object)
925 {
926     vout_thread_t *vout = object;
927     bool          has_wrapper;
928
929     /*
930      * Initialize thread
931      */
932     has_wrapper = !vout_OpenWrapper(vout, vout->p->psz_module_name);
933
934     vlc_mutex_lock(&vout->p->change_lock);
935
936     if (has_wrapper)
937         vout->p->b_error = ThreadInit(vout);
938     else
939         vout->p->b_error = true;
940
941     /* signal the creation of the vout */
942     vout->p->b_ready = true;
943     vlc_cond_signal(&vout->p->change_wait);
944
945     if (vout->p->b_error)
946         goto exit_thread;
947
948     /* */
949     bool    last_picture_interlaced      = false;
950     int     last_picture_qtype           = QTYPE_NONE;
951     mtime_t last_picture_interlaced_date = mdate();
952
953     /*
954      * Main loop - it is not executed if an error occurred during
955      * initialization
956      */
957     while (!vout->p->b_done && !vout->p->b_error) {
958         /* */
959         if(vout->p->title.show && vout->p->title.value)
960             DisplayTitleOnOSD(vout);
961
962         vlc_mutex_lock(&vout->p->picture_lock);
963
964         mtime_t deadline = VLC_TS_INVALID;
965         bool has_displayed = !ThreadDisplayPicture(vout, vout->p->step.is_requested, &deadline);
966
967         if (has_displayed) {
968             vout->p->step.timestamp = vout->p->displayed.timestamp;
969             if (vout->p->step.last <= VLC_TS_INVALID)
970                 vout->p->step.last = vout->p->step.timestamp;
971         }
972         if (vout->p->step.is_requested) {
973             if (!has_displayed && !vout->p->b_picture_empty) {
974                 picture_t *peek = picture_fifo_Peek(vout->p->decoder_fifo);
975                 if (peek)
976                     picture_Release(peek);
977                 if (!peek) {
978                     vout->p->b_picture_empty = true;
979                     vlc_cond_signal(&vout->p->picture_wait);
980                 }
981             }
982             if (has_displayed) {
983                 vout->p->step.is_requested = false;
984                 vlc_cond_signal(&vout->p->picture_wait);
985             }
986         }
987
988         const int  picture_qtype      = vout->p->displayed.qtype;
989         const bool picture_interlaced = vout->p->displayed.is_interlaced;
990
991         vlc_mutex_unlock(&vout->p->picture_lock);
992
993         if (vout_ManageWrapper(vout)) {
994             /* A fatal error occurred, and the thread must terminate
995              * immediately, without displaying anything - setting b_error to 1
996              * causes the immediate end of the main while() loop. */
997             // FIXME pf_end
998             vout->p->b_error = true;
999             break;
1000         }
1001
1002         /* Post processing */
1003         const int postproc_change = (picture_qtype != QTYPE_NONE) - (last_picture_qtype != QTYPE_NONE);
1004         if (postproc_change == 1)
1005             PostProcessEnable(vout);
1006         else if (postproc_change == -1)
1007             PostProcessDisable(vout);
1008         if (postproc_change)
1009             last_picture_qtype = picture_qtype;
1010
1011         /* Deinterlacing
1012          * Wait 30s before quiting interlacing mode */
1013         const int interlacing_change = (!!picture_interlaced) - (!!last_picture_interlaced);
1014         if ((interlacing_change == 1) ||
1015             (interlacing_change == -1 && last_picture_interlaced_date + 30000000 < mdate())) {
1016             DeinterlaceNeeded(vout, picture_interlaced);
1017             last_picture_interlaced = picture_interlaced;
1018         }
1019         if (picture_interlaced)
1020             last_picture_interlaced_date = mdate();
1021
1022         /* Check for "video filter2" changes */
1023         vlc_mutex_lock(&vout->p->vfilter_lock);
1024         if (vout->p->psz_vf2) {
1025             es_format_t fmt;
1026
1027             es_format_Init(&fmt, VIDEO_ES, vout->fmt_render.i_chroma);
1028             fmt.video = vout->fmt_render;
1029             filter_chain_Reset(vout->p->p_vf2_chain, &fmt, &fmt);
1030
1031             if (filter_chain_AppendFromString(vout->p->p_vf2_chain,
1032                                               vout->p->psz_vf2) < 0)
1033                 msg_Err(vout, "Video filter chain creation failed");
1034
1035             free(vout->p->psz_vf2);
1036             vout->p->psz_vf2 = NULL;
1037
1038             if (last_picture_qtype != QTYPE_NONE)
1039                 PostProcessSetFilterQuality(vout);
1040         }
1041         vlc_mutex_unlock(&vout->p->vfilter_lock);
1042
1043         vlc_mutex_unlock(&vout->p->change_lock);
1044
1045         if (deadline > VLC_TS_INVALID) {
1046             vlc_mutex_lock(&vout->p->picture_lock);
1047             vlc_cond_timedwait(&vout->p->picture_wait, &vout->p->picture_lock, deadline);
1048             vlc_mutex_unlock(&vout->p->picture_lock);
1049         }
1050
1051         vlc_mutex_lock(&vout->p->change_lock);
1052     }
1053
1054     /*
1055      * Error loop - wait until the thread destruction is requested
1056      *
1057      * XXX I wonder if we should periodically clean the decoder_fifo
1058      * or have a way to prevent it filling up.
1059      */
1060     while (vout->p->b_error && !vout->p->b_done)
1061         vlc_cond_wait(&vout->p->change_wait, &vout->p->change_lock);
1062
1063     /* Clean thread */
1064     ThreadClean(vout);
1065
1066 exit_thread:
1067     /* Detach subpicture unit from both input and vout */
1068     spu_Attach(vout->p->p_spu, VLC_OBJECT(vout), false);
1069     vlc_object_detach(vout->p->p_spu);
1070
1071     /* Destroy the video filters2 */
1072     filter_chain_Delete(vout->p->p_vf2_chain);
1073
1074     vlc_mutex_unlock(&vout->p->change_lock);
1075
1076     if (has_wrapper)
1077         vout_CloseWrapper(vout);
1078
1079     return NULL;
1080 }
1081
1082 /*****************************************************************************
1083  * object variables callbacks: a bunch of object variables are used by the
1084  * interfaces to interact with the vout.
1085  *****************************************************************************/
1086 static int FilterCallback( vlc_object_t *p_this, char const *psz_cmd,
1087                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
1088 {
1089     vout_thread_t *p_vout = (vout_thread_t *)p_this;
1090     input_thread_t *p_input;
1091     (void)psz_cmd; (void)oldval; (void)p_data;
1092
1093     p_input = (input_thread_t *)vlc_object_find( p_this, VLC_OBJECT_INPUT,
1094                                                  FIND_PARENT );
1095     if (!p_input)
1096     {
1097         msg_Err( p_vout, "Input not found" );
1098         return VLC_EGENERIC;
1099     }
1100
1101     var_SetBool( p_vout, "intf-change", true );
1102
1103     /* Modify input as well because the vout might have to be restarted */
1104     var_Create( p_input, "vout-filter", VLC_VAR_STRING );
1105     var_SetString( p_input, "vout-filter", newval.psz_string );
1106
1107     /* Now restart current video stream */
1108     input_Control( p_input, INPUT_RESTART_ES, -VIDEO_ES );
1109     vlc_object_release( p_input );
1110
1111     return VLC_SUCCESS;
1112 }
1113
1114 /*****************************************************************************
1115  * Video Filter2 stuff
1116  *****************************************************************************/
1117 static int VideoFilter2Callback( vlc_object_t *p_this, char const *psz_cmd,
1118                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
1119 {
1120     vout_thread_t *p_vout = (vout_thread_t *)p_this;
1121     (void)psz_cmd; (void)oldval; (void)p_data;
1122
1123     vlc_mutex_lock( &p_vout->p->vfilter_lock );
1124     p_vout->p->psz_vf2 = strdup( newval.psz_string );
1125     vlc_mutex_unlock( &p_vout->p->vfilter_lock );
1126
1127     return VLC_SUCCESS;
1128 }
1129
1130 /*****************************************************************************
1131  * Post-processing
1132  *****************************************************************************/
1133 static bool PostProcessIsPresent( const char *psz_filter )
1134 {
1135     const char  *psz_pp = "postproc";
1136     const size_t i_pp = strlen(psz_pp);
1137     return psz_filter &&
1138            !strncmp( psz_filter, psz_pp, strlen(psz_pp) ) &&
1139            ( psz_filter[i_pp] == '\0' || psz_filter[i_pp] == ':' );
1140 }
1141
1142 static int PostProcessCallback( vlc_object_t *p_this, char const *psz_cmd,
1143                                 vlc_value_t oldval, vlc_value_t newval, void *p_data )
1144 {
1145     vout_thread_t *p_vout = (vout_thread_t *)p_this;
1146     VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval); VLC_UNUSED(p_data);
1147
1148     static const char *psz_pp = "postproc";
1149
1150     char *psz_vf2 = var_GetString( p_vout, "video-filter" );
1151
1152     if( newval.i_int <= 0 )
1153     {
1154         if( PostProcessIsPresent( psz_vf2 ) )
1155         {
1156             strcpy( psz_vf2, &psz_vf2[strlen(psz_pp)] );
1157             if( *psz_vf2 == ':' )
1158                 strcpy( psz_vf2, &psz_vf2[1] );
1159         }
1160     }
1161     else
1162     {
1163         if( !PostProcessIsPresent( psz_vf2 ) )
1164         {
1165             if( psz_vf2 )
1166             {
1167                 char *psz_tmp = psz_vf2;
1168                 if( asprintf( &psz_vf2, "%s:%s", psz_pp, psz_tmp ) < 0 )
1169                     psz_vf2 = psz_tmp;
1170                 else
1171                     free( psz_tmp );
1172             }
1173             else
1174             {
1175                 psz_vf2 = strdup( psz_pp );
1176             }
1177         }
1178     }
1179     if( psz_vf2 )
1180     {
1181         var_SetString( p_vout, "video-filter", psz_vf2 );
1182         free( psz_vf2 );
1183     }
1184
1185     return VLC_SUCCESS;
1186 }
1187 static void PostProcessEnable( vout_thread_t *p_vout )
1188 {
1189     vlc_value_t text;
1190     msg_Dbg( p_vout, "Post-processing available" );
1191     var_Create( p_vout, "postprocess", VLC_VAR_INTEGER | VLC_VAR_HASCHOICE );
1192     text.psz_string = _("Post processing");
1193     var_Change( p_vout, "postprocess", VLC_VAR_SETTEXT, &text, NULL );
1194
1195     for( int i = 0; i <= 6; i++ )
1196     {
1197         vlc_value_t val;
1198         vlc_value_t text;
1199         char psz_text[1+1];
1200
1201         val.i_int = i;
1202         snprintf( psz_text, sizeof(psz_text), "%d", i );
1203         if( i == 0 )
1204             text.psz_string = _("Disable");
1205         else
1206             text.psz_string = psz_text;
1207         var_Change( p_vout, "postprocess", VLC_VAR_ADDCHOICE, &val, &text );
1208     }
1209     var_AddCallback( p_vout, "postprocess", PostProcessCallback, NULL );
1210
1211     /* */
1212     char *psz_filter = var_GetNonEmptyString( p_vout, "video-filter" );
1213     int i_postproc_q = 0;
1214     if( PostProcessIsPresent( psz_filter ) )
1215         i_postproc_q = var_CreateGetInteger( p_vout, "postproc-q" );
1216
1217     var_SetInteger( p_vout, "postprocess", i_postproc_q );
1218
1219     free( psz_filter );
1220 }
1221 static void PostProcessDisable( vout_thread_t *p_vout )
1222 {
1223     msg_Dbg( p_vout, "Post-processing no more available" );
1224     var_Destroy( p_vout, "postprocess" );
1225 }
1226 static void PostProcessSetFilterQuality( vout_thread_t *p_vout )
1227 {
1228     vlc_object_t *p_pp = vlc_object_find_name( p_vout, "postproc", FIND_CHILD );
1229     if( !p_pp )
1230         return;
1231
1232     var_SetInteger( p_pp, "postproc-q", var_GetInteger( p_vout, "postprocess" ) );
1233     vlc_object_release( p_pp );
1234 }
1235
1236
1237 static void DisplayTitleOnOSD( vout_thread_t *p_vout )
1238 {
1239     const mtime_t i_start = mdate();
1240     const mtime_t i_stop = i_start + INT64_C(1000) * p_vout->p->title.timeout;
1241
1242     if( i_stop <= i_start )
1243         return;
1244
1245     vlc_assert_locked( &p_vout->p->change_lock );
1246
1247     vout_ShowTextAbsolute( p_vout, DEFAULT_CHAN,
1248                            p_vout->p->title.value, NULL,
1249                            p_vout->p->title.position,
1250                            30 + p_vout->fmt_in.i_width
1251                               - p_vout->fmt_in.i_visible_width
1252                               - p_vout->fmt_in.i_x_offset,
1253                            20 + p_vout->fmt_in.i_y_offset,
1254                            i_start, i_stop );
1255
1256     free( p_vout->p->title.value );
1257
1258     p_vout->p->title.value = NULL;
1259 }
1260
1261 /*****************************************************************************
1262  * Deinterlacing
1263  *****************************************************************************/
1264 typedef struct
1265 {
1266     const char *psz_mode;
1267     bool       b_vout_filter;
1268 } deinterlace_mode_t;
1269
1270 /* XXX
1271  * You can use the non vout filter if and only if the video properties stay the
1272  * same (width/height/chroma/fps), at least for now.
1273  */
1274 static const deinterlace_mode_t p_deinterlace_mode[] = {
1275     { "",        false },
1276     //{ "discard", true },
1277     { "blend",   false },
1278     //{ "mean",    true  },
1279     //{ "bob",     true },
1280     //{ "linear",  true },
1281     { "x",       false },
1282     //{ "yadif",   true },
1283     //{ "yadif2x", true },
1284     { NULL,      false }
1285 };
1286 static const deinterlace_mode_t *DeinterlaceGetMode( const char *psz_mode )
1287 {
1288     for( const deinterlace_mode_t *p_mode = &p_deinterlace_mode[0]; p_mode->psz_mode; p_mode++ )
1289     {
1290         if( !strcmp( p_mode->psz_mode, psz_mode ) )
1291             return p_mode;
1292     }
1293     return NULL;
1294 }
1295
1296 static char *FilterFind( char *psz_filter_base, const char *psz_module )
1297 {
1298     const size_t i_module = strlen( psz_module );
1299     const char *psz_filter = psz_filter_base;
1300
1301     if( !psz_filter || i_module <= 0 )
1302         return NULL;
1303
1304     for( ;; )
1305     {
1306         char *psz_find = strstr( psz_filter, psz_module );
1307         if( !psz_find )
1308             return NULL;
1309         if( psz_find[i_module] == '\0' || psz_find[i_module] == ':' )
1310             return psz_find;
1311         psz_filter = &psz_find[i_module];
1312     }
1313 }
1314
1315 static bool DeinterlaceIsPresent( vout_thread_t *p_vout, bool b_vout_filter )
1316 {
1317     char *psz_filter = var_GetNonEmptyString( p_vout, b_vout_filter ? "vout-filter" : "video-filter" );
1318
1319     bool b_found = FilterFind( psz_filter, "deinterlace" ) != NULL;
1320
1321     free( psz_filter );
1322
1323     return b_found;
1324 }
1325
1326 static void DeinterlaceRemove( vout_thread_t *p_vout, bool b_vout_filter )
1327 {
1328     const char *psz_variable = b_vout_filter ? "vout-filter" : "video-filter";
1329     char *psz_filter = var_GetNonEmptyString( p_vout, psz_variable );
1330
1331     char *psz = FilterFind( psz_filter, "deinterlace" );
1332     if( !psz )
1333     {
1334         free( psz_filter );
1335         return;
1336     }
1337
1338     /* */
1339     strcpy( &psz[0], &psz[strlen("deinterlace")] );
1340     if( *psz == ':' )
1341         strcpy( &psz[0], &psz[1] );
1342
1343     var_SetString( p_vout, psz_variable, psz_filter );
1344     free( psz_filter );
1345 }
1346 static void DeinterlaceAdd( vout_thread_t *p_vout, bool b_vout_filter )
1347 {
1348     const char *psz_variable = b_vout_filter ? "vout-filter" : "video-filter";
1349
1350     char *psz_filter = var_GetNonEmptyString( p_vout, psz_variable );
1351
1352     if( FilterFind( psz_filter, "deinterlace" ) )
1353     {
1354         free( psz_filter );
1355         return;
1356     }
1357
1358     /* */
1359     if( psz_filter )
1360     {
1361         char *psz_tmp = psz_filter;
1362         if( asprintf( &psz_filter, "%s:%s", psz_tmp, "deinterlace" ) < 0 )
1363             psz_filter = psz_tmp;
1364         else
1365             free( psz_tmp );
1366     }
1367     else
1368     {
1369         psz_filter = strdup( "deinterlace" );
1370     }
1371
1372     if( psz_filter )
1373     {
1374         var_SetString( p_vout, psz_variable, psz_filter );
1375         free( psz_filter );
1376     }
1377 }
1378
1379 static void DeinterlaceSave( vout_thread_t *p_vout, int i_deinterlace, const char *psz_mode, bool is_needed )
1380 {
1381     /* We have to set input variable to ensure restart support
1382      * XXX it is only needed because of vout-filter but must be done
1383      * for non video filter anyway */
1384     vlc_object_t *p_input = vlc_object_find( p_vout, VLC_OBJECT_INPUT, FIND_PARENT );
1385     if( !p_input )
1386         return;
1387
1388     /* Another hack for "vout filter" mode */
1389     if( i_deinterlace < 0 )
1390         i_deinterlace = is_needed ? -2 : -3;
1391
1392     var_Create( p_input, "deinterlace", VLC_VAR_INTEGER );
1393     var_SetInteger( p_input, "deinterlace", i_deinterlace );
1394
1395     static const char * const ppsz_variable[] = {
1396         "deinterlace-mode",
1397         "filter-deinterlace-mode",
1398         "sout-deinterlace-mode",
1399         NULL
1400     };
1401     for( int i = 0; ppsz_variable[i]; i++ )
1402     {
1403         var_Create( p_input, ppsz_variable[i], VLC_VAR_STRING );
1404         var_SetString( p_input, ppsz_variable[i], psz_mode );
1405     }
1406
1407     vlc_object_release( p_input );
1408 }
1409 static int DeinterlaceCallback( vlc_object_t *p_this, char const *psz_cmd,
1410                                 vlc_value_t oldval, vlc_value_t newval, void *p_data )
1411 {
1412     VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval); VLC_UNUSED(newval); VLC_UNUSED(p_data);
1413     vout_thread_t *p_vout = (vout_thread_t *)p_this;
1414
1415     /* */
1416     const int  i_deinterlace = var_GetInteger( p_this, "deinterlace" );
1417     char       *psz_mode     = var_GetString( p_this, "deinterlace-mode" );
1418     const bool is_needed     = var_GetBool( p_this, "deinterlace-needed" );
1419     if( !psz_mode )
1420         return VLC_EGENERIC;
1421
1422     DeinterlaceSave( p_vout, i_deinterlace, psz_mode, is_needed );
1423
1424     /* */
1425     bool b_vout_filter = false;
1426     const deinterlace_mode_t *p_mode = DeinterlaceGetMode( psz_mode );
1427     if( p_mode )
1428         b_vout_filter = p_mode->b_vout_filter;
1429
1430     /* */
1431     char *psz_old;
1432     if( b_vout_filter )
1433     {
1434         psz_old = var_CreateGetString( p_vout, "filter-deinterlace-mode" );
1435     }
1436     else
1437     {
1438         psz_old = var_CreateGetString( p_vout, "sout-deinterlace-mode" );
1439         var_SetString( p_vout, "sout-deinterlace-mode", psz_mode );
1440     }
1441
1442     msg_Dbg( p_vout, "deinterlace %d, mode %s, is_needed %d", i_deinterlace, psz_mode, is_needed );
1443     if( i_deinterlace == 0 || ( i_deinterlace == -1 && !is_needed ) )
1444     {
1445         DeinterlaceRemove( p_vout, false );
1446         DeinterlaceRemove( p_vout, true );
1447     }
1448     else
1449     {
1450         if( !DeinterlaceIsPresent( p_vout, b_vout_filter ) )
1451         {
1452             DeinterlaceRemove( p_vout, !b_vout_filter );
1453             DeinterlaceAdd( p_vout, b_vout_filter );
1454         }
1455         else
1456         {
1457             /* The deinterlace filter was already inserted but we have changed the mode */
1458             DeinterlaceRemove( p_vout, !b_vout_filter );
1459             if( psz_old && strcmp( psz_old, psz_mode ) )
1460                 var_TriggerCallback( p_vout, b_vout_filter ? "vout-filter" : "video-filter" );
1461         }
1462     }
1463
1464     /* */
1465     free( psz_old );
1466     free( psz_mode );
1467     return VLC_SUCCESS;
1468 }
1469
1470 static void DeinterlaceEnable( vout_thread_t *p_vout )
1471 {
1472     vlc_value_t val, text;
1473
1474     if( !p_vout->p->b_first_vout )
1475         return;
1476
1477     msg_Dbg( p_vout, "Deinterlacing available" );
1478
1479     /* Create the configuration variables */
1480     /* */
1481     var_Create( p_vout, "deinterlace", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT | VLC_VAR_HASCHOICE );
1482     int i_deinterlace = var_GetInteger( p_vout, "deinterlace" );
1483
1484     text.psz_string = _("Deinterlace");
1485     var_Change( p_vout, "deinterlace", VLC_VAR_SETTEXT, &text, NULL );
1486
1487     const module_config_t *p_optd = config_FindConfig( VLC_OBJECT(p_vout), "deinterlace" );
1488     var_Change( p_vout, "deinterlace", VLC_VAR_CLEARCHOICES, NULL, NULL );
1489     for( int i = 0; p_optd && i < p_optd->i_list; i++ )
1490     {
1491         val.i_int  = p_optd->pi_list[i];
1492         text.psz_string = (char*)vlc_gettext(p_optd->ppsz_list_text[i]);
1493         var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
1494     }
1495     var_AddCallback( p_vout, "deinterlace", DeinterlaceCallback, NULL );
1496     /* */
1497     var_Create( p_vout, "deinterlace-mode", VLC_VAR_STRING | VLC_VAR_DOINHERIT | VLC_VAR_HASCHOICE );
1498     char *psz_deinterlace = var_GetNonEmptyString( p_vout, "deinterlace-mode" );
1499
1500     text.psz_string = _("Deinterlace mode");
1501     var_Change( p_vout, "deinterlace-mode", VLC_VAR_SETTEXT, &text, NULL );
1502
1503     const module_config_t *p_optm = config_FindConfig( VLC_OBJECT(p_vout), "deinterlace-mode" );
1504     var_Change( p_vout, "deinterlace-mode", VLC_VAR_CLEARCHOICES, NULL, NULL );
1505     for( int i = 0; p_optm && i < p_optm->i_list; i++ )
1506     {
1507         if( !DeinterlaceGetMode( p_optm->ppsz_list[i] ) )
1508             continue;
1509
1510         val.psz_string  = p_optm->ppsz_list[i];
1511         text.psz_string = (char*)vlc_gettext(p_optm->ppsz_list_text[i]);
1512         var_Change( p_vout, "deinterlace-mode", VLC_VAR_ADDCHOICE, &val, &text );
1513     }
1514     var_AddCallback( p_vout, "deinterlace-mode", DeinterlaceCallback, NULL );
1515     /* */
1516     var_Create( p_vout, "deinterlace-needed", VLC_VAR_BOOL );
1517     var_AddCallback( p_vout, "deinterlace-needed", DeinterlaceCallback, NULL );
1518
1519     /* Override the initial value from filters if present */
1520     char *psz_filter_mode = NULL;
1521     if( DeinterlaceIsPresent( p_vout, true ) )
1522         psz_filter_mode = var_CreateGetNonEmptyString( p_vout, "filter-deinterlace-mode" );
1523     else if( DeinterlaceIsPresent( p_vout, false ) )
1524         psz_filter_mode = var_CreateGetNonEmptyString( p_vout, "sout-deinterlace-mode" );
1525     if( psz_filter_mode )
1526     {
1527         free( psz_deinterlace );
1528         if( i_deinterlace >= -1 )
1529             i_deinterlace = 1;
1530         psz_deinterlace = psz_filter_mode;
1531     }
1532
1533     /* */
1534     if( i_deinterlace == -2 )
1535         p_vout->p->displayed.is_interlaced = true;
1536     else if( i_deinterlace == -3 )
1537         p_vout->p->displayed.is_interlaced = false;
1538     if( i_deinterlace < 0 )
1539         i_deinterlace = -1;
1540
1541     /* */
1542     val.psz_string = psz_deinterlace ? psz_deinterlace : p_optm->orig.psz;
1543     var_Change( p_vout, "deinterlace-mode", VLC_VAR_SETVALUE, &val, NULL );
1544     val.b_bool = p_vout->p->displayed.is_interlaced;
1545     var_Change( p_vout, "deinterlace-needed", VLC_VAR_SETVALUE, &val, NULL );
1546
1547     var_SetInteger( p_vout, "deinterlace", i_deinterlace );
1548     free( psz_deinterlace );
1549 }
1550
1551 static void DeinterlaceNeeded( vout_thread_t *p_vout, bool is_interlaced )
1552 {
1553     msg_Dbg( p_vout, "Detected %s video",
1554              is_interlaced ? "interlaced" : "progressive" );
1555     var_SetBool( p_vout, "deinterlace-needed", is_interlaced );
1556 }
1557
1558 /* */
1559 static void PrintVideoFormat(vout_thread_t *vout,
1560                              const char *description,
1561                              const video_format_t *fmt)
1562 {
1563     msg_Dbg(vout, "%s sz %ix%i, of (%i,%i), vsz %ix%i, 4cc %4.4s, sar %i:%i, msk r0x%x g0x%x b0x%x",
1564             description,
1565             fmt->i_width, fmt->i_height, fmt->i_x_offset, fmt->i_y_offset,
1566             fmt->i_visible_width, fmt->i_visible_height,
1567             (char*)&fmt->i_chroma,
1568             fmt->i_sar_num, fmt->i_sar_den,
1569             fmt->i_rmask, fmt->i_gmask, fmt->i_bmask);
1570 }
1571