]> git.sesse.net Git - vlc/blob - src/video_output/video_output.c
Do not hold change_lock while loading the vout module.
[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  *
14  * This program is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation; either version 2 of the License, or
17  * (at your option) any later version.
18  *
19  * This program is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
27  *****************************************************************************/
28
29 /*****************************************************************************
30  * Preamble
31  *****************************************************************************/
32 #ifdef HAVE_CONFIG_H
33 # include "config.h"
34 #endif
35
36 #include <vlc_common.h>
37
38 #include <stdlib.h>                                                /* free() */
39 #include <string.h>
40
41
42 #ifdef HAVE_SYS_TIMES_H
43 #   include <sys/times.h>
44 #endif
45
46 #include <vlc_vout.h>
47
48 #include <vlc_filter.h>
49 #include <vlc_osd.h>
50 #include <assert.h>
51
52 #if defined( __APPLE__ )
53 /* Include darwin_specific.h here if needed */
54 #endif
55
56 /** FIXME This is quite ugly but needed while we don't have counters
57  * helpers */
58 //#include "input/input_internal.h"
59
60 #include <libvlc.h>
61 #include <vlc_input.h>
62 #include "vout_pictures.h"
63 #include "vout_internal.h"
64
65 /*****************************************************************************
66  * Local prototypes
67  *****************************************************************************/
68 static int      InitThread        ( vout_thread_t * );
69 static void*    RunThread         ( void *  );
70 static void     ErrorThread       ( vout_thread_t * );
71 static void     CleanThread       ( vout_thread_t * );
72 static void     EndThread         ( vout_thread_t * );
73
74 static void     AspectRatio       ( int, int *, int * );
75
76 static void VideoFormatImportRgb( video_format_t *, const picture_heap_t * );
77 static void PictureHeapFixRgb( picture_heap_t * );
78
79 static void     vout_Destructor   ( vlc_object_t * p_this );
80
81 /* Object variables callbacks */
82 static int FilterCallback( vlc_object_t *, char const *,
83                            vlc_value_t, vlc_value_t, void * );
84 static int VideoFilter2Callback( vlc_object_t *, char const *,
85                                  vlc_value_t, vlc_value_t, void * );
86
87 /* */
88 static void PostProcessEnable( vout_thread_t * );
89 static void PostProcessDisable( vout_thread_t * );
90 static void PostProcessSetFilterQuality( vout_thread_t *p_vout );
91 static int  PostProcessCallback( vlc_object_t *, char const *,
92                                  vlc_value_t, vlc_value_t, void * );
93 /* */
94 static void DeinterlaceEnable( vout_thread_t * );
95 static void DeinterlaceNeeded( vout_thread_t *, bool );
96
97 /* From vout_intf.c */
98 int vout_Snapshot( vout_thread_t *, picture_t * );
99
100 /* Display media title in OSD */
101 static void DisplayTitleOnOSD( vout_thread_t *p_vout );
102
103 /* Time during which the thread will sleep if it has nothing to
104  * display (in micro-seconds) */
105 #define VOUT_IDLE_SLEEP                 ((int)(0.020*CLOCK_FREQ))
106
107 /* Maximum lap of time allowed between the beginning of rendering and
108  * display. If, compared to the current date, the next image is too
109  * late, the thread will perform an idle loop. This time should be
110  * at least VOUT_IDLE_SLEEP plus the time required to render a few
111  * images, to avoid trashing of decoded images */
112 #define VOUT_DISPLAY_DELAY              ((int)(0.200*CLOCK_FREQ))
113
114 /* Better be in advance when awakening than late... */
115 #define VOUT_MWAIT_TOLERANCE            ((mtime_t)(0.020*CLOCK_FREQ))
116
117 /* Minimum number of direct pictures the video output will accept without
118  * creating additional pictures in system memory */
119 #ifdef OPTIMIZE_MEMORY
120 #   define VOUT_MIN_DIRECT_PICTURES        (VOUT_MAX_PICTURES/2)
121 #else
122 #   define VOUT_MIN_DIRECT_PICTURES        (3*VOUT_MAX_PICTURES/4)
123 #endif
124
125 /*****************************************************************************
126  * Video Filter2 functions
127  *****************************************************************************/
128 static picture_t *video_new_buffer_filter( filter_t *p_filter )
129 {
130     vout_thread_t *p_vout = (vout_thread_t*)p_filter->p_owner;
131     picture_t *p_picture = vout_CreatePicture( p_vout, 0, 0, 0 );
132
133     p_picture->i_status = READY_PICTURE;
134
135     return p_picture;
136 }
137
138 static void video_del_buffer_filter( filter_t *p_filter, picture_t *p_pic )
139 {
140     vout_thread_t *p_vout = (vout_thread_t*)p_filter->p_owner;
141
142     vlc_mutex_lock( &p_vout->picture_lock );
143     vout_UsePictureLocked( p_vout, p_pic );
144     vlc_mutex_unlock( &p_vout->picture_lock );
145 }
146
147 static int video_filter_buffer_allocation_init( filter_t *p_filter, void *p_data )
148 {
149     p_filter->pf_vout_buffer_new = video_new_buffer_filter;
150     p_filter->pf_vout_buffer_del = video_del_buffer_filter;
151     p_filter->p_owner = p_data; /* p_vout */
152     return VLC_SUCCESS;
153 }
154
155 /*****************************************************************************
156  * vout_Request: find a video output thread, create one, or destroy one.
157  *****************************************************************************
158  * This function looks for a video output thread matching the current
159  * properties. If not found, it spawns a new one.
160  *****************************************************************************/
161 vout_thread_t *__vout_Request( vlc_object_t *p_this, vout_thread_t *p_vout,
162                                video_format_t *p_fmt )
163 {
164     if( !p_fmt )
165     {
166         /* Video output is no longer used.
167          * TODO: support for reusing video outputs with proper _thread-safe_
168          * reference handling. */
169         if( p_vout )
170             vout_CloseAndRelease( p_vout );
171         return NULL;
172     }
173
174     /* If a video output was provided, lock it, otherwise look for one. */
175     if( p_vout )
176     {
177         vlc_object_hold( p_vout );
178     }
179
180     /* TODO: find a suitable unused video output */
181
182     /* If we now have a video output, check it has the right properties */
183     if( p_vout )
184     {
185         vlc_mutex_lock( &p_vout->change_lock );
186
187         /* We don't directly check for the "vout-filter" variable for obvious
188          * performance reasons. */
189         if( p_vout->p->b_filter_change )
190         {
191             char *psz_filter_chain = var_GetString( p_vout, "vout-filter" );
192
193             if( psz_filter_chain && !*psz_filter_chain )
194             {
195                 free( psz_filter_chain );
196                 psz_filter_chain = NULL;
197             }
198             if( p_vout->p->psz_filter_chain && !*p_vout->p->psz_filter_chain )
199             {
200                 free( p_vout->p->psz_filter_chain );
201                 p_vout->p->psz_filter_chain = NULL;
202             }
203
204             if( !psz_filter_chain && !p_vout->p->psz_filter_chain )
205             {
206                 p_vout->p->b_filter_change = false;
207             }
208
209             free( psz_filter_chain );
210         }
211
212         if( p_vout->fmt_render.i_chroma != vlc_fourcc_GetCodec( VIDEO_ES, p_fmt->i_chroma ) ||
213             p_vout->fmt_render.i_width != p_fmt->i_width ||
214             p_vout->fmt_render.i_height != p_fmt->i_height ||
215             p_vout->p->b_filter_change )
216         {
217             vlc_mutex_unlock( &p_vout->change_lock );
218
219             /* We are not interested in this format, close this vout */
220             vout_CloseAndRelease( p_vout );
221             vlc_object_release( p_vout );
222             p_vout = NULL;
223         }
224         else
225         {
226             /* This video output is cool! Hijack it. */
227             if( p_vout->fmt_render.i_aspect != p_fmt->i_aspect )
228             {
229                 /* Correct aspect ratio on change
230                  * FIXME factorize this code with other aspect ration related code */
231                 unsigned int i_sar_num;
232                 unsigned int i_sar_den;
233                 unsigned int i_aspect;
234
235                 i_aspect = p_fmt->i_aspect;
236                 vlc_ureduce( &i_sar_num, &i_sar_den,
237                              p_fmt->i_sar_num, p_fmt->i_sar_den, 50000 );
238 #if 0
239                 /* What's that, it does not seems to be used correcly everywhere
240                  * beside the previous p_vout->fmt_render.i_aspect != p_fmt->i_aspect
241                  * should be fixed to use it too then */
242                 if( p_vout->i_par_num > 0 && p_vout->i_par_den > 0 )
243                 {
244                     i_sar_num *= p_vout->i_par_den;
245                     i_sar_den *= p_vout->i_par_num;
246                     i_aspect = i_aspect * p_vout->i_par_den / p_vout->i_par_num;
247                 }
248 #endif
249
250                 if( i_sar_num > 0 && i_sar_den > 0 && i_aspect > 0 )
251                 {
252                     p_vout->fmt_in.i_sar_num = i_sar_num;
253                     p_vout->fmt_in.i_sar_den = i_sar_den;
254                     p_vout->fmt_in.i_aspect  = i_aspect;
255
256                     p_vout->fmt_render.i_sar_num = i_sar_num;
257                     p_vout->fmt_render.i_sar_den = i_sar_den;
258                     p_vout->fmt_render.i_aspect  = i_aspect;
259
260                     p_vout->render.i_aspect   = i_aspect;
261
262                     p_vout->i_changes |= VOUT_ASPECT_CHANGE;
263
264                 }
265             }
266             vlc_mutex_unlock( &p_vout->change_lock );
267
268             vlc_object_release( p_vout );
269         }
270
271         if( p_vout )
272         {
273             msg_Dbg( p_this, "reusing provided vout" );
274
275             spu_Attach( p_vout->p_spu, VLC_OBJECT(p_vout), false );
276             vlc_object_detach( p_vout );
277
278             vlc_object_attach( p_vout, p_this );
279             spu_Attach( p_vout->p_spu, VLC_OBJECT(p_vout), true );
280         }
281     }
282
283     if( !p_vout )
284     {
285         msg_Dbg( p_this, "no usable vout present, spawning one" );
286
287         p_vout = vout_Create( p_this, p_fmt );
288     }
289
290     return p_vout;
291 }
292
293 /*****************************************************************************
294  * vout_Create: creates a new video output thread
295  *****************************************************************************
296  * This function creates a new video output thread, and returns a pointer
297  * to its description. On error, it returns NULL.
298  *****************************************************************************/
299 vout_thread_t * __vout_Create( vlc_object_t *p_parent, video_format_t *p_fmt )
300 {
301     vout_thread_t  * p_vout;                            /* thread descriptor */
302     int              i_index;                               /* loop variable */
303     vlc_value_t      text;
304
305     unsigned int i_width = p_fmt->i_width;
306     unsigned int i_height = p_fmt->i_height;
307     vlc_fourcc_t i_chroma = vlc_fourcc_GetCodec( VIDEO_ES, p_fmt->i_chroma );
308     unsigned int i_aspect = p_fmt->i_aspect;
309
310     config_chain_t *p_cfg;
311     char *psz_parser;
312     char *psz_name;
313
314     if( i_width <= 0 || i_height <= 0 || i_aspect <= 0 )
315         return NULL;
316
317     vlc_ureduce( &p_fmt->i_sar_num, &p_fmt->i_sar_den,
318                  p_fmt->i_sar_num, p_fmt->i_sar_den, 50000 );
319     if( p_fmt->i_sar_num <= 0 || p_fmt->i_sar_den <= 0 )
320         return NULL;
321
322     /* Allocate descriptor */
323     static const char typename[] = "video output";
324     p_vout = vlc_custom_create( p_parent, sizeof( *p_vout ), VLC_OBJECT_VOUT,
325                                 typename );
326     if( p_vout == NULL )
327         return NULL;
328
329     /* */
330     p_vout->p = calloc( 1, sizeof(*p_vout->p) );
331     if( !p_vout->p )
332     {
333         vlc_object_release( p_vout );
334         return NULL;
335     }
336
337     /* Initialize pictures - translation tables and functions
338      * will be initialized later in InitThread */
339     for( i_index = 0; i_index < 2 * VOUT_MAX_PICTURES + 1; i_index++)
340     {
341         p_vout->p_picture[i_index].pf_lock = NULL;
342         p_vout->p_picture[i_index].pf_unlock = NULL;
343         p_vout->p_picture[i_index].i_status = FREE_PICTURE;
344         p_vout->p_picture[i_index].i_type   = EMPTY_PICTURE;
345         p_vout->p_picture[i_index].b_slow   = 0;
346     }
347
348     /* No images in the heap */
349     p_vout->i_heap_size = 0;
350
351     /* Initialize the rendering heap */
352     I_RENDERPICTURES = 0;
353
354     p_vout->fmt_render        = *p_fmt;   /* FIXME palette */
355     p_vout->fmt_in            = *p_fmt;   /* FIXME palette */
356
357     p_vout->render.i_width    = i_width;
358     p_vout->render.i_height   = i_height;
359     p_vout->render.i_chroma   = i_chroma;
360     p_vout->render.i_aspect   = i_aspect;
361
362     p_vout->render.i_rmask    = p_fmt->i_rmask;
363     p_vout->render.i_gmask    = p_fmt->i_gmask;
364     p_vout->render.i_bmask    = p_fmt->i_bmask;
365
366     p_vout->render.i_last_used_pic = -1;
367     p_vout->render.b_allow_modify_pics = 1;
368
369     /* Zero the output heap */
370     I_OUTPUTPICTURES = 0;
371     p_vout->output.i_width    = 0;
372     p_vout->output.i_height   = 0;
373     p_vout->output.i_chroma   = 0;
374     p_vout->output.i_aspect   = 0;
375
376     p_vout->output.i_rmask    = 0;
377     p_vout->output.i_gmask    = 0;
378     p_vout->output.i_bmask    = 0;
379
380     /* Initialize misc stuff */
381     p_vout->i_changes    = 0;
382     p_vout->b_autoscale  = 1;
383     p_vout->i_zoom      = ZOOM_FP_FACTOR;
384     p_vout->b_fullscreen = 0;
385     p_vout->i_alignment  = 0;
386     p_vout->p->render_time  = 10;
387     p_vout->p->c_fps_samples = 0;
388     vout_statistic_Init( &p_vout->p->statistic );
389     p_vout->p->b_filter_change = 0;
390     p_vout->p->b_paused = false;
391     p_vout->p->i_pause_date = 0;
392     p_vout->pf_control = NULL;
393     p_vout->p->i_par_num =
394     p_vout->p->i_par_den = 1;
395     p_vout->p->p_picture_displayed = NULL;
396     p_vout->p->i_picture_displayed_date = 0;
397     p_vout->p->b_picture_displayed = false;
398     p_vout->p->b_picture_empty = false;
399     p_vout->p->i_picture_qtype = QTYPE_NONE;
400     p_vout->p->b_picture_interlaced = false;
401
402     vlc_mouse_Init( &p_vout->p->mouse );
403
404     vout_snapshot_Init( &p_vout->p->snapshot );
405
406     /* Initialize locks */
407     vlc_mutex_init( &p_vout->picture_lock );
408     vlc_cond_init( &p_vout->p->picture_wait );
409     vlc_mutex_init( &p_vout->change_lock );
410     vlc_mutex_init( &p_vout->p->vfilter_lock );
411
412     /* Mouse coordinates */
413     var_Create( p_vout, "mouse-x", VLC_VAR_INTEGER );
414     var_Create( p_vout, "mouse-y", VLC_VAR_INTEGER );
415     var_Create( p_vout, "mouse-button-down", VLC_VAR_INTEGER );
416     var_Create( p_vout, "mouse-moved", VLC_VAR_BOOL );
417     var_Create( p_vout, "mouse-clicked", VLC_VAR_BOOL );
418
419     /* Initialize subpicture unit */
420     p_vout->p_spu = spu_Create( p_vout );
421
422     /* Attach the new object now so we can use var inheritance below */
423     vlc_object_attach( p_vout, p_parent );
424
425     /* */
426     spu_Init( p_vout->p_spu );
427
428     spu_Attach( p_vout->p_spu, VLC_OBJECT(p_vout), true );
429
430     /* Take care of some "interface/control" related initialisations */
431     vout_IntfInit( p_vout );
432
433     /* If the parent is not a VOUT object, that means we are at the start of
434      * the video output pipe */
435     if( vlc_internals( p_parent )->i_object_type != VLC_OBJECT_VOUT )
436     {
437         /* Look for the default filter configuration */
438         p_vout->p->psz_filter_chain =
439             var_CreateGetStringCommand( p_vout, "vout-filter" );
440
441         /* Apply video filter2 objects on the first vout */
442         p_vout->p->psz_vf2 =
443             var_CreateGetStringCommand( p_vout, "video-filter" );
444
445         p_vout->p->b_first_vout = true;
446     }
447     else
448     {
449         /* continue the parent's filter chain */
450         char *psz_tmp;
451
452         /* Ugly hack to jump to our configuration chain */
453         p_vout->p->psz_filter_chain
454             = ((vout_thread_t *)p_parent)->p->psz_filter_chain;
455         p_vout->p->psz_filter_chain
456             = config_ChainCreate( &psz_tmp, &p_cfg, p_vout->p->psz_filter_chain );
457         config_ChainDestroy( p_cfg );
458         free( psz_tmp );
459
460         /* Create a video filter2 var ... but don't inherit values */
461         var_Create( p_vout, "video-filter",
462                     VLC_VAR_STRING | VLC_VAR_ISCOMMAND );
463         p_vout->p->psz_vf2 = var_GetString( p_vout, "video-filter" );
464
465         /* */
466         p_vout->p->b_first_vout = false;
467     }
468
469     var_AddCallback( p_vout, "video-filter", VideoFilter2Callback, NULL );
470     p_vout->p->p_vf2_chain = filter_chain_New( p_vout, "video filter2",
471         false, video_filter_buffer_allocation_init, NULL, p_vout );
472
473     /* Choose the video output module */
474     if( !p_vout->p->psz_filter_chain || !*p_vout->p->psz_filter_chain )
475     {
476         psz_parser = var_CreateGetString( p_vout, "vout" );
477     }
478     else
479     {
480         psz_parser = strdup( p_vout->p->psz_filter_chain );
481         p_vout->p->b_title_show = false;
482     }
483
484     /* Create the vout thread */
485     char* psz_tmp = config_ChainCreate( &psz_name, &p_cfg, psz_parser );
486     free( psz_parser );
487     free( psz_tmp );
488     p_vout->p_cfg = p_cfg;
489
490     /* Create a few object variables for interface interaction */
491     var_Create( p_vout, "vout-filter", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
492     text.psz_string = _("Filters");
493     var_Change( p_vout, "vout-filter", VLC_VAR_SETTEXT, &text, NULL );
494     var_AddCallback( p_vout, "vout-filter", FilterCallback, NULL );
495
496     /* */
497     DeinterlaceEnable( p_vout );
498
499     if( p_vout->p->psz_filter_chain && *p_vout->p->psz_filter_chain )
500         p_vout->p->psz_module_type = "video filter";
501     else
502         p_vout->p->psz_module_type = "video output";
503     p_vout->p->psz_module_name = psz_name;
504     p_vout->p_module = NULL;
505
506     /* */
507     vlc_object_set_destructor( p_vout, vout_Destructor );
508
509     /* */
510     vlc_cond_init( &p_vout->p->change_wait );
511     if( vlc_clone( &p_vout->p->thread, RunThread, p_vout,
512                    VLC_THREAD_PRIORITY_OUTPUT ) )
513     {
514         spu_Attach( p_vout->p_spu, VLC_OBJECT(p_vout), false );
515         spu_Destroy( p_vout->p_spu );
516         p_vout->p_spu = NULL;
517         vlc_object_release( p_vout );
518         return NULL;
519     }
520
521     vlc_mutex_lock( &p_vout->change_lock );
522     while( !p_vout->p->b_ready )
523     {   /* We are (ab)using the same condition in opposite directions for
524          * b_ready and b_done. This works because of the strict ordering. */
525         assert( !p_vout->p->b_done );
526         vlc_cond_wait( &p_vout->p->change_wait, &p_vout->change_lock );
527     }
528     vlc_mutex_unlock( &p_vout->change_lock );
529
530     if( p_vout->b_error )
531     {
532         msg_Err( p_vout, "video output creation failed" );
533         vout_CloseAndRelease( p_vout );
534         return NULL;
535     }
536
537     return p_vout;
538 }
539
540 /*****************************************************************************
541  * vout_Close: Close a vout created by vout_Create.
542  *****************************************************************************
543  * You HAVE to call it on vout created by vout_Create before vlc_object_release.
544  * You should NEVER call it on vout not obtained through vout_Create
545  * (like with vout_Request or vlc_object_find.)
546  * You can use vout_CloseAndRelease() as a convenience method.
547  *****************************************************************************/
548 void vout_Close( vout_thread_t *p_vout )
549 {
550     assert( p_vout );
551
552     vlc_mutex_lock( &p_vout->change_lock );
553     p_vout->p->b_done = true;
554     vlc_cond_signal( &p_vout->p->change_wait );
555     vlc_mutex_unlock( &p_vout->change_lock );
556
557     vout_snapshot_End( &p_vout->p->snapshot );
558
559     vlc_join( p_vout->p->thread, NULL );
560 }
561
562 /* */
563 static void vout_Destructor( vlc_object_t * p_this )
564 {
565     vout_thread_t *p_vout = (vout_thread_t *)p_this;
566
567     /* Make sure the vout was stopped first */
568     assert( !p_vout->p_module );
569
570     free( p_vout->p->psz_module_name );
571
572     /* */
573     if( p_vout->p_spu )
574         spu_Destroy( p_vout->p_spu );
575
576     /* Destroy the locks */
577     vlc_cond_destroy( &p_vout->p->change_wait );
578     vlc_cond_destroy( &p_vout->p->picture_wait );
579     vlc_mutex_destroy( &p_vout->picture_lock );
580     vlc_mutex_destroy( &p_vout->change_lock );
581     vlc_mutex_destroy( &p_vout->p->vfilter_lock );
582
583     /* */
584     vout_statistic_Clean( &p_vout->p->statistic );
585
586     /* */
587     vout_snapshot_Clean( &p_vout->p->snapshot );
588
589     /* */
590     free( p_vout->p->psz_filter_chain );
591     free( p_vout->p->psz_title );
592
593     config_ChainDestroy( p_vout->p_cfg );
594
595     free( p_vout->p );
596
597 #ifndef __APPLE__
598     vout_thread_t *p_another_vout;
599
600     /* This is a dirty hack mostly for Linux, where there is no way to get the
601      * GUI back if you closed it while playing video. This is solved in
602      * Mac OS X, where we have this novelty called menubar, that will always
603      * allow you access to the applications main functionality. They should try
604      * that on linux sometime. */
605     p_another_vout = vlc_object_find( p_this->p_libvlc,
606                                       VLC_OBJECT_VOUT, FIND_ANYWHERE );
607     if( p_another_vout == NULL )
608         var_SetBool( p_this->p_libvlc, "intf-show", true );
609     else
610         vlc_object_release( p_another_vout );
611 #endif
612 }
613
614 /* */
615 void vout_ChangePause( vout_thread_t *p_vout, bool b_paused, mtime_t i_date )
616 {
617     vlc_mutex_lock( &p_vout->change_lock );
618
619     assert( !p_vout->p->b_paused || !b_paused );
620
621     vlc_mutex_lock( &p_vout->picture_lock );
622
623     p_vout->p->i_picture_displayed_date = 0;
624
625     if( p_vout->p->b_paused )
626     {
627         const mtime_t i_duration = i_date - p_vout->p->i_pause_date;
628
629         for( int i_index = 0; i_index < I_RENDERPICTURES; i_index++ )
630         {
631             picture_t *p_pic = PP_RENDERPICTURE[i_index];
632
633             if( p_pic->i_status == READY_PICTURE )
634                 p_pic->date += i_duration;
635         }
636         vlc_cond_signal( &p_vout->p->picture_wait );
637         vlc_mutex_unlock( &p_vout->picture_lock );
638
639         spu_OffsetSubtitleDate( p_vout->p_spu, i_duration );
640     }
641     else
642     {
643         vlc_mutex_unlock( &p_vout->picture_lock );
644     }
645     p_vout->p->b_paused = b_paused;
646     p_vout->p->i_pause_date = i_date;
647
648     vlc_mutex_unlock( &p_vout->change_lock );
649 }
650
651 void vout_GetResetStatistic( vout_thread_t *p_vout, int *pi_displayed, int *pi_lost )
652 {
653     vout_statistic_GetReset( &p_vout->p->statistic,
654                              pi_displayed, pi_lost );
655 }
656
657 void vout_Flush( vout_thread_t *p_vout, mtime_t i_date )
658 {
659     vlc_mutex_lock( &p_vout->picture_lock );
660     p_vout->p->i_picture_displayed_date = 0;
661     for( int i = 0; i < p_vout->render.i_pictures; i++ )
662     {
663         picture_t *p_pic = p_vout->render.pp_picture[i];
664
665         if( p_pic->i_status == READY_PICTURE ||
666             p_pic->i_status == DISPLAYED_PICTURE )
667         {
668             /* We cannot change picture status if it is in READY_PICTURE state,
669              * Just make sure they won't be displayed */
670             if( p_pic->date > i_date )
671                 p_pic->date = i_date;
672         }
673     }
674     vlc_cond_signal( &p_vout->p->picture_wait );
675     vlc_mutex_unlock( &p_vout->picture_lock );
676 }
677
678 void vout_FixLeaks( vout_thread_t *p_vout, bool b_forced )
679 {
680     int i_pic, i_ready_pic;
681
682     vlc_mutex_lock( &p_vout->picture_lock );
683
684     for( i_pic = 0, i_ready_pic = 0; i_pic < p_vout->render.i_pictures && !b_forced; i_pic++ )
685     {
686         const picture_t *p_pic = p_vout->render.pp_picture[i_pic];
687
688         if( p_pic->i_status == READY_PICTURE )
689         {
690             i_ready_pic++;
691             /* If we have at least 2 ready pictures, wait for the vout thread to
692              * process one */
693             if( i_ready_pic >= 2 )
694                 break;
695
696             continue;
697         }
698
699         if( p_pic->i_status == DISPLAYED_PICTURE )
700         {
701             /* If at least one displayed picture is not referenced
702              * let vout free it */
703             if( p_pic->i_refcount == 0 )
704                 break;
705         }
706     }
707     if( i_pic < p_vout->render.i_pictures && !b_forced )
708     {
709         vlc_mutex_unlock( &p_vout->picture_lock );
710         return;
711     }
712
713     /* Too many pictures are still referenced, there is probably a bug
714      * with the decoder */
715     if( !b_forced )
716         msg_Err( p_vout, "pictures leaked, resetting the heap" );
717
718     /* Just free all the pictures */
719     for( i_pic = 0; i_pic < p_vout->render.i_pictures; i_pic++ )
720     {
721         picture_t *p_pic = p_vout->render.pp_picture[i_pic];
722
723         msg_Dbg( p_vout, "[%d] %d %d", i_pic, p_pic->i_status, p_pic->i_refcount );
724         p_pic->i_refcount = 0;
725
726         switch( p_pic->i_status )
727         {
728         case READY_PICTURE:
729         case DISPLAYED_PICTURE:
730         case RESERVED_PICTURE:
731             if( p_pic != p_vout->p->p_picture_displayed )
732                 vout_UsePictureLocked( p_vout, p_pic );
733             break;
734         }
735     }
736     vlc_cond_signal( &p_vout->p->picture_wait );
737     vlc_mutex_unlock( &p_vout->picture_lock );
738 }
739 void vout_NextPicture( vout_thread_t *p_vout, mtime_t *pi_duration )
740 {
741     vlc_mutex_lock( &p_vout->picture_lock );
742
743     const mtime_t i_displayed_date = p_vout->p->i_picture_displayed_date;
744
745     p_vout->p->b_picture_displayed = false;
746     p_vout->p->b_picture_empty = false;
747     if( p_vout->p->p_picture_displayed )
748     {
749         p_vout->p->p_picture_displayed->date = 1;
750         vlc_cond_signal( &p_vout->p->picture_wait );
751     }
752
753     while( !p_vout->p->b_picture_displayed && !p_vout->p->b_picture_empty )
754         vlc_cond_wait( &p_vout->p->picture_wait, &p_vout->picture_lock );
755
756     *pi_duration = __MAX( p_vout->p->i_picture_displayed_date - i_displayed_date, 0 );
757
758     /* TODO advance subpicture by the duration ... */
759
760     vlc_mutex_unlock( &p_vout->picture_lock );
761 }
762
763 void vout_DisplayTitle( vout_thread_t *p_vout, const char *psz_title )
764 {
765     assert( psz_title );
766
767     if( !config_GetInt( p_vout, "osd" ) )
768         return;
769
770     vlc_mutex_lock( &p_vout->change_lock );
771     free( p_vout->p->psz_title );
772     p_vout->p->psz_title = strdup( psz_title );
773     vlc_mutex_unlock( &p_vout->change_lock );
774 }
775
776 spu_t *vout_GetSpu( vout_thread_t *p_vout )
777 {
778     return p_vout->p_spu;
779 }
780
781 /*****************************************************************************
782  * InitThread: initialize video output thread
783  *****************************************************************************
784  * This function is called from RunThread and performs the second step of the
785  * initialization. It returns 0 on success. Note that the thread's flag are not
786  * modified inside this function.
787  * XXX You have to enter it with change_lock taken.
788  *****************************************************************************/
789 static int ChromaCreate( vout_thread_t *p_vout );
790 static void ChromaDestroy( vout_thread_t *p_vout );
791
792 static bool ChromaIsEqual( const picture_heap_t *p_output, const picture_heap_t *p_render )
793 {
794      if( !vout_ChromaCmp( p_output->i_chroma, p_render->i_chroma ) )
795          return false;
796
797      if( p_output->i_chroma != VLC_CODEC_RGB15 &&
798          p_output->i_chroma != VLC_CODEC_RGB16 &&
799          p_output->i_chroma != VLC_CODEC_RGB24 &&
800          p_output->i_chroma != VLC_CODEC_RGB32 )
801          return true;
802
803      return p_output->i_rmask == p_render->i_rmask &&
804             p_output->i_gmask == p_render->i_gmask &&
805             p_output->i_bmask == p_render->i_bmask;
806 }
807
808 static int InitThread( vout_thread_t *p_vout )
809 {
810     int i, i_aspect_x, i_aspect_y;
811
812     /* Initialize output method, it allocates direct buffers for us */
813     if( p_vout->pf_init( p_vout ) )
814         return VLC_EGENERIC;
815
816     p_vout->p->p_picture_displayed = NULL;
817
818     if( !I_OUTPUTPICTURES )
819     {
820         msg_Err( p_vout, "plugin was unable to allocate at least "
821                          "one direct buffer" );
822         p_vout->pf_end( p_vout );
823         return VLC_EGENERIC;
824     }
825
826     if( I_OUTPUTPICTURES > VOUT_MAX_PICTURES )
827     {
828         msg_Err( p_vout, "plugin allocated too many direct buffers, "
829                          "our internal buffers must have overflown." );
830         p_vout->pf_end( p_vout );
831         return VLC_EGENERIC;
832     }
833
834     msg_Dbg( p_vout, "got %i direct buffer(s)", I_OUTPUTPICTURES );
835
836     AspectRatio( p_vout->fmt_render.i_aspect, &i_aspect_x, &i_aspect_y );
837
838     AspectRatio( p_vout->fmt_in.i_aspect, &i_aspect_x, &i_aspect_y );
839
840     if( !p_vout->fmt_out.i_width || !p_vout->fmt_out.i_height )
841     {
842         p_vout->fmt_out.i_width = p_vout->fmt_out.i_visible_width =
843             p_vout->output.i_width;
844         p_vout->fmt_out.i_height = p_vout->fmt_out.i_visible_height =
845             p_vout->output.i_height;
846         p_vout->fmt_out.i_x_offset =  p_vout->fmt_out.i_y_offset = 0;
847
848         p_vout->fmt_out.i_aspect = p_vout->output.i_aspect;
849         p_vout->fmt_out.i_chroma = p_vout->output.i_chroma;
850     }
851     if( !p_vout->fmt_out.i_sar_num || !p_vout->fmt_out.i_sar_num )
852     {
853         p_vout->fmt_out.i_sar_num = p_vout->fmt_out.i_aspect *
854             p_vout->fmt_out.i_height;
855         p_vout->fmt_out.i_sar_den = VOUT_ASPECT_FACTOR *
856             p_vout->fmt_out.i_width;
857     }
858
859     vlc_ureduce( &p_vout->fmt_out.i_sar_num, &p_vout->fmt_out.i_sar_den,
860                  p_vout->fmt_out.i_sar_num, p_vout->fmt_out.i_sar_den, 0 );
861
862     AspectRatio( p_vout->fmt_out.i_aspect, &i_aspect_x, &i_aspect_y );
863
864     /* FIXME removed the need of both fmt_* and heap infos */
865     /* Calculate shifts from system-updated masks */
866     PictureHeapFixRgb( &p_vout->render );
867     VideoFormatImportRgb( &p_vout->fmt_render, &p_vout->render );
868
869     PictureHeapFixRgb( &p_vout->output );
870     VideoFormatImportRgb( &p_vout->fmt_out, &p_vout->output );
871
872     /* print some usefull debug info about different vout formats
873      */
874     msg_Dbg( p_vout, "pic render sz %ix%i, of (%i,%i), vsz %ix%i, 4cc %4.4s, ar %i:%i, sar %i:%i, msk r0x%x g0x%x b0x%x",
875              p_vout->fmt_render.i_width, p_vout->fmt_render.i_height,
876              p_vout->fmt_render.i_x_offset, p_vout->fmt_render.i_y_offset,
877              p_vout->fmt_render.i_visible_width,
878              p_vout->fmt_render.i_visible_height,
879              (char*)&p_vout->fmt_render.i_chroma,
880              i_aspect_x, i_aspect_y,
881              p_vout->fmt_render.i_sar_num, p_vout->fmt_render.i_sar_den,
882              p_vout->fmt_render.i_rmask, p_vout->fmt_render.i_gmask, p_vout->fmt_render.i_bmask );
883
884     msg_Dbg( p_vout, "pic in sz %ix%i, of (%i,%i), vsz %ix%i, 4cc %4.4s, ar %i:%i, sar %i:%i, msk r0x%x g0x%x b0x%x",
885              p_vout->fmt_in.i_width, p_vout->fmt_in.i_height,
886              p_vout->fmt_in.i_x_offset, p_vout->fmt_in.i_y_offset,
887              p_vout->fmt_in.i_visible_width,
888              p_vout->fmt_in.i_visible_height,
889              (char*)&p_vout->fmt_in.i_chroma,
890              i_aspect_x, i_aspect_y,
891              p_vout->fmt_in.i_sar_num, p_vout->fmt_in.i_sar_den,
892              p_vout->fmt_in.i_rmask, p_vout->fmt_in.i_gmask, p_vout->fmt_in.i_bmask );
893
894     msg_Dbg( p_vout, "pic out sz %ix%i, of (%i,%i), vsz %ix%i, 4cc %4.4s, ar %i:%i, sar %i:%i, msk r0x%x g0x%x b0x%x",
895              p_vout->fmt_out.i_width, p_vout->fmt_out.i_height,
896              p_vout->fmt_out.i_x_offset, p_vout->fmt_out.i_y_offset,
897              p_vout->fmt_out.i_visible_width,
898              p_vout->fmt_out.i_visible_height,
899              (char*)&p_vout->fmt_out.i_chroma,
900              i_aspect_x, i_aspect_y,
901              p_vout->fmt_out.i_sar_num, p_vout->fmt_out.i_sar_den,
902              p_vout->fmt_out.i_rmask, p_vout->fmt_out.i_gmask, p_vout->fmt_out.i_bmask );
903
904     /* Check whether we managed to create direct buffers similar to
905      * the render buffers, ie same size and chroma */
906     if( ( p_vout->output.i_width == p_vout->render.i_width )
907      && ( p_vout->output.i_height == p_vout->render.i_height )
908      && ( ChromaIsEqual( &p_vout->output, &p_vout->render ) ) )
909     {
910         /* Cool ! We have direct buffers, we can ask the decoder to
911          * directly decode into them ! Map the first render buffers to
912          * the first direct buffers, but keep the first direct buffer
913          * for memcpy operations */
914         p_vout->p->b_direct = true;
915
916         for( i = 1; i < VOUT_MAX_PICTURES; i++ )
917         {
918             if( p_vout->p_picture[ i ].i_type != DIRECT_PICTURE &&
919                 I_RENDERPICTURES >= VOUT_MIN_DIRECT_PICTURES - 1 &&
920                 p_vout->p_picture[ i - 1 ].i_type == DIRECT_PICTURE )
921             {
922                 /* We have enough direct buffers so there's no need to
923                  * try to use system memory buffers. */
924                 break;
925             }
926             PP_RENDERPICTURE[ I_RENDERPICTURES ] = &p_vout->p_picture[ i ];
927             I_RENDERPICTURES++;
928         }
929
930         msg_Dbg( p_vout, "direct render, mapping "
931                  "render pictures 0-%i to system pictures 1-%i",
932                  VOUT_MAX_PICTURES - 2, VOUT_MAX_PICTURES - 1 );
933     }
934     else
935     {
936         /* Rats... Something is wrong here, we could not find an output
937          * plugin able to directly render what we decode. See if we can
938          * find a chroma plugin to do the conversion */
939         p_vout->p->b_direct = false;
940
941         if( ChromaCreate( p_vout ) )
942         {
943             p_vout->pf_end( p_vout );
944             return VLC_EGENERIC;
945         }
946
947         msg_Dbg( p_vout, "indirect render, mapping "
948                  "render pictures 0-%i to system pictures %i-%i",
949                  VOUT_MAX_PICTURES - 1, I_OUTPUTPICTURES,
950                  I_OUTPUTPICTURES + VOUT_MAX_PICTURES - 1 );
951
952         /* Append render buffers after the direct buffers */
953         for( i = I_OUTPUTPICTURES; i < 2 * VOUT_MAX_PICTURES; i++ )
954         {
955             PP_RENDERPICTURE[ I_RENDERPICTURES ] = &p_vout->p_picture[ i ];
956             I_RENDERPICTURES++;
957
958             /* Check if we have enough render pictures */
959             if( I_RENDERPICTURES == VOUT_MAX_PICTURES )
960                 break;
961         }
962     }
963
964     return VLC_SUCCESS;
965 }
966
967 /*****************************************************************************
968  * RunThread: video output thread
969  *****************************************************************************
970  * Video output thread. This function does only returns when the thread is
971  * terminated. It handles the pictures arriving in the video heap and the
972  * display device events.
973  *****************************************************************************/
974 static void* RunThread( void *p_this )
975 {
976     vout_thread_t *p_vout = p_this;
977     int             i_idle_loops = 0;  /* loops without displaying a picture */
978     int             i_picture_qtype_last = QTYPE_NONE;
979     bool            b_picture_interlaced_last = false;
980     mtime_t         i_picture_interlaced_last_date;
981
982     /*
983      * Initialize thread
984      */
985     p_vout->p_module = module_need( p_vout,
986                                     p_vout->p->psz_module_type,
987                                     p_vout->p->psz_module_name,
988                                     !strcmp(p_vout->p->psz_module_type, "video filter") );
989
990     vlc_mutex_lock( &p_vout->change_lock );
991
992     if( p_vout->p_module )
993         p_vout->b_error = InitThread( p_vout );
994     else
995         p_vout->b_error = true;
996
997     /* signal the creation of the vout */
998     p_vout->p->b_ready = true;
999     vlc_cond_signal( &p_vout->p->change_wait );
1000
1001     if( p_vout->b_error )
1002         goto exit_thread;
1003
1004     /* */
1005     const bool b_drop_late = var_CreateGetBool( p_vout, "drop-late-frames" );
1006     i_picture_interlaced_last_date = mdate();
1007
1008     /*
1009      * Main loop - it is not executed if an error occurred during
1010      * initialization
1011      */
1012     while( !p_vout->p->b_done && !p_vout->b_error )
1013     {
1014         /* Initialize loop variables */
1015         const mtime_t current_date = mdate();
1016         picture_t *p_picture;
1017         picture_t *p_filtered_picture;
1018         mtime_t display_date;
1019         picture_t *p_directbuffer;
1020         int i_index;
1021
1022         if( p_vout->p->b_title_show && p_vout->p->psz_title )
1023             DisplayTitleOnOSD( p_vout );
1024
1025         vlc_mutex_lock( &p_vout->picture_lock );
1026
1027         /* Look for the earliest picture but after the last displayed one */
1028         picture_t *p_last = p_vout->p->p_picture_displayed;;
1029
1030         p_picture = NULL;
1031         for( i_index = 0; i_index < I_RENDERPICTURES; i_index++ )
1032         {
1033             picture_t *p_pic = PP_RENDERPICTURE[i_index];
1034
1035             if( p_pic->i_status != READY_PICTURE )
1036                 continue;
1037
1038             if( p_vout->p->b_paused && p_last && p_last->date > 1 )
1039                 continue;
1040
1041             if( p_last && p_pic != p_last && p_pic->date <= p_last->date )
1042             {
1043                 /* Drop old picture */
1044                 vout_UsePictureLocked( p_vout, p_pic );
1045             }
1046             else if( !p_vout->p->b_paused && !p_pic->b_force && p_pic != p_last &&
1047                      p_pic->date < current_date + p_vout->p->render_time &&
1048                      b_drop_late )
1049             {
1050                 /* Picture is late: it will be destroyed and the thread
1051                  * will directly choose the next picture */
1052                 vout_UsePictureLocked( p_vout, p_pic );
1053                 vout_statistic_Update( &p_vout->p->statistic, 0, 1 );
1054
1055                 msg_Warn( p_vout, "late picture skipped (%"PRId64" > %d)",
1056                                   current_date - p_pic->date, - p_vout->p->render_time );
1057             }
1058             else if( ( !p_last || p_last->date < p_pic->date ) &&
1059                      ( p_picture == NULL || p_pic->date < p_picture->date ) )
1060             {
1061                 p_picture = p_pic;
1062             }
1063         }
1064         if( !p_picture )
1065         {
1066             p_picture = p_last;
1067
1068             if( !p_vout->p->b_picture_empty )
1069             {
1070                 p_vout->p->b_picture_empty = true;
1071                 vlc_cond_signal( &p_vout->p->picture_wait );
1072             }
1073         }
1074
1075         display_date = 0;
1076         if( p_picture )
1077         {
1078             display_date = p_picture->date;
1079
1080             /* If we found better than the last picture, destroy it */
1081             if( p_last && p_picture != p_last )
1082             {
1083                 vout_UsePictureLocked( p_vout, p_last );
1084                 p_vout->p->p_picture_displayed = p_last = NULL;
1085             }
1086
1087             /* Compute FPS rate */
1088             p_vout->p->p_fps_sample[ p_vout->p->c_fps_samples++ % VOUT_FPS_SAMPLES ] = display_date;
1089
1090             if( !p_vout->p->b_paused && display_date > current_date + VOUT_DISPLAY_DELAY )
1091             {
1092                 /* A picture is ready to be rendered, but its rendering date
1093                  * is far from the current one so the thread will perform an
1094                  * empty loop as if no picture were found. The picture state
1095                  * is unchanged */
1096                 p_picture    = NULL;
1097                 display_date = 0;
1098             }
1099             else if( p_picture == p_last )
1100             {
1101                 /* We are asked to repeat the previous picture, but we first
1102                  * wait for a couple of idle loops */
1103                 if( i_idle_loops < 4 )
1104                 {
1105                     p_picture    = NULL;
1106                     display_date = 0;
1107                 }
1108                 else
1109                 {
1110                     /* We set the display date to something high, otherwise
1111                      * we'll have lots of problems with late pictures */
1112                     display_date = current_date + p_vout->p->render_time;
1113                 }
1114             }
1115             else if( p_vout->p->b_paused && display_date > current_date + VOUT_DISPLAY_DELAY )
1116             {
1117                 display_date = current_date + VOUT_DISPLAY_DELAY;
1118             }
1119
1120             if( p_picture )
1121             {
1122                 if( p_picture->date > 1 )
1123                 {
1124                     p_vout->p->i_picture_displayed_date = p_picture->date;
1125                     if( p_picture != p_last && !p_vout->p->b_picture_displayed )
1126                     {
1127                         p_vout->p->b_picture_displayed = true;
1128                         vlc_cond_signal( &p_vout->p->picture_wait );
1129                     }
1130                 }
1131                 p_vout->p->p_picture_displayed = p_picture;
1132             }
1133         }
1134
1135         /* */
1136         const int i_postproc_type = p_vout->p->i_picture_qtype;
1137         const int i_postproc_state = (p_vout->p->i_picture_qtype != QTYPE_NONE) - (i_picture_qtype_last != QTYPE_NONE);
1138
1139         const bool b_picture_interlaced = p_vout->p->b_picture_interlaced;
1140         const int  i_picture_interlaced_state = (!!p_vout->p->b_picture_interlaced) - (!!b_picture_interlaced_last);
1141
1142         vlc_mutex_unlock( &p_vout->picture_lock );
1143
1144         if( p_picture == NULL )
1145             i_idle_loops++;
1146
1147         p_filtered_picture = NULL;
1148         if( p_picture )
1149             p_filtered_picture = filter_chain_VideoFilter( p_vout->p->p_vf2_chain,
1150                                                            p_picture );
1151
1152         const bool b_snapshot = vout_snapshot_IsRequested( &p_vout->p->snapshot );
1153
1154         /*
1155          * Check for subpictures to display
1156          */
1157         mtime_t spu_render_time;
1158         if( p_vout->p->b_paused )
1159             spu_render_time = p_vout->p->i_pause_date;
1160         else if( p_picture )
1161             spu_render_time = p_picture->date > 1 ? p_picture->date : mdate();
1162         else
1163             spu_render_time = 0;
1164
1165         subpicture_t *p_subpic = spu_SortSubpictures( p_vout->p_spu,
1166                                                       spu_render_time,
1167                                                       b_snapshot );
1168         /*
1169          * Perform rendering
1170          */
1171         vout_statistic_Update( &p_vout->p->statistic, 1, 0 );
1172         p_directbuffer = vout_RenderPicture( p_vout,
1173                                              p_filtered_picture, p_subpic,
1174                                              spu_render_time );
1175
1176         /*
1177          * Take a snapshot if requested
1178          */
1179         if( p_directbuffer && b_snapshot )
1180             vout_snapshot_Set( &p_vout->p->snapshot,
1181                                &p_vout->fmt_out, p_directbuffer );
1182
1183         /*
1184          * Call the plugin-specific rendering method if there is one
1185          */
1186         if( p_filtered_picture != NULL && p_directbuffer != NULL && p_vout->pf_render )
1187         {
1188             /* Render the direct buffer returned by vout_RenderPicture */
1189             p_vout->pf_render( p_vout, p_directbuffer );
1190         }
1191
1192         /*
1193          * Sleep, wake up
1194          */
1195         if( display_date != 0 && p_directbuffer != NULL )
1196         {
1197             mtime_t current_render_time = mdate() - current_date;
1198             /* if render time is very large we don't include it in the mean */
1199             if( current_render_time < p_vout->p->render_time +
1200                 VOUT_DISPLAY_DELAY )
1201             {
1202                 /* Store render time using a sliding mean weighting to
1203                  * current value in a 3 to 1 ratio*/
1204                 p_vout->p->render_time *= 3;
1205                 p_vout->p->render_time += current_render_time;
1206                 p_vout->p->render_time >>= 2;
1207             }
1208             else
1209                 msg_Dbg( p_vout, "skipped big render time %d > %d", (int) current_render_time,
1210                  (int) (p_vout->p->render_time +VOUT_DISPLAY_DELAY ) ) ;
1211         }
1212
1213         /* Give back change lock */
1214         vlc_mutex_unlock( &p_vout->change_lock );
1215
1216         /* Sleep a while or until a given date */
1217         if( display_date != 0 )
1218         {
1219             /* If there are *vout* filters in the chain, better give them the picture
1220              * in advance */
1221             if( !p_vout->p->psz_filter_chain || !*p_vout->p->psz_filter_chain )
1222             {
1223                 mwait( display_date - VOUT_MWAIT_TOLERANCE );
1224             }
1225         }
1226         else
1227         {
1228             /* Wait until a frame is being sent or a spurious wakeup (not a problem here) */
1229             vlc_mutex_lock( &p_vout->picture_lock );
1230             vlc_cond_timedwait( &p_vout->p->picture_wait, &p_vout->picture_lock, current_date + VOUT_IDLE_SLEEP );
1231             vlc_mutex_unlock( &p_vout->picture_lock );
1232         }
1233
1234         /* On awakening, take back lock and send immediately picture
1235          * to display. */
1236         /* Note: p_vout->p->b_done could be true here and now */
1237         vlc_mutex_lock( &p_vout->change_lock );
1238
1239         /*
1240          * Display the previously rendered picture
1241          */
1242         if( p_filtered_picture != NULL && p_directbuffer != NULL )
1243         {
1244             /* Display the direct buffer returned by vout_RenderPicture */
1245             if( p_vout->pf_display )
1246                 p_vout->pf_display( p_vout, p_directbuffer );
1247
1248             /* Tell the vout this was the last picture and that it does not
1249              * need to be forced anymore. */
1250             p_picture->b_force = false;
1251         }
1252
1253         /* Drop the filtered picture if created by video filters */
1254         if( p_filtered_picture != NULL && p_filtered_picture != p_picture )
1255         {
1256             vlc_mutex_lock( &p_vout->picture_lock );
1257             vout_UsePictureLocked( p_vout, p_filtered_picture );
1258             vlc_mutex_unlock( &p_vout->picture_lock );
1259         }
1260
1261         if( p_picture != NULL )
1262         {
1263             /* Reinitialize idle loop count */
1264             i_idle_loops = 0;
1265         }
1266
1267         /*
1268          * Check events and manage thread
1269          */
1270         if( p_vout->pf_manage && p_vout->pf_manage( p_vout ) )
1271         {
1272             /* A fatal error occurred, and the thread must terminate
1273              * immediately, without displaying anything - setting b_error to 1
1274              * causes the immediate end of the main while() loop. */
1275             // FIXME pf_end
1276             p_vout->b_error = 1;
1277             break;
1278         }
1279
1280         while( p_vout->i_changes & VOUT_ON_TOP_CHANGE )
1281         {
1282             p_vout->i_changes &= ~VOUT_ON_TOP_CHANGE;
1283             vlc_mutex_unlock( &p_vout->change_lock );
1284             vout_Control( p_vout, VOUT_SET_STAY_ON_TOP, p_vout->b_on_top );
1285             vlc_mutex_lock( &p_vout->change_lock );
1286         }
1287
1288         if( p_vout->i_changes & VOUT_SIZE_CHANGE )
1289         {
1290             /* this must only happen when the vout plugin is incapable of
1291              * rescaling the picture itself. In this case we need to destroy
1292              * the current picture buffers and recreate new ones with the right
1293              * dimensions */
1294             int i;
1295
1296             p_vout->i_changes &= ~VOUT_SIZE_CHANGE;
1297
1298             assert( !p_vout->p->b_direct );
1299
1300             ChromaDestroy( p_vout );
1301
1302             vlc_mutex_lock( &p_vout->picture_lock );
1303
1304             p_vout->pf_end( p_vout );
1305
1306             p_vout->p->p_picture_displayed = NULL;
1307             for( i = 0; i < I_OUTPUTPICTURES; i++ )
1308                  p_vout->p_picture[ i ].i_status = FREE_PICTURE;
1309             vlc_cond_signal( &p_vout->p->picture_wait );
1310
1311             I_OUTPUTPICTURES = 0;
1312
1313             if( p_vout->pf_init( p_vout ) )
1314             {
1315                 msg_Err( p_vout, "cannot resize display" );
1316                 /* FIXME: pf_end will be called again in CleanThread()? */
1317                 p_vout->b_error = 1;
1318             }
1319
1320             vlc_mutex_unlock( &p_vout->picture_lock );
1321
1322             /* Need to reinitialise the chroma plugin. Since we might need
1323              * resizing too and it's not sure that we already had it,
1324              * recreate the chroma plugin chain from scratch. */
1325             /* dionoea */
1326             if( ChromaCreate( p_vout ) )
1327             {
1328                 msg_Err( p_vout, "WOW THIS SUCKS BIG TIME!!!!!" );
1329                 p_vout->b_error = 1;
1330             }
1331             if( p_vout->b_error )
1332                 break;
1333         }
1334
1335         if( p_vout->i_changes & VOUT_PICTURE_BUFFERS_CHANGE )
1336         {
1337             /* This happens when the picture buffers need to be recreated.
1338              * This is useful on multimonitor displays for instance.
1339              *
1340              * Warning: This only works when the vout creates only 1 picture
1341              * buffer!! */
1342             p_vout->i_changes &= ~VOUT_PICTURE_BUFFERS_CHANGE;
1343
1344             if( !p_vout->p->b_direct )
1345                 ChromaDestroy( p_vout );
1346
1347             vlc_mutex_lock( &p_vout->picture_lock );
1348
1349             p_vout->pf_end( p_vout );
1350
1351             I_OUTPUTPICTURES = I_RENDERPICTURES = 0;
1352
1353             p_vout->b_error = InitThread( p_vout );
1354             if( p_vout->b_error )
1355                 msg_Err( p_vout, "InitThread after VOUT_PICTURE_BUFFERS_CHANGE failed" );
1356
1357             vlc_cond_signal( &p_vout->p->picture_wait );
1358             vlc_mutex_unlock( &p_vout->picture_lock );
1359
1360             if( p_vout->b_error )
1361                 break;
1362         }
1363
1364         /* Post processing */
1365         if( i_postproc_state == 1 )
1366             PostProcessEnable( p_vout );
1367         else if( i_postproc_state == -1 )
1368             PostProcessDisable( p_vout );
1369         if( i_postproc_state != 0 )
1370             i_picture_qtype_last = i_postproc_type;
1371
1372         /* Deinterlacing
1373          * Wait 30s before quiting interlacing mode */
1374         if( ( i_picture_interlaced_state == 1 ) ||
1375             ( i_picture_interlaced_state == -1 && i_picture_interlaced_last_date + 30000000 < current_date ) )
1376         {
1377             DeinterlaceNeeded( p_vout, b_picture_interlaced );
1378             b_picture_interlaced_last = b_picture_interlaced;
1379         }
1380         if( b_picture_interlaced )
1381             i_picture_interlaced_last_date = current_date;
1382
1383
1384         /* Check for "video filter2" changes */
1385         vlc_mutex_lock( &p_vout->p->vfilter_lock );
1386         if( p_vout->p->psz_vf2 )
1387         {
1388             es_format_t fmt;
1389
1390             es_format_Init( &fmt, VIDEO_ES, p_vout->fmt_render.i_chroma );
1391             fmt.video = p_vout->fmt_render;
1392             filter_chain_Reset( p_vout->p->p_vf2_chain, &fmt, &fmt );
1393
1394             if( filter_chain_AppendFromString( p_vout->p->p_vf2_chain,
1395                                                p_vout->p->psz_vf2 ) < 0 )
1396                 msg_Err( p_vout, "Video filter chain creation failed" );
1397
1398             free( p_vout->p->psz_vf2 );
1399             p_vout->p->psz_vf2 = NULL;
1400
1401             if( i_picture_qtype_last != QTYPE_NONE )
1402                 PostProcessSetFilterQuality( p_vout );
1403         }
1404         vlc_mutex_unlock( &p_vout->p->vfilter_lock );
1405     }
1406
1407     /*
1408      * Error loop - wait until the thread destruction is requested
1409      */
1410     if( p_vout->b_error )
1411         ErrorThread( p_vout );
1412
1413     /* Clean thread */
1414     CleanThread( p_vout );
1415
1416 exit_thread:
1417     /* End of thread */
1418     EndThread( p_vout );
1419     vlc_mutex_unlock( &p_vout->change_lock );
1420
1421     if( p_vout->p_module )
1422         module_unneed( p_vout, p_vout->p_module );
1423     p_vout->p_module = NULL;
1424
1425     return NULL;
1426 }
1427
1428 /*****************************************************************************
1429  * ErrorThread: RunThread() error loop
1430  *****************************************************************************
1431  * This function is called when an error occurred during thread main's loop.
1432  * The thread can still receive feed, but must be ready to terminate as soon
1433  * as possible.
1434  *****************************************************************************/
1435 static void ErrorThread( vout_thread_t *p_vout )
1436 {
1437     /* Wait until a `close' order */
1438     while( !p_vout->p->b_done )
1439         vlc_cond_wait( &p_vout->p->change_wait, &p_vout->change_lock );
1440 }
1441
1442 /*****************************************************************************
1443  * CleanThread: clean up after InitThread
1444  *****************************************************************************
1445  * This function is called after a sucessful
1446  * initialization. It frees all resources allocated by InitThread.
1447  * XXX You have to enter it with change_lock taken.
1448  *****************************************************************************/
1449 static void CleanThread( vout_thread_t *p_vout )
1450 {
1451     int     i_index;                                        /* index in heap */
1452
1453     if( !p_vout->p->b_direct )
1454         ChromaDestroy( p_vout );
1455
1456     /* Destroy all remaining pictures */
1457     for( i_index = 0; i_index < 2 * VOUT_MAX_PICTURES + 1; i_index++ )
1458     {
1459         if ( p_vout->p_picture[i_index].i_type == MEMORY_PICTURE )
1460         {
1461             free( p_vout->p_picture[i_index].p_data_orig );
1462         }
1463     }
1464
1465     /* Destroy translation tables */
1466     if( !p_vout->b_error )
1467         p_vout->pf_end( p_vout );
1468 }
1469
1470 /*****************************************************************************
1471  * EndThread: thread destruction
1472  *****************************************************************************
1473  * This function is called when the thread ends.
1474  * It frees all resources not allocated by InitThread.
1475  * XXX You have to enter it with change_lock taken.
1476  *****************************************************************************/
1477 static void EndThread( vout_thread_t *p_vout )
1478 {
1479 #ifdef STATS
1480     {
1481         struct tms cpu_usage;
1482         times( &cpu_usage );
1483
1484         msg_Dbg( p_vout, "cpu usage (user: %d, system: %d)",
1485                  cpu_usage.tms_utime, cpu_usage.tms_stime );
1486     }
1487 #endif
1488
1489     /* FIXME does that function *really* need to be called inside the thread ? */
1490
1491     /* Detach subpicture unit from both input and vout */
1492     spu_Attach( p_vout->p_spu, VLC_OBJECT(p_vout), false );
1493     vlc_object_detach( p_vout->p_spu );
1494
1495     /* Destroy the video filters2 */
1496     filter_chain_Delete( p_vout->p->p_vf2_chain );
1497 }
1498
1499 /* Thread helpers */
1500 static picture_t *ChromaGetPicture( filter_t *p_filter )
1501 {
1502     picture_t *p_pic = (picture_t *)p_filter->p_owner;
1503     p_filter->p_owner = NULL;
1504     return p_pic;
1505 }
1506
1507 static int ChromaCreate( vout_thread_t *p_vout )
1508 {
1509     static const char typename[] = "chroma";
1510     filter_t *p_chroma;
1511
1512     /* Choose the best module */
1513     p_chroma = p_vout->p->p_chroma =
1514         vlc_custom_create( p_vout, sizeof(filter_t), VLC_OBJECT_GENERIC,
1515                            typename );
1516
1517     vlc_object_attach( p_chroma, p_vout );
1518
1519     /* TODO: Set the fmt_in and fmt_out stuff here */
1520     p_chroma->fmt_in.video = p_vout->fmt_render;
1521     p_chroma->fmt_out.video = p_vout->fmt_out;
1522     VideoFormatImportRgb( &p_chroma->fmt_in.video, &p_vout->render );
1523     VideoFormatImportRgb( &p_chroma->fmt_out.video, &p_vout->output );
1524
1525     p_chroma->p_module = module_need( p_chroma, "video filter2", NULL, false );
1526
1527     if( p_chroma->p_module == NULL )
1528     {
1529         msg_Err( p_vout, "no chroma module for %4.4s to %4.4s i=%dx%d o=%dx%d",
1530                  (char*)&p_vout->render.i_chroma,
1531                  (char*)&p_vout->output.i_chroma,
1532                  p_chroma->fmt_in.video.i_width, p_chroma->fmt_in.video.i_height,
1533                  p_chroma->fmt_out.video.i_width, p_chroma->fmt_out.video.i_height
1534                  );
1535
1536         vlc_object_release( p_vout->p->p_chroma );
1537         p_vout->p->p_chroma = NULL;
1538
1539         return VLC_EGENERIC;
1540     }
1541     p_chroma->pf_vout_buffer_new = ChromaGetPicture;
1542     return VLC_SUCCESS;
1543 }
1544
1545 static void ChromaDestroy( vout_thread_t *p_vout )
1546 {
1547     assert( !p_vout->p->b_direct );
1548
1549     if( !p_vout->p->p_chroma )
1550         return;
1551
1552     module_unneed( p_vout->p->p_chroma, p_vout->p->p_chroma->p_module );
1553     vlc_object_release( p_vout->p->p_chroma );
1554     p_vout->p->p_chroma = NULL;
1555 }
1556
1557 /* following functions are local */
1558 static void AspectRatio( int i_aspect, int *i_aspect_x, int *i_aspect_y )
1559 {
1560     const int i_pgcd = i_aspect ? GCD( i_aspect, VOUT_ASPECT_FACTOR ) : 1;
1561     *i_aspect_x = i_aspect / i_pgcd;
1562     *i_aspect_y = VOUT_ASPECT_FACTOR / i_pgcd;
1563 }
1564
1565 /**
1566  * This function copies all RGB informations from a picture_heap_t into
1567  * a video_format_t
1568  */
1569 static void VideoFormatImportRgb( video_format_t *p_fmt, const picture_heap_t *p_heap )
1570 {
1571     p_fmt->i_rmask = p_heap->i_rmask;
1572     p_fmt->i_gmask = p_heap->i_gmask;
1573     p_fmt->i_bmask = p_heap->i_bmask;
1574     p_fmt->i_rrshift = p_heap->i_rrshift;
1575     p_fmt->i_lrshift = p_heap->i_lrshift;
1576     p_fmt->i_rgshift = p_heap->i_rgshift;
1577     p_fmt->i_lgshift = p_heap->i_lgshift;
1578     p_fmt->i_rbshift = p_heap->i_rbshift;
1579     p_fmt->i_lbshift = p_heap->i_lbshift;
1580 }
1581
1582 /**
1583  * This funtion copes all RGB informations from a video_format_t into
1584  * a picture_heap_t
1585  */
1586 static void VideoFormatExportRgb( const video_format_t *p_fmt, picture_heap_t *p_heap )
1587 {
1588     p_heap->i_rmask = p_fmt->i_rmask;
1589     p_heap->i_gmask = p_fmt->i_gmask;
1590     p_heap->i_bmask = p_fmt->i_bmask;
1591     p_heap->i_rrshift = p_fmt->i_rrshift;
1592     p_heap->i_lrshift = p_fmt->i_lrshift;
1593     p_heap->i_rgshift = p_fmt->i_rgshift;
1594     p_heap->i_lgshift = p_fmt->i_lgshift;
1595     p_heap->i_rbshift = p_fmt->i_rbshift;
1596     p_heap->i_lbshift = p_fmt->i_lbshift;
1597 }
1598
1599 /**
1600  * This function computes rgb shifts from masks
1601  */
1602 static void PictureHeapFixRgb( picture_heap_t *p_heap )
1603 {
1604     video_format_t fmt;
1605
1606     /* */
1607     fmt.i_chroma = p_heap->i_chroma;
1608     VideoFormatImportRgb( &fmt, p_heap );
1609
1610     /* */
1611     video_format_FixRgb( &fmt );
1612
1613     VideoFormatExportRgb( &fmt, p_heap );
1614 }
1615
1616 /*****************************************************************************
1617  * object variables callbacks: a bunch of object variables are used by the
1618  * interfaces to interact with the vout.
1619  *****************************************************************************/
1620 static int FilterCallback( vlc_object_t *p_this, char const *psz_cmd,
1621                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
1622 {
1623     vout_thread_t *p_vout = (vout_thread_t *)p_this;
1624     input_thread_t *p_input;
1625     (void)psz_cmd; (void)oldval; (void)p_data;
1626
1627     p_input = (input_thread_t *)vlc_object_find( p_this, VLC_OBJECT_INPUT,
1628                                                  FIND_PARENT );
1629     if (!p_input)
1630     {
1631         msg_Err( p_vout, "Input not found" );
1632         return VLC_EGENERIC;
1633     }
1634
1635     var_SetBool( p_vout, "intf-change", true );
1636
1637     /* Modify input as well because the vout might have to be restarted */
1638     var_Create( p_input, "vout-filter", VLC_VAR_STRING );
1639     var_SetString( p_input, "vout-filter", newval.psz_string );
1640
1641     /* Now restart current video stream */
1642     input_Control( p_input, INPUT_RESTART_ES, -VIDEO_ES );
1643     vlc_object_release( p_input );
1644
1645     return VLC_SUCCESS;
1646 }
1647
1648 /*****************************************************************************
1649  * Video Filter2 stuff
1650  *****************************************************************************/
1651 static int VideoFilter2Callback( vlc_object_t *p_this, char const *psz_cmd,
1652                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
1653 {
1654     vout_thread_t *p_vout = (vout_thread_t *)p_this;
1655     (void)psz_cmd; (void)oldval; (void)p_data;
1656
1657     vlc_mutex_lock( &p_vout->p->vfilter_lock );
1658     p_vout->p->psz_vf2 = strdup( newval.psz_string );
1659     vlc_mutex_unlock( &p_vout->p->vfilter_lock );
1660
1661     return VLC_SUCCESS;
1662 }
1663
1664 /*****************************************************************************
1665  * Post-processing
1666  *****************************************************************************/
1667 static bool PostProcessIsPresent( const char *psz_filter )
1668 {
1669     const char  *psz_pp = "postproc";
1670     const size_t i_pp = strlen(psz_pp);
1671     return psz_filter &&
1672            !strncmp( psz_filter, psz_pp, strlen(psz_pp) ) &&
1673            ( psz_filter[i_pp] == '\0' || psz_filter[i_pp] == ':' );
1674 }
1675
1676 static int PostProcessCallback( vlc_object_t *p_this, char const *psz_cmd,
1677                                 vlc_value_t oldval, vlc_value_t newval, void *p_data )
1678 {
1679     vout_thread_t *p_vout = (vout_thread_t *)p_this;
1680     VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval); VLC_UNUSED(p_data);
1681
1682     static const char *psz_pp = "postproc";
1683
1684     char *psz_vf2 = var_GetString( p_vout, "video-filter" );
1685
1686     if( newval.i_int <= 0 )
1687     {
1688         if( PostProcessIsPresent( psz_vf2 ) )
1689         {
1690             strcpy( psz_vf2, &psz_vf2[strlen(psz_pp)] );
1691             if( *psz_vf2 == ':' )
1692                 strcpy( psz_vf2, &psz_vf2[1] );
1693         }
1694     }
1695     else
1696     {
1697         if( !PostProcessIsPresent( psz_vf2 ) )
1698         {
1699             if( psz_vf2 )
1700             {
1701                 char *psz_tmp = psz_vf2;
1702                 if( asprintf( &psz_vf2, "%s:%s", psz_pp, psz_tmp ) < 0 )
1703                     psz_vf2 = psz_tmp;
1704                 else
1705                     free( psz_tmp );
1706             }
1707             else
1708             {
1709                 psz_vf2 = strdup( psz_pp );
1710             }
1711         }
1712     }
1713     if( psz_vf2 )
1714     {
1715         var_SetString( p_vout, "video-filter", psz_vf2 );
1716         free( psz_vf2 );
1717     }
1718
1719     return VLC_SUCCESS;
1720 }
1721 static void PostProcessEnable( vout_thread_t *p_vout )
1722 {
1723     vlc_value_t text;
1724     msg_Dbg( p_vout, "Post-processing available" );
1725     var_Create( p_vout, "postprocess", VLC_VAR_INTEGER | VLC_VAR_HASCHOICE );
1726     text.psz_string = _("Post processing");
1727     var_Change( p_vout, "postprocess", VLC_VAR_SETTEXT, &text, NULL );
1728
1729     for( int i = 0; i <= 6; i++ )
1730     {
1731         vlc_value_t val;
1732         vlc_value_t text;
1733         char psz_text[1+1];
1734
1735         val.i_int = i;
1736         snprintf( psz_text, sizeof(psz_text), "%d", i );
1737         if( i == 0 )
1738             text.psz_string = _("Disable");
1739         else
1740             text.psz_string = psz_text;
1741         var_Change( p_vout, "postprocess", VLC_VAR_ADDCHOICE, &val, &text );
1742     }
1743     var_AddCallback( p_vout, "postprocess", PostProcessCallback, NULL );
1744
1745     /* */
1746     char *psz_filter = var_GetNonEmptyString( p_vout, "video-filter" );
1747     int i_postproc_q = 0;
1748     if( PostProcessIsPresent( psz_filter ) )
1749         i_postproc_q = var_CreateGetInteger( p_vout, "postproc-q" );
1750
1751     var_SetInteger( p_vout, "postprocess", i_postproc_q );
1752
1753     free( psz_filter );
1754 }
1755 static void PostProcessDisable( vout_thread_t *p_vout )
1756 {
1757     msg_Dbg( p_vout, "Post-processing no more available" );
1758     var_Destroy( p_vout, "postprocess" );
1759 }
1760 static void PostProcessSetFilterQuality( vout_thread_t *p_vout )
1761 {
1762     vlc_object_t *p_pp = vlc_object_find_name( p_vout, "postproc", FIND_CHILD );
1763     if( !p_pp )
1764         return;
1765
1766     var_SetInteger( p_pp, "postproc-q", var_GetInteger( p_vout, "postprocess" ) );
1767     vlc_object_release( p_pp );
1768 }
1769
1770
1771 static void DisplayTitleOnOSD( vout_thread_t *p_vout )
1772 {
1773     const mtime_t i_start = mdate();
1774     const mtime_t i_stop = i_start + INT64_C(1000) * p_vout->p->i_title_timeout;
1775
1776     if( i_stop <= i_start )
1777         return;
1778
1779     vlc_assert_locked( &p_vout->change_lock );
1780
1781     vout_ShowTextAbsolute( p_vout, DEFAULT_CHAN,
1782                            p_vout->p->psz_title, NULL,
1783                            p_vout->p->i_title_position,
1784                            30 + p_vout->fmt_in.i_width
1785                               - p_vout->fmt_in.i_visible_width
1786                               - p_vout->fmt_in.i_x_offset,
1787                            20 + p_vout->fmt_in.i_y_offset,
1788                            i_start, i_stop );
1789
1790     free( p_vout->p->psz_title );
1791
1792     p_vout->p->psz_title = NULL;
1793 }
1794
1795 /*****************************************************************************
1796  * Deinterlacing
1797  *****************************************************************************/
1798 typedef struct
1799 {
1800     const char *psz_mode;
1801     bool       b_vout_filter;
1802 } deinterlace_mode_t;
1803
1804 /* XXX
1805  * You can use the non vout filter if and only if the video properties stay the
1806  * same (width/height/chroma/fps), at least for now.
1807  */
1808 static const deinterlace_mode_t p_deinterlace_mode[] = {
1809     { "",        false },
1810     { "discard", true },
1811     { "blend",   false },
1812     { "mean",    true  },
1813     { "bob",     true },
1814     { "linear",  true },
1815     { "x",       false },
1816     { "yadif",   true },
1817     { "yadif2x", true },
1818     { NULL,      true }
1819 };
1820
1821 static char *FilterFind( char *psz_filter_base, const char *psz_module )
1822 {
1823     const size_t i_module = strlen( psz_module );
1824     const char *psz_filter = psz_filter_base;
1825
1826     if( !psz_filter || i_module <= 0 )
1827         return NULL;
1828
1829     for( ;; )
1830     {
1831         char *psz_find = strstr( psz_filter, psz_module );
1832         if( !psz_find )
1833             return NULL;
1834         if( psz_find[i_module] == '\0' || psz_find[i_module] == ':' )
1835             return psz_find;
1836         psz_filter = &psz_find[i_module];
1837     }
1838 }
1839
1840 static bool DeinterlaceIsPresent( vout_thread_t *p_vout, bool b_vout_filter )
1841 {
1842     char *psz_filter = var_GetNonEmptyString( p_vout, b_vout_filter ? "vout-filter" : "video-filter" );
1843
1844     bool b_found = FilterFind( psz_filter, "deinterlace" ) != NULL;
1845
1846     free( psz_filter );
1847
1848     return b_found;
1849 }
1850
1851 static void DeinterlaceRemove( vout_thread_t *p_vout, bool b_vout_filter )
1852 {
1853     const char *psz_variable = b_vout_filter ? "vout-filter" : "video-filter";
1854     char *psz_filter = var_GetNonEmptyString( p_vout, psz_variable );
1855
1856     char *psz = FilterFind( psz_filter, "deinterlace" );
1857     if( !psz )
1858     {
1859         free( psz_filter );
1860         return;
1861     }
1862
1863     /* */
1864     strcpy( &psz[0], &psz[strlen("deinterlace")] );
1865     if( *psz == ':' )
1866         strcpy( &psz[0], &psz[1] );
1867
1868     var_SetString( p_vout, psz_variable, psz_filter );
1869     free( psz_filter );
1870 }
1871 static void DeinterlaceAdd( vout_thread_t *p_vout, bool b_vout_filter )
1872 {
1873     const char *psz_variable = b_vout_filter ? "vout-filter" : "video-filter";
1874
1875     char *psz_filter = var_GetNonEmptyString( p_vout, psz_variable );
1876
1877     if( FilterFind( psz_filter, "deinterlace" ) )
1878     {
1879         free( psz_filter );
1880         return;
1881     }
1882
1883     /* */
1884     if( psz_filter )
1885     {
1886         char *psz_tmp = psz_filter;
1887         if( asprintf( &psz_filter, "%s:%s", psz_tmp, "deinterlace" ) < 0 )
1888             psz_filter = psz_tmp;
1889         else
1890             free( psz_tmp );
1891     }
1892     else
1893     {
1894         psz_filter = strdup( "deinterlace" );
1895     }
1896
1897     if( psz_filter )
1898     {
1899         var_SetString( p_vout, psz_variable, psz_filter );
1900         free( psz_filter );
1901     }
1902 }
1903
1904 static void DeinterlaceSave( vout_thread_t *p_vout, int i_deinterlace, const char *psz_mode, bool is_needed )
1905 {
1906     /* We have to set input variable to ensure restart support
1907      * XXX it is only needed because of vout-filter but must be done
1908      * for non video filter anyway */
1909     vlc_object_t *p_input = vlc_object_find( p_vout, VLC_OBJECT_INPUT, FIND_PARENT );
1910     if( !p_input )
1911         return;
1912
1913     /* Another hack for "vout filter" mode */
1914     if( i_deinterlace < 0 )
1915         i_deinterlace = is_needed ? -2 : -3;
1916
1917     var_Create( p_input, "deinterlace", VLC_VAR_INTEGER );
1918     var_SetInteger( p_input, "deinterlace", i_deinterlace );
1919
1920     static const char * const ppsz_variable[] = {
1921         "deinterlace-mode",
1922         "filter-deinterlace-mode",
1923         "sout-deinterlace-mode",
1924         NULL
1925     };
1926     for( int i = 0; ppsz_variable[i]; i++ )
1927     {
1928         var_Create( p_input, ppsz_variable[i], VLC_VAR_STRING );
1929         var_SetString( p_input, ppsz_variable[i], psz_mode );
1930     }
1931
1932     vlc_object_release( p_input );
1933 }
1934 static int DeinterlaceCallback( vlc_object_t *p_this, char const *psz_cmd,
1935                                 vlc_value_t oldval, vlc_value_t newval, void *p_data )
1936 {
1937     VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval); VLC_UNUSED(newval); VLC_UNUSED(p_data);
1938     vout_thread_t *p_vout = (vout_thread_t *)p_this;
1939
1940     /* */
1941     const int  i_deinterlace = var_GetInteger( p_this, "deinterlace" );
1942     char       *psz_mode     = var_GetString( p_this, "deinterlace-mode" );
1943     const bool is_needed     = var_GetBool( p_this, "deinterlace-needed" );
1944     if( !psz_mode )
1945         return VLC_EGENERIC;
1946
1947     DeinterlaceSave( p_vout, i_deinterlace, psz_mode, is_needed );
1948
1949     /* */
1950     bool b_vout_filter = true;
1951     for( const deinterlace_mode_t *p_mode = &p_deinterlace_mode[0]; p_mode->psz_mode; p_mode++ )
1952     {
1953         if( !strcmp( p_mode->psz_mode, psz_mode ) )
1954         {
1955             b_vout_filter = p_mode->b_vout_filter;
1956             break;
1957         }
1958     }
1959
1960     /* */
1961     char *psz_old;
1962     if( b_vout_filter )
1963     {
1964         psz_old = var_CreateGetString( p_vout, "filter-deinterlace-mode" );
1965     }
1966     else
1967     {
1968         psz_old = var_CreateGetString( p_vout, "sout-deinterlace-mode" );
1969         var_SetString( p_vout, "sout-deinterlace-mode", psz_mode );
1970     }
1971
1972     msg_Dbg( p_vout, "deinterlace %d, mode %s, is_needed %d", i_deinterlace, psz_mode, is_needed );
1973     if( i_deinterlace == 0 || ( i_deinterlace == -1 && !is_needed ) )
1974     {
1975         DeinterlaceRemove( p_vout, false );
1976         DeinterlaceRemove( p_vout, true );
1977     }
1978     else
1979     {
1980         if( !DeinterlaceIsPresent( p_vout, b_vout_filter ) )
1981         {
1982             DeinterlaceRemove( p_vout, !b_vout_filter );
1983             DeinterlaceAdd( p_vout, b_vout_filter );
1984         }
1985         else
1986         {
1987             /* The deinterlace filter was already inserted but we have changed the mode */
1988             DeinterlaceRemove( p_vout, !b_vout_filter );
1989             if( psz_old && strcmp( psz_old, psz_mode ) )
1990                 var_TriggerCallback( p_vout, b_vout_filter ? "vout-filter" : "video-filter" );
1991         }
1992     }
1993
1994     /* */
1995     free( psz_old );
1996     free( psz_mode );
1997     return VLC_SUCCESS;
1998 }
1999
2000 static void DeinterlaceEnable( vout_thread_t *p_vout )
2001 {
2002     vlc_value_t val, text;
2003
2004     if( !p_vout->p->b_first_vout )
2005         return;
2006
2007     msg_Dbg( p_vout, "Deinterlacing available" );
2008
2009     /* Create the configuration variables */
2010     /* */
2011     var_Create( p_vout, "deinterlace", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT | VLC_VAR_HASCHOICE );
2012     int i_deinterlace = var_GetInteger( p_vout, "deinterlace" );
2013
2014     text.psz_string = _("Deinterlace");
2015     var_Change( p_vout, "deinterlace", VLC_VAR_SETTEXT, &text, NULL );
2016
2017     const module_config_t *p_optd = config_FindConfig( VLC_OBJECT(p_vout), "deinterlace" );
2018     var_Change( p_vout, "deinterlace", VLC_VAR_CLEARCHOICES, NULL, NULL );
2019     for( int i = 0; p_optd && i < p_optd->i_list; i++ )
2020     {
2021         val.i_int  = p_optd->pi_list[i];
2022         text.psz_string = (char*)vlc_gettext(p_optd->ppsz_list_text[i]);
2023         var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
2024     }
2025     var_AddCallback( p_vout, "deinterlace", DeinterlaceCallback, NULL );
2026     /* */
2027     var_Create( p_vout, "deinterlace-mode", VLC_VAR_STRING | VLC_VAR_DOINHERIT | VLC_VAR_HASCHOICE );
2028     char *psz_deinterlace = var_GetNonEmptyString( p_vout, "deinterlace-mode" );
2029
2030     text.psz_string = _("Deinterlace mode");
2031     var_Change( p_vout, "deinterlace-mode", VLC_VAR_SETTEXT, &text, NULL );
2032
2033     const module_config_t *p_optm = config_FindConfig( VLC_OBJECT(p_vout), "deinterlace-mode" );
2034     var_Change( p_vout, "deinterlace-mode", VLC_VAR_CLEARCHOICES, NULL, NULL );
2035     for( int i = 0; p_optm && i < p_optm->i_list; i++ )
2036     {
2037         val.psz_string  = p_optm->ppsz_list[i];
2038         text.psz_string = (char*)vlc_gettext(p_optm->ppsz_list_text[i]);
2039         var_Change( p_vout, "deinterlace-mode", VLC_VAR_ADDCHOICE, &val, &text );
2040     }
2041     var_AddCallback( p_vout, "deinterlace-mode", DeinterlaceCallback, NULL );
2042     /* */
2043     var_Create( p_vout, "deinterlace-needed", VLC_VAR_BOOL );
2044     var_AddCallback( p_vout, "deinterlace-needed", DeinterlaceCallback, NULL );
2045
2046     /* Override the initial value from filters if present */
2047     char *psz_filter_mode = NULL;
2048     if( DeinterlaceIsPresent( p_vout, true ) )
2049         psz_filter_mode = var_CreateGetNonEmptyString( p_vout, "filter-deinterlace-mode" );
2050     else if( DeinterlaceIsPresent( p_vout, false ) )
2051         psz_filter_mode = var_CreateGetNonEmptyString( p_vout, "sout-deinterlace-mode" );
2052     if( psz_filter_mode )
2053     {
2054         free( psz_deinterlace );
2055         if( i_deinterlace >= -1 )
2056             i_deinterlace = 1;
2057         psz_deinterlace = psz_filter_mode;
2058     }
2059
2060     /* */
2061     bool is_needed;
2062     if( i_deinterlace == -2 )
2063         is_needed = true;
2064     else if( i_deinterlace == -3 )
2065         is_needed = false;
2066     if( i_deinterlace < 0 )
2067         i_deinterlace = -1;
2068
2069     p_vout->p->b_picture_interlaced = is_needed;
2070
2071     /* */
2072     val.psz_string = psz_deinterlace ? psz_deinterlace : p_optm->orig.psz;
2073     var_Change( p_vout, "deinterlace-mode", VLC_VAR_SETVALUE, &val, NULL );
2074     val.b_bool = is_needed;
2075     var_Change( p_vout, "deinterlace-needed", VLC_VAR_SETVALUE, &val, NULL );
2076
2077     var_SetInteger( p_vout, "deinterlace", i_deinterlace );
2078     free( psz_deinterlace );
2079 }
2080
2081 static void DeinterlaceNeeded( vout_thread_t *p_vout, bool is_interlaced )
2082 {
2083     msg_Dbg( p_vout, "Detected %s video",
2084              is_interlaced ? "interlaced" : "progressive" );
2085     var_SetBool( p_vout, "deinterlace-needed", is_interlaced );
2086 }
2087