Fix potential NULL dereference (CID 27).
[vlc.git] / 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         ( vlc_object_t *  );
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 DeinterlaceCallback( vlc_object_t *, char const *,
83                                 vlc_value_t, vlc_value_t, void * );
84 static int FilterCallback( vlc_object_t *, char const *,
85                            vlc_value_t, vlc_value_t, void * );
86 static int VideoFilter2Callback( vlc_object_t *, char const *,
87                                  vlc_value_t, vlc_value_t, void * );
88
89 /* From vout_intf.c */
90 int vout_Snapshot( vout_thread_t *, picture_t * );
91
92 /* Display media title in OSD */
93 static void DisplayTitleOnOSD( vout_thread_t *p_vout );
94
95 /* */
96 static void DropPicture( vout_thread_t *p_vout, picture_t *p_picture );
97
98 /*****************************************************************************
99  * Video Filter2 functions
100  *****************************************************************************/
101 static picture_t *video_new_buffer_filter( filter_t *p_filter )
102 {
103     vout_thread_t *p_vout = (vout_thread_t*)p_filter->p_owner;
104     picture_t *p_picture = vout_CreatePicture( p_vout, 0, 0, 0 );
105
106     p_picture->i_status = READY_PICTURE;
107
108     return p_picture;
109 }
110
111 static void video_del_buffer_filter( filter_t *p_filter, picture_t *p_pic )
112 {
113     vout_thread_t *p_vout = (vout_thread_t*)p_filter->p_owner;
114
115     DropPicture( p_vout, p_pic );
116 }
117
118 static int video_filter_buffer_allocation_init( filter_t *p_filter, void *p_data )
119 {
120     p_filter->pf_vout_buffer_new = video_new_buffer_filter;
121     p_filter->pf_vout_buffer_del = video_del_buffer_filter;
122     p_filter->p_owner = p_data; /* p_vout */
123     return VLC_SUCCESS;
124 }
125
126 /*****************************************************************************
127  * vout_Request: find a video output thread, create one, or destroy one.
128  *****************************************************************************
129  * This function looks for a video output thread matching the current
130  * properties. If not found, it spawns a new one.
131  *****************************************************************************/
132 vout_thread_t *__vout_Request( vlc_object_t *p_this, vout_thread_t *p_vout,
133                                video_format_t *p_fmt )
134 {
135     const bool b_vout_provided = p_vout != NULL;
136     if( !p_fmt )
137     {
138         /* Video output is no longer used.
139          * TODO: support for reusing video outputs with proper _thread-safe_
140          * reference handling. */
141         if( p_vout )
142             vout_CloseAndRelease( p_vout );
143         return NULL;
144     }
145
146     /* If a video output was provided, lock it, otherwise look for one. */
147     if( p_vout )
148     {
149         vlc_object_hold( p_vout );
150     }
151
152     /* TODO: find a suitable unused video output */
153
154     /* If we now have a video output, check it has the right properties */
155     if( p_vout )
156     {
157         char *psz_filter_chain;
158         vlc_value_t val;
159
160         vlc_mutex_lock( &p_vout->change_lock );
161
162         /* We don't directly check for the "vout-filter" variable for obvious
163          * performance reasons. */
164         if( p_vout->p->b_filter_change )
165         {
166             var_Get( p_vout, "vout-filter", &val );
167             psz_filter_chain = val.psz_string;
168
169             if( psz_filter_chain && !*psz_filter_chain )
170             {
171                 free( psz_filter_chain );
172                 psz_filter_chain = NULL;
173             }
174             if( p_vout->p->psz_filter_chain && !*p_vout->p->psz_filter_chain )
175             {
176                 free( p_vout->p->psz_filter_chain );
177                 p_vout->p->psz_filter_chain = NULL;
178             }
179
180             if( !psz_filter_chain && !p_vout->p->psz_filter_chain )
181             {
182                 p_vout->p->b_filter_change = false;
183             }
184
185             free( psz_filter_chain );
186         }
187
188         if( p_vout->fmt_render.i_chroma != p_fmt->i_chroma ||
189             p_vout->fmt_render.i_width != p_fmt->i_width ||
190             p_vout->fmt_render.i_height != p_fmt->i_height ||
191             p_vout->p->b_filter_change )
192         {
193             vlc_mutex_unlock( &p_vout->change_lock );
194
195             /* We are not interested in this format, close this vout */
196             vout_CloseAndRelease( p_vout );
197             vlc_object_release( p_vout );
198             p_vout = NULL;
199         }
200         else
201         {
202             /* This video output is cool! Hijack it. */
203             if( p_vout->fmt_render.i_aspect != p_fmt->i_aspect )
204             {
205                 /* Correct aspect ratio on change
206                  * FIXME factorize this code with other aspect ration related code */
207                 unsigned int i_sar_num;
208                 unsigned int i_sar_den;
209                 unsigned int i_aspect;
210
211                 i_aspect = p_fmt->i_aspect;
212                 vlc_ureduce( &i_sar_num, &i_sar_den,
213                              p_fmt->i_sar_num, p_fmt->i_sar_den, 50000 );
214 #if 0
215                 /* What's that, it does not seems to be used correcly everywhere
216                  * beside the previous p_vout->fmt_render.i_aspect != p_fmt->i_aspect
217                  * should be fixed to use it too then */
218                 if( p_vout->i_par_num > 0 && p_vout->i_par_den > 0 )
219                 {
220                     i_sar_num *= p_vout->i_par_den;
221                     i_sar_den *= p_vout->i_par_num;
222                     i_aspect = i_aspect * p_vout->i_par_den / p_vout->i_par_num;
223                 }
224 #endif
225
226                 if( i_sar_num > 0 && i_sar_den > 0 && i_aspect > 0 )
227                 {
228                     p_vout->fmt_in.i_sar_num = i_sar_num;
229                     p_vout->fmt_in.i_sar_den = i_sar_den;
230                     p_vout->fmt_in.i_aspect  = i_aspect;
231
232                     p_vout->fmt_render.i_sar_num = i_sar_num;
233                     p_vout->fmt_render.i_sar_den = i_sar_den;
234                     p_vout->fmt_render.i_aspect  = i_aspect;
235
236                     p_vout->render.i_aspect   = i_aspect;
237
238                     p_vout->i_changes |= VOUT_ASPECT_CHANGE;
239
240                 }
241             }
242             vlc_mutex_unlock( &p_vout->change_lock );
243
244             vlc_object_release( p_vout );
245         }
246
247         if( p_vout )
248         {
249             msg_Dbg( p_this, "reusing provided vout" );
250
251             spu_Attach( p_vout->p_spu, p_this, true );
252
253             vlc_object_detach( p_vout );
254             vlc_object_attach( p_vout, p_this );
255
256             /* Display title if we are not using the vout given to vout_Request.
257              * XXX for now b_vout_provided is always true at this stage */
258             if( p_vout->p->b_title_show && !b_vout_provided )
259                 DisplayTitleOnOSD( p_vout );
260         }
261     }
262
263     if( !p_vout )
264     {
265         msg_Dbg( p_this, "no usable vout present, spawning one" );
266
267         p_vout = vout_Create( p_this, p_fmt );
268     }
269
270     return p_vout;
271 }
272
273 /*****************************************************************************
274  * vout_Create: creates a new video output thread
275  *****************************************************************************
276  * This function creates a new video output thread, and returns a pointer
277  * to its description. On error, it returns NULL.
278  *****************************************************************************/
279 vout_thread_t * __vout_Create( vlc_object_t *p_parent, video_format_t *p_fmt )
280 {
281     vout_thread_t  * p_vout;                            /* thread descriptor */
282     int              i_index;                               /* loop variable */
283     vlc_value_t      val, text;
284
285     unsigned int i_width = p_fmt->i_width;
286     unsigned int i_height = p_fmt->i_height;
287     vlc_fourcc_t i_chroma = p_fmt->i_chroma;
288     unsigned int i_aspect = p_fmt->i_aspect;
289
290     config_chain_t *p_cfg;
291     char *psz_parser;
292     char *psz_name;
293
294     if( i_width <= 0 || i_height <= 0 || i_aspect <= 0 )
295         return NULL;
296
297     vlc_ureduce( &p_fmt->i_sar_num, &p_fmt->i_sar_den,
298                  p_fmt->i_sar_num, p_fmt->i_sar_den, 50000 );
299     if( p_fmt->i_sar_num <= 0 || p_fmt->i_sar_den <= 0 )
300         return NULL;
301
302     /* Allocate descriptor */
303     static const char typename[] = "video output";
304     p_vout = vlc_custom_create( p_parent, sizeof( *p_vout ), VLC_OBJECT_VOUT,
305                                 typename );
306     if( p_vout == NULL )
307         return NULL;
308
309     /* */
310     p_vout->p = calloc( 1, sizeof(*p_vout->p) );
311     if( !p_vout->p )
312     {
313         vlc_object_release( p_vout );
314         return NULL;
315     }
316
317     /* Initialize pictures - translation tables and functions
318      * will be initialized later in InitThread */
319     for( i_index = 0; i_index < 2 * VOUT_MAX_PICTURES + 1; i_index++)
320     {
321         p_vout->p_picture[i_index].pf_lock = NULL;
322         p_vout->p_picture[i_index].pf_unlock = NULL;
323         p_vout->p_picture[i_index].i_status = FREE_PICTURE;
324         p_vout->p_picture[i_index].i_type   = EMPTY_PICTURE;
325         p_vout->p_picture[i_index].b_slow   = 0;
326     }
327
328     /* No images in the heap */
329     p_vout->i_heap_size = 0;
330
331     /* Initialize the rendering heap */
332     I_RENDERPICTURES = 0;
333
334     p_vout->fmt_render        = *p_fmt;   /* FIXME palette */
335     p_vout->fmt_in            = *p_fmt;   /* FIXME palette */
336
337     p_vout->render.i_width    = i_width;
338     p_vout->render.i_height   = i_height;
339     p_vout->render.i_chroma   = i_chroma;
340     p_vout->render.i_aspect   = i_aspect;
341
342     p_vout->render.i_rmask    = p_fmt->i_rmask;
343     p_vout->render.i_gmask    = p_fmt->i_gmask;
344     p_vout->render.i_bmask    = p_fmt->i_bmask;
345
346     p_vout->render.i_last_used_pic = -1;
347     p_vout->render.b_allow_modify_pics = 1;
348
349     /* Zero the output heap */
350     I_OUTPUTPICTURES = 0;
351     p_vout->output.i_width    = 0;
352     p_vout->output.i_height   = 0;
353     p_vout->output.i_chroma   = 0;
354     p_vout->output.i_aspect   = 0;
355
356     p_vout->output.i_rmask    = 0;
357     p_vout->output.i_gmask    = 0;
358     p_vout->output.i_bmask    = 0;
359
360     /* Initialize misc stuff */
361     p_vout->i_changes    = 0;
362     p_vout->b_scale      = 1;
363     p_vout->b_fullscreen = 0;
364     p_vout->i_alignment  = 0;
365     p_vout->p->render_time  = 10;
366     p_vout->p->c_fps_samples = 0;
367     p_vout->p->i_picture_lost = 0;
368     p_vout->p->i_picture_displayed = 0;
369     p_vout->p->b_filter_change = 0;
370     p_vout->p->b_paused = false;
371     p_vout->p->i_pause_date = 0;
372     p_vout->pf_control = NULL;
373     p_vout->p_window = NULL;
374     p_vout->p->i_par_num =
375     p_vout->p->i_par_den = 1;
376
377     /* Initialize locks */
378     vlc_mutex_init_recursive( &p_vout->picture_lock );
379     vlc_mutex_init( &p_vout->change_lock );
380     vlc_mutex_init( &p_vout->p->vfilter_lock );
381
382     /* Mouse coordinates */
383     var_Create( p_vout, "mouse-x", VLC_VAR_INTEGER );
384     var_Create( p_vout, "mouse-y", VLC_VAR_INTEGER );
385     var_Create( p_vout, "mouse-button-down", VLC_VAR_INTEGER );
386     var_Create( p_vout, "mouse-moved", VLC_VAR_BOOL );
387     var_Create( p_vout, "mouse-clicked", VLC_VAR_INTEGER );
388
389     /* Initialize subpicture unit */
390     p_vout->p_spu = spu_Create( p_vout );
391     spu_Attach( p_vout->p_spu, p_parent, true );
392
393     /* Attach the new object now so we can use var inheritance below */
394     vlc_object_attach( p_vout, p_parent );
395
396     spu_Init( p_vout->p_spu );
397
398     /* Take care of some "interface/control" related initialisations */
399     vout_IntfInit( p_vout );
400
401     /* If the parent is not a VOUT object, that means we are at the start of
402      * the video output pipe */
403     if( p_parent->i_object_type != VLC_OBJECT_VOUT )
404     {
405         /* Look for the default filter configuration */
406         p_vout->p->psz_filter_chain =
407             var_CreateGetStringCommand( p_vout, "vout-filter" );
408
409         /* Apply video filter2 objects on the first vout */
410         p_vout->p->psz_vf2 =
411             var_CreateGetStringCommand( p_vout, "video-filter" );
412     }
413     else
414     {
415         /* continue the parent's filter chain */
416         char *psz_tmp;
417
418         /* Ugly hack to jump to our configuration chain */
419         p_vout->p->psz_filter_chain
420             = ((vout_thread_t *)p_parent)->p->psz_filter_chain;
421         p_vout->p->psz_filter_chain
422             = config_ChainCreate( &psz_tmp, &p_cfg, p_vout->p->psz_filter_chain );
423         config_ChainDestroy( p_cfg );
424         free( psz_tmp );
425
426         /* Create a video filter2 var ... but don't inherit values */
427         var_Create( p_vout, "video-filter",
428                     VLC_VAR_STRING | VLC_VAR_ISCOMMAND );
429         p_vout->p->psz_vf2 = var_GetString( p_vout, "video-filter" );
430     }
431
432     var_AddCallback( p_vout, "video-filter", VideoFilter2Callback, NULL );
433     p_vout->p->p_vf2_chain = filter_chain_New( p_vout, "video filter2",
434         false, video_filter_buffer_allocation_init, NULL, p_vout );
435
436     /* Choose the video output module */
437     if( !p_vout->p->psz_filter_chain || !*p_vout->p->psz_filter_chain )
438     {
439         var_Create( p_vout, "vout", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
440         var_Get( p_vout, "vout", &val );
441         psz_parser = val.psz_string;
442     }
443     else
444     {
445         psz_parser = strdup( p_vout->p->psz_filter_chain );
446         p_vout->p->b_title_show = false;
447     }
448
449     /* Create the vout thread */
450     char* psz_tmp = config_ChainCreate( &psz_name, &p_cfg, psz_parser );
451     free( psz_parser );
452     free( psz_tmp );
453     p_vout->p_cfg = p_cfg;
454     p_vout->p_module = module_need( p_vout,
455         ( p_vout->p->psz_filter_chain && *p_vout->p->psz_filter_chain ) ?
456         "video filter" : "video output", psz_name, p_vout->p->psz_filter_chain && *p_vout->p->psz_filter_chain );
457     free( psz_name );
458
459     if( p_vout->p_module == NULL )
460     {
461         msg_Err( p_vout, "no suitable vout module" );
462         vlc_object_set_destructor( p_vout, vout_Destructor );
463         vlc_object_release( p_vout );
464         return NULL;
465     }
466
467     /* Create a few object variables for interface interaction */
468     var_Create( p_vout, "deinterlace", VLC_VAR_STRING | VLC_VAR_HASCHOICE );
469     text.psz_string = _("Deinterlace");
470     var_Change( p_vout, "deinterlace", VLC_VAR_SETTEXT, &text, NULL );
471     val.psz_string = (char *)""; text.psz_string = _("Disable");
472     var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
473     val.psz_string = (char *)"discard"; text.psz_string = _("Discard");
474     var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
475     val.psz_string = (char *)"blend"; text.psz_string = _("Blend");
476     var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
477     val.psz_string = (char *)"mean"; text.psz_string = _("Mean");
478     var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
479     val.psz_string = (char *)"bob"; text.psz_string = _("Bob");
480     var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
481     val.psz_string = (char *)"linear"; text.psz_string = _("Linear");
482     var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
483     val.psz_string = (char *)"x"; text.psz_string = (char *)"X";
484     var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
485
486     if( var_Get( p_vout, "deinterlace-mode", &val ) == VLC_SUCCESS )
487     {
488         var_Set( p_vout, "deinterlace", val );
489         free( val.psz_string );
490     }
491     var_AddCallback( p_vout, "deinterlace", DeinterlaceCallback, NULL );
492
493     var_Create( p_vout, "vout-filter", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
494     text.psz_string = _("Filters");
495     var_Change( p_vout, "vout-filter", VLC_VAR_SETTEXT, &text, NULL );
496     var_AddCallback( p_vout, "vout-filter", FilterCallback, NULL );
497
498     if( vlc_thread_create( p_vout, "video output", RunThread,
499                            VLC_THREAD_PRIORITY_OUTPUT, true ) )
500     {
501         module_unneed( p_vout, p_vout->p_module );
502         p_vout->p_module = NULL;
503         vlc_object_set_destructor( p_vout, vout_Destructor );
504         vlc_object_release( p_vout );
505         return NULL;
506     }
507
508     vlc_object_set_destructor( p_vout, vout_Destructor );
509
510     if( p_vout->b_error )
511     {
512         msg_Err( p_vout, "video output creation failed" );
513         vout_CloseAndRelease( p_vout );
514         return NULL;
515     }
516
517     return p_vout;
518 }
519
520 /*****************************************************************************
521  * vout_Close: Close a vout created by vout_Create.
522  *****************************************************************************
523  * You HAVE to call it on vout created by vout_Create before vlc_object_release.
524  * You should NEVER call it on vout not obtained through vout_Create
525  * (like with vout_Request or vlc_object_find.)
526  * You can use vout_CloseAndRelease() as a convenient method.
527  *****************************************************************************/
528 void vout_Close( vout_thread_t *p_vout )
529 {
530     assert( p_vout );
531
532     vlc_object_kill( p_vout );
533     vlc_thread_join( p_vout );
534     module_unneed( p_vout, p_vout->p_module );
535     p_vout->p_module = NULL;
536 }
537
538 /* */
539 static void vout_Destructor( vlc_object_t * p_this )
540 {
541     vout_thread_t *p_vout = (vout_thread_t *)p_this;
542
543     /* Make sure the vout was stopped first */
544     assert( !p_vout->p_module );
545
546     /* */
547     spu_Destroy( p_vout->p_spu );
548
549     /* Destroy the locks */
550     vlc_mutex_destroy( &p_vout->picture_lock );
551     vlc_mutex_destroy( &p_vout->change_lock );
552     vlc_mutex_destroy( &p_vout->p->vfilter_lock );
553
554     free( p_vout->p->psz_filter_chain );
555
556     config_ChainDestroy( p_vout->p_cfg );
557
558     free( p_vout->p );
559
560 #ifndef __APPLE__
561     vout_thread_t *p_another_vout;
562
563     /* This is a dirty hack mostly for Linux, where there is no way to get the
564      * GUI back if you closed it while playing video. This is solved in
565      * Mac OS X, where we have this novelty called menubar, that will always
566      * allow you access to the applications main functionality. They should try
567      * that on linux sometime. */
568     p_another_vout = vlc_object_find( p_this->p_libvlc,
569                                       VLC_OBJECT_VOUT, FIND_ANYWHERE );
570     if( p_another_vout == NULL )
571         var_SetBool( p_this->p_libvlc, "intf-show", true );
572     else
573         vlc_object_release( p_another_vout );
574 #endif
575 }
576
577 /* */
578 void vout_ChangePause( vout_thread_t *p_vout, bool b_paused, mtime_t i_date )
579 {
580     vlc_object_lock( p_vout );
581
582     assert( !p_vout->p->b_paused || !b_paused );
583     if( p_vout->p->b_paused )
584     {
585         const mtime_t i_duration = i_date - p_vout->p->i_pause_date;
586
587         for( int i_index = 0; i_index < I_RENDERPICTURES; i_index++ )
588         {
589             picture_t *p_pic = PP_RENDERPICTURE[i_index];
590
591             if( p_pic->i_status == READY_PICTURE )
592                 p_pic->date += i_duration;
593         }
594         spu_OffsetSubtitleDate( p_vout->p_spu, i_duration );
595     }
596     p_vout->p->b_paused = b_paused;
597     p_vout->p->i_pause_date = i_date;
598
599     vlc_object_unlock( p_vout );
600 }
601 void vout_GetResetStatistic( vout_thread_t *p_vout, int *pi_displayed, int *pi_lost )
602 {
603     vlc_object_lock( p_vout );
604
605     *pi_displayed = p_vout->p->i_picture_displayed;
606     *pi_lost = p_vout->p->i_picture_lost;
607
608     p_vout->p->i_picture_displayed = 0;
609     p_vout->p->i_picture_lost = 0;
610
611     vlc_object_unlock( p_vout );
612 }
613 void vout_Flush( vout_thread_t *p_vout, mtime_t i_date )
614 {
615     vlc_mutex_lock( &p_vout->picture_lock );
616     for( int i = 0; i < p_vout->render.i_pictures; i++ )
617     {
618         picture_t *p_pic = p_vout->render.pp_picture[i];
619
620         if( p_pic->i_status == READY_PICTURE ||
621             p_pic->i_status == DISPLAYED_PICTURE )
622         {
623             /* We cannot change picture status if it is in READY_PICTURE state,
624              * Just make sure they won't be displayed */
625             if( p_pic->date > i_date )
626                 p_pic->date = i_date;
627         }
628     }
629     vlc_mutex_unlock( &p_vout->picture_lock );
630 }
631 void vout_FixLeaks( vout_thread_t *p_vout, bool b_forced )
632 {
633     int i_pic, i_ready_pic;
634
635     vlc_mutex_lock( &p_vout->picture_lock );
636
637     for( i_pic = 0, i_ready_pic = 0; i_pic < p_vout->render.i_pictures && !b_forced; i_pic++ )
638     {
639         const picture_t *p_pic = p_vout->render.pp_picture[i_pic];
640
641         if( p_pic->i_status == READY_PICTURE )
642         {
643             i_ready_pic++;
644             /* If we have at least 2 ready pictures, wait for the vout thread to
645              * process one */
646             if( i_ready_pic >= 2 )
647                 break;
648
649             continue;
650         }
651
652         if( p_pic->i_status == DISPLAYED_PICTURE )
653         {
654             /* If at least one displayed picture is not referenced
655              * let vout free it */
656             if( p_pic->i_refcount == 0 )
657                 break;
658         }
659     }
660     if( i_pic < p_vout->render.i_pictures && !b_forced )
661     {
662         vlc_mutex_unlock( &p_vout->picture_lock );
663         return;
664     }
665
666     /* Too many pictures are still referenced, there is probably a bug
667      * with the decoder */
668     if( !b_forced )
669         msg_Err( p_vout, "pictures leaked, resetting the heap" );
670
671     /* Just free all the pictures */
672     for( i_pic = 0; i_pic < p_vout->render.i_pictures; i_pic++ )
673     {
674         picture_t *p_pic = p_vout->render.pp_picture[i_pic];
675
676         if( p_pic->i_status == RESERVED_PICTURE )
677             vout_DestroyPicture( p_vout, p_pic );
678         if( p_pic->i_refcount > 0 )
679             vout_UnlinkPicture( p_vout, p_pic );
680     }
681     vlc_mutex_unlock( &p_vout->picture_lock );
682 }
683
684 /*****************************************************************************
685  * InitThread: initialize video output thread
686  *****************************************************************************
687  * This function is called from RunThread 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 ChromaCreate( vout_thread_t *p_vout );
693 static void ChromaDestroy( vout_thread_t *p_vout );
694
695 static bool ChromaIsEqual( const picture_heap_t *p_output, const picture_heap_t *p_render )
696 {
697      if( !vout_ChromaCmp( p_output->i_chroma, p_render->i_chroma ) )
698          return false;
699
700      if( p_output->i_chroma != FOURCC_RV15 &&
701          p_output->i_chroma != FOURCC_RV16 &&
702          p_output->i_chroma != FOURCC_RV24 &&
703          p_output->i_chroma != FOURCC_RV32 )
704          return true;
705
706      return p_output->i_rmask == p_render->i_rmask &&
707             p_output->i_gmask == p_render->i_gmask &&
708             p_output->i_bmask == p_render->i_bmask;
709 }
710
711 static int InitThread( vout_thread_t *p_vout )
712 {
713     int i, i_aspect_x, i_aspect_y;
714
715     /* Initialize output method, it allocates direct buffers for us */
716     if( p_vout->pf_init( p_vout ) )
717         return VLC_EGENERIC;
718
719     if( !I_OUTPUTPICTURES )
720     {
721         msg_Err( p_vout, "plugin was unable to allocate at least "
722                          "one direct buffer" );
723         p_vout->pf_end( p_vout );
724         return VLC_EGENERIC;
725     }
726
727     if( I_OUTPUTPICTURES > VOUT_MAX_PICTURES )
728     {
729         msg_Err( p_vout, "plugin allocated too many direct buffers, "
730                          "our internal buffers must have overflown." );
731         p_vout->pf_end( p_vout );
732         return VLC_EGENERIC;
733     }
734
735     msg_Dbg( p_vout, "got %i direct buffer(s)", I_OUTPUTPICTURES );
736
737     AspectRatio( p_vout->fmt_render.i_aspect, &i_aspect_x, &i_aspect_y );
738
739     msg_Dbg( p_vout, "picture in %ix%i (%i,%i,%ix%i), "
740              "chroma %4.4s, ar %i:%i, sar %i:%i",
741              p_vout->fmt_render.i_width, p_vout->fmt_render.i_height,
742              p_vout->fmt_render.i_x_offset, p_vout->fmt_render.i_y_offset,
743              p_vout->fmt_render.i_visible_width,
744              p_vout->fmt_render.i_visible_height,
745              (char*)&p_vout->fmt_render.i_chroma,
746              i_aspect_x, i_aspect_y,
747              p_vout->fmt_render.i_sar_num, p_vout->fmt_render.i_sar_den );
748
749     AspectRatio( p_vout->fmt_in.i_aspect, &i_aspect_x, &i_aspect_y );
750
751     msg_Dbg( p_vout, "picture user %ix%i (%i,%i,%ix%i), "
752              "chroma %4.4s, ar %i:%i, sar %i:%i",
753              p_vout->fmt_in.i_width, p_vout->fmt_in.i_height,
754              p_vout->fmt_in.i_x_offset, p_vout->fmt_in.i_y_offset,
755              p_vout->fmt_in.i_visible_width,
756              p_vout->fmt_in.i_visible_height,
757              (char*)&p_vout->fmt_in.i_chroma,
758              i_aspect_x, i_aspect_y,
759              p_vout->fmt_in.i_sar_num, p_vout->fmt_in.i_sar_den );
760
761     if( !p_vout->fmt_out.i_width || !p_vout->fmt_out.i_height )
762     {
763         p_vout->fmt_out.i_width = p_vout->fmt_out.i_visible_width =
764             p_vout->output.i_width;
765         p_vout->fmt_out.i_height = p_vout->fmt_out.i_visible_height =
766             p_vout->output.i_height;
767         p_vout->fmt_out.i_x_offset =  p_vout->fmt_out.i_y_offset = 0;
768
769         p_vout->fmt_out.i_aspect = p_vout->output.i_aspect;
770         p_vout->fmt_out.i_chroma = p_vout->output.i_chroma;
771     }
772     if( !p_vout->fmt_out.i_sar_num || !p_vout->fmt_out.i_sar_num )
773     {
774         p_vout->fmt_out.i_sar_num = p_vout->fmt_out.i_aspect *
775             p_vout->fmt_out.i_height;
776         p_vout->fmt_out.i_sar_den = VOUT_ASPECT_FACTOR *
777             p_vout->fmt_out.i_width;
778     }
779
780     vlc_ureduce( &p_vout->fmt_out.i_sar_num, &p_vout->fmt_out.i_sar_den,
781                  p_vout->fmt_out.i_sar_num, p_vout->fmt_out.i_sar_den, 0 );
782
783     AspectRatio( p_vout->fmt_out.i_aspect, &i_aspect_x, &i_aspect_y );
784
785     msg_Dbg( p_vout, "picture out %ix%i (%i,%i,%ix%i), "
786              "chroma %4.4s, ar %i:%i, sar %i:%i",
787              p_vout->fmt_out.i_width, p_vout->fmt_out.i_height,
788              p_vout->fmt_out.i_x_offset, p_vout->fmt_out.i_y_offset,
789              p_vout->fmt_out.i_visible_width,
790              p_vout->fmt_out.i_visible_height,
791              (char*)&p_vout->fmt_out.i_chroma,
792              i_aspect_x, i_aspect_y,
793              p_vout->fmt_out.i_sar_num, p_vout->fmt_out.i_sar_den );
794
795     /* FIXME removed the need of both fmt_* and heap infos */
796     /* Calculate shifts from system-updated masks */
797     PictureHeapFixRgb( &p_vout->render );
798     VideoFormatImportRgb( &p_vout->fmt_render, &p_vout->render );
799
800     PictureHeapFixRgb( &p_vout->output );
801     VideoFormatImportRgb( &p_vout->fmt_out, &p_vout->output );
802
803     /* Check whether we managed to create direct buffers similar to
804      * the render buffers, ie same size and chroma */
805     if( ( p_vout->output.i_width == p_vout->render.i_width )
806      && ( p_vout->output.i_height == p_vout->render.i_height )
807      && ( ChromaIsEqual( &p_vout->output, &p_vout->render ) ) )
808     {
809         /* Cool ! We have direct buffers, we can ask the decoder to
810          * directly decode into them ! Map the first render buffers to
811          * the first direct buffers, but keep the first direct buffer
812          * for memcpy operations */
813         p_vout->p->b_direct = true;
814
815         for( i = 1; i < VOUT_MAX_PICTURES; i++ )
816         {
817             if( p_vout->p_picture[ i ].i_type != DIRECT_PICTURE &&
818                 I_RENDERPICTURES >= VOUT_MIN_DIRECT_PICTURES - 1 &&
819                 p_vout->p_picture[ i - 1 ].i_type == DIRECT_PICTURE )
820             {
821                 /* We have enough direct buffers so there's no need to
822                  * try to use system memory buffers. */
823                 break;
824             }
825             PP_RENDERPICTURE[ I_RENDERPICTURES ] = &p_vout->p_picture[ i ];
826             I_RENDERPICTURES++;
827         }
828
829         msg_Dbg( p_vout, "direct render, mapping "
830                  "render pictures 0-%i to system pictures 1-%i",
831                  VOUT_MAX_PICTURES - 2, VOUT_MAX_PICTURES - 1 );
832     }
833     else
834     {
835         /* Rats... Something is wrong here, we could not find an output
836          * plugin able to directly render what we decode. See if we can
837          * find a chroma plugin to do the conversion */
838         p_vout->p->b_direct = false;
839
840         if( ChromaCreate( p_vout ) )
841         {
842             p_vout->pf_end( p_vout );
843             return VLC_EGENERIC;
844         }
845
846         msg_Dbg( p_vout, "indirect render, mapping "
847                  "render pictures 0-%i to system pictures %i-%i",
848                  VOUT_MAX_PICTURES - 1, I_OUTPUTPICTURES,
849                  I_OUTPUTPICTURES + VOUT_MAX_PICTURES - 1 );
850
851         /* Append render buffers after the direct buffers */
852         for( i = I_OUTPUTPICTURES; i < 2 * VOUT_MAX_PICTURES; i++ )
853         {
854             PP_RENDERPICTURE[ I_RENDERPICTURES ] = &p_vout->p_picture[ i ];
855             I_RENDERPICTURES++;
856
857             /* Check if we have enough render pictures */
858             if( I_RENDERPICTURES == VOUT_MAX_PICTURES )
859                 break;
860         }
861     }
862
863     /* Link pictures back to their heap */
864     for( i = 0 ; i < I_RENDERPICTURES ; i++ )
865     {
866         PP_RENDERPICTURE[ i ]->p_heap = &p_vout->render;
867     }
868
869     for( i = 0 ; i < I_OUTPUTPICTURES ; i++ )
870     {
871         PP_OUTPUTPICTURE[ i ]->p_heap = &p_vout->output;
872     }
873
874     return VLC_SUCCESS;
875 }
876
877 /*****************************************************************************
878  * RunThread: video output thread
879  *****************************************************************************
880  * Video output thread. This function does only returns when the thread is
881  * terminated. It handles the pictures arriving in the video heap and the
882  * display device events.
883  *****************************************************************************/
884 static void* RunThread( vlc_object_t *p_this )
885 {
886     vout_thread_t *p_vout = (vout_thread_t *)p_this;
887     int             i_idle_loops = 0;  /* loops without displaying a picture */
888
889     picture_t *     p_last_picture = NULL;                   /* last picture */
890
891     subpicture_t *  p_subpic = NULL;                   /* subpicture pointer */
892
893     bool            b_drop_late;
894
895     int canc = vlc_savecancel();
896
897     /*
898      * Initialize thread
899      */
900     vlc_mutex_lock( &p_vout->change_lock );
901     p_vout->b_error = InitThread( p_vout );
902
903     b_drop_late = var_CreateGetBool( p_vout, "drop-late-frames" );
904
905     /* signal the creation of the vout */
906     vlc_thread_ready( p_vout );
907
908     if( p_vout->b_error )
909     {
910         EndThread( p_vout );
911         vlc_mutex_unlock( &p_vout->change_lock );
912         vlc_restorecancel( canc );
913         return NULL;
914     }
915
916     vlc_object_lock( p_vout );
917
918     if( p_vout->p->b_title_show )
919         DisplayTitleOnOSD( p_vout );
920
921     /*
922      * Main loop - it is not executed if an error occurred during
923      * initialization
924      */
925     while( vlc_object_alive( p_vout ) && !p_vout->b_error )
926     {
927         /* Initialize loop variables */
928         const mtime_t current_date = mdate();
929         picture_t *p_picture = NULL;
930         picture_t *p_filtered_picture;
931         mtime_t display_date = 0;
932         picture_t *p_directbuffer;
933         int i_index;
934
935         /* Find the picture to display (the one with the earliest date). */
936         vlc_mutex_lock( &p_vout->picture_lock );
937
938         for( i_index = 0; i_index < I_RENDERPICTURES; i_index++ )
939         {
940             picture_t *p_pic = PP_RENDERPICTURE[i_index];
941
942             if( p_pic->i_status == READY_PICTURE &&
943                 ( p_picture == NULL || p_pic->date < display_date ) )
944             {
945                 p_picture = p_pic;
946                 display_date = p_picture->date;
947             }
948         }
949         if( p_vout->p->b_paused && p_last_picture != NULL )
950         {
951             p_picture = NULL;
952             if( p_last_picture->date == 1 )
953             {
954                 for( i_index = 0; i_index < I_RENDERPICTURES; i_index++ )
955                 {
956                     picture_t *p_pic = PP_RENDERPICTURE[i_index];
957
958                     if( p_pic->i_status != READY_PICTURE )
959                         continue;
960                     if( p_pic->date <= p_last_picture->date && p_pic != p_last_picture )
961                     {
962                         DropPicture( p_vout, p_pic );
963                     }
964                     else if( p_pic->date > p_last_picture->date && ( p_picture == NULL || p_pic->date < display_date ) )
965                     {
966                         p_picture = p_pic;
967                         display_date = p_picture->date;
968                     }
969                 }
970             }
971             if( !p_picture )
972                 p_picture = p_last_picture;
973         }
974
975         if( p_picture )
976         {
977             /* If we met the last picture, parse again to see whether there is
978              * a more appropriate one. */
979             if( p_picture == p_last_picture && !p_vout->p->b_paused )
980             {
981                 for( i_index = 0; i_index < I_RENDERPICTURES; i_index++ )
982                 {
983                     picture_t *p_pic = PP_RENDERPICTURE[i_index];
984
985                     if( p_pic->i_status == READY_PICTURE &&
986                         p_pic != p_last_picture &&
987                         ( p_picture == p_last_picture || p_pic->date < display_date ) )
988                     {
989                         p_picture = p_pic;
990                         display_date = p_picture->date;
991                     }
992                 }
993             }
994
995             /* If we found better than the last picture, destroy it */
996             if( p_last_picture && p_picture != p_last_picture )
997             {
998                 DropPicture( p_vout, p_last_picture );
999                 p_last_picture = NULL;
1000             }
1001
1002             /* Compute FPS rate */
1003             p_vout->p->p_fps_sample[ p_vout->p->c_fps_samples++ % VOUT_FPS_SAMPLES ]
1004                 = display_date;
1005
1006             if( !p_picture->b_force &&
1007                 p_picture != p_last_picture &&
1008                 display_date < current_date + p_vout->p->render_time &&
1009                 b_drop_late )
1010             {
1011                 /* Picture is late: it will be destroyed and the thread
1012                  * will directly choose the next picture */
1013                 DropPicture( p_vout, p_picture );
1014                 p_vout->p->i_picture_lost++;
1015                 msg_Warn( p_vout, "late picture skipped (%"PRId64")",
1016                                   current_date - display_date );
1017                 vlc_mutex_unlock( &p_vout->picture_lock );
1018                 continue;
1019             }
1020
1021             if( display_date > current_date + VOUT_DISPLAY_DELAY )
1022             {
1023                 /* A picture is ready to be rendered, but its rendering date
1024                  * is far from the current one so the thread will perform an
1025                  * empty loop as if no picture were found. The picture state
1026                  * is unchanged */
1027                 p_picture    = NULL;
1028                 display_date = 0;
1029             }
1030             else if( p_picture == p_last_picture )
1031             {
1032                 /* We are asked to repeat the previous picture, but we first
1033                  * wait for a couple of idle loops */
1034                 if( i_idle_loops < 4 )
1035                 {
1036                     p_picture    = NULL;
1037                     display_date = 0;
1038                 }
1039                 else
1040                 {
1041                     /* We set the display date to something high, otherwise
1042                      * we'll have lots of problems with late pictures */
1043                     display_date = current_date + p_vout->p->render_time;
1044                 }
1045             }
1046         }
1047         vlc_mutex_unlock( &p_vout->picture_lock );
1048
1049         if( p_picture == NULL )
1050             i_idle_loops++;
1051
1052         p_filtered_picture = NULL;
1053         if( p_picture )
1054             p_filtered_picture = filter_chain_VideoFilter( p_vout->p->p_vf2_chain,
1055                                                            p_picture );
1056
1057         /* FIXME it is a bit ugly that b_snapshot is not locked but I do not
1058          * know which lock to use (here and in the snapshot callback) */
1059         const bool b_snapshot = p_vout->p->b_snapshot;
1060         if( b_snapshot )
1061             p_vout->p->b_snapshot = false;
1062
1063         /*
1064          * Check for subpictures to display
1065          */
1066         if( display_date > 0 )
1067             p_subpic = spu_SortSubpictures( p_vout->p_spu, display_date,
1068                                             p_vout->p->b_paused, b_snapshot );
1069
1070         /*
1071          * Perform rendering
1072          */
1073         p_vout->p->i_picture_displayed++;
1074         p_directbuffer = vout_RenderPicture( p_vout, p_filtered_picture,
1075                                              p_subpic, p_vout->p->b_paused );
1076
1077         /*
1078          * Take a snapshot if requested
1079          */
1080         if( p_directbuffer && b_snapshot )
1081             vout_Snapshot( p_vout, p_directbuffer );
1082
1083         /*
1084          * Call the plugin-specific rendering method if there is one
1085          */
1086         if( p_filtered_picture != NULL && p_directbuffer != NULL && p_vout->pf_render )
1087         {
1088             /* Render the direct buffer returned by vout_RenderPicture */
1089             p_vout->pf_render( p_vout, p_directbuffer );
1090         }
1091
1092         /*
1093          * Sleep, wake up
1094          */
1095         if( display_date != 0 && p_directbuffer != NULL )
1096         {
1097             mtime_t current_render_time = mdate() - current_date;
1098             /* if render time is very large we don't include it in the mean */
1099             if( current_render_time < p_vout->p->render_time +
1100                 VOUT_DISPLAY_DELAY )
1101             {
1102                 /* Store render time using a sliding mean weighting to
1103                  * current value in a 3 to 1 ratio*/
1104                 p_vout->p->render_time *= 3;
1105                 p_vout->p->render_time += current_render_time;
1106                 p_vout->p->render_time >>= 2;
1107             }
1108         }
1109
1110         /* Give back change lock */
1111         vlc_mutex_unlock( &p_vout->change_lock );
1112
1113         vlc_object_unlock( p_vout );
1114
1115         /* Sleep a while or until a given date */
1116         if( display_date != 0 )
1117         {
1118             /* If there are filters in the chain, better give them the picture
1119              * in advance */
1120             if( !p_vout->p->psz_filter_chain || !*p_vout->p->psz_filter_chain )
1121             {
1122                 mwait( display_date - VOUT_MWAIT_TOLERANCE );
1123             }
1124         }
1125         else
1126         {
1127             msleep( VOUT_IDLE_SLEEP );
1128         }
1129
1130         /* On awakening, take back lock and send immediately picture
1131          * to display. */
1132         vlc_object_lock( p_vout );
1133         /* Note: vlc_object_alive() could be false here, and we
1134          * could be dead */
1135         vlc_mutex_lock( &p_vout->change_lock );
1136
1137         /*
1138          * Display the previously rendered picture
1139          */
1140         if( p_filtered_picture != NULL && p_directbuffer != NULL )
1141         {
1142             /* Display the direct buffer returned by vout_RenderPicture */
1143             if( p_vout->pf_display )
1144                 p_vout->pf_display( p_vout, p_directbuffer );
1145
1146             /* Tell the vout this was the last picture and that it does not
1147              * need to be forced anymore. */
1148             p_last_picture = p_picture;
1149             p_last_picture->b_force = false;
1150         }
1151
1152         /* Drop the filtered picture if created by video filters */
1153         if( p_filtered_picture != NULL && p_filtered_picture != p_picture )
1154             DropPicture( p_vout, p_filtered_picture );
1155
1156         if( p_picture != NULL )
1157         {
1158             /* Reinitialize idle loop count */
1159             i_idle_loops = 0;
1160         }
1161
1162         /*
1163          * Check events and manage thread
1164          */
1165         if( p_vout->pf_manage && p_vout->pf_manage( p_vout ) )
1166         {
1167             /* A fatal error occurred, and the thread must terminate
1168              * immediately, without displaying anything - setting b_error to 1
1169              * causes the immediate end of the main while() loop. */
1170             // FIXME pf_end
1171             p_vout->b_error = 1;
1172             break;
1173         }
1174
1175         if( p_vout->i_changes & VOUT_SIZE_CHANGE )
1176         {
1177             /* this must only happen when the vout plugin is incapable of
1178              * rescaling the picture itself. In this case we need to destroy
1179              * the current picture buffers and recreate new ones with the right
1180              * dimensions */
1181             int i;
1182
1183             p_vout->i_changes &= ~VOUT_SIZE_CHANGE;
1184
1185             assert( !p_vout->p->b_direct );
1186
1187             ChromaDestroy( p_vout );
1188
1189             vlc_mutex_lock( &p_vout->picture_lock );
1190
1191             p_vout->pf_end( p_vout );
1192
1193             for( i = 0; i < I_OUTPUTPICTURES; i++ )
1194                  p_vout->p_picture[ i ].i_status = FREE_PICTURE;
1195
1196             I_OUTPUTPICTURES = 0;
1197
1198             if( p_vout->pf_init( p_vout ) )
1199             {
1200                 msg_Err( p_vout, "cannot resize display" );
1201                 /* FIXME: pf_end will be called again in EndThread() */
1202                 p_vout->b_error = 1;
1203             }
1204
1205             vlc_mutex_unlock( &p_vout->picture_lock );
1206
1207             /* Need to reinitialise the chroma plugin. Since we might need
1208              * resizing too and it's not sure that we already had it,
1209              * recreate the chroma plugin chain from scratch. */
1210             /* dionoea */
1211             if( ChromaCreate( p_vout ) )
1212             {
1213                 msg_Err( p_vout, "WOW THIS SUCKS BIG TIME!!!!!" );
1214                 p_vout->b_error = 1;
1215             }
1216             if( p_vout->b_error )
1217                 break;
1218         }
1219
1220         if( p_vout->i_changes & VOUT_PICTURE_BUFFERS_CHANGE )
1221         {
1222             /* This happens when the picture buffers need to be recreated.
1223              * This is useful on multimonitor displays for instance.
1224              *
1225              * Warning: This only works when the vout creates only 1 picture
1226              * buffer!! */
1227             p_vout->i_changes &= ~VOUT_PICTURE_BUFFERS_CHANGE;
1228
1229             if( !p_vout->p->b_direct )
1230                 ChromaDestroy( p_vout );
1231
1232             vlc_mutex_lock( &p_vout->picture_lock );
1233
1234             p_vout->pf_end( p_vout );
1235
1236             I_OUTPUTPICTURES = I_RENDERPICTURES = 0;
1237
1238             p_vout->b_error = InitThread( p_vout );
1239             if( p_vout->b_error )
1240                 msg_Err( p_vout, "InitThread after VOUT_PICTURE_BUFFERS_CHANGE failed\n" );
1241
1242             vlc_mutex_unlock( &p_vout->picture_lock );
1243
1244             if( p_vout->b_error )
1245                 break;
1246         }
1247
1248         /* Check for "video filter2" changes */
1249         vlc_mutex_lock( &p_vout->p->vfilter_lock );
1250         if( p_vout->p->psz_vf2 )
1251         {
1252             es_format_t fmt;
1253
1254             es_format_Init( &fmt, VIDEO_ES, p_vout->fmt_render.i_chroma );
1255             fmt.video = p_vout->fmt_render;
1256             filter_chain_Reset( p_vout->p->p_vf2_chain, &fmt, &fmt );
1257
1258             if( filter_chain_AppendFromString( p_vout->p->p_vf2_chain,
1259                                                p_vout->p->psz_vf2 ) < 0 )
1260                 msg_Err( p_vout, "Video filter chain creation failed" );
1261
1262             free( p_vout->p->psz_vf2 );
1263             p_vout->p->psz_vf2 = NULL;
1264         }
1265         vlc_mutex_unlock( &p_vout->p->vfilter_lock );
1266     }
1267
1268     /*
1269      * Error loop - wait until the thread destruction is requested
1270      */
1271     if( p_vout->b_error )
1272         ErrorThread( p_vout );
1273
1274     /* End of thread */
1275     CleanThread( p_vout );
1276     EndThread( p_vout );
1277     vlc_mutex_unlock( &p_vout->change_lock );
1278
1279     vlc_object_unlock( p_vout );
1280     vlc_restorecancel( canc );
1281     return NULL;
1282 }
1283
1284 /*****************************************************************************
1285  * ErrorThread: RunThread() error loop
1286  *****************************************************************************
1287  * This function is called when an error occurred during thread main's loop.
1288  * The thread can still receive feed, but must be ready to terminate as soon
1289  * as possible.
1290  *****************************************************************************/
1291 static void ErrorThread( vout_thread_t *p_vout )
1292 {
1293     /* Wait until a `die' order */
1294     while( vlc_object_alive( p_vout ) )
1295         vlc_object_wait( p_vout );
1296 }
1297
1298 /*****************************************************************************
1299  * CleanThread: clean up after InitThread
1300  *****************************************************************************
1301  * This function is called after a sucessful
1302  * initialization. It frees all resources allocated by InitThread.
1303  * XXX You have to enter it with change_lock taken.
1304  *****************************************************************************/
1305 static void CleanThread( vout_thread_t *p_vout )
1306 {
1307     int     i_index;                                        /* index in heap */
1308
1309     if( !p_vout->p->b_direct )
1310         ChromaDestroy( p_vout );
1311
1312     /* Destroy all remaining pictures */
1313     for( i_index = 0; i_index < 2 * VOUT_MAX_PICTURES + 1; i_index++ )
1314     {
1315         if ( p_vout->p_picture[i_index].i_type == MEMORY_PICTURE )
1316         {
1317             free( p_vout->p_picture[i_index].p_data_orig );
1318         }
1319     }
1320
1321     /* Destroy translation tables */
1322     if( !p_vout->b_error )
1323         p_vout->pf_end( p_vout );
1324 }
1325
1326 /*****************************************************************************
1327  * EndThread: thread destruction
1328  *****************************************************************************
1329  * This function is called when the thread ends.
1330  * It frees all resources not allocated by InitThread.
1331  * XXX You have to enter it with change_lock taken.
1332  *****************************************************************************/
1333 static void EndThread( vout_thread_t *p_vout )
1334 {
1335 #ifdef STATS
1336     {
1337         struct tms cpu_usage;
1338         times( &cpu_usage );
1339
1340         msg_Dbg( p_vout, "cpu usage (user: %d, system: %d)",
1341                  cpu_usage.tms_utime, cpu_usage.tms_stime );
1342     }
1343 #endif
1344
1345     /* FIXME does that function *really* need to be called inside the thread ? */
1346
1347     /* Destroy subpicture unit */
1348     spu_Attach( p_vout->p_spu, VLC_OBJECT(p_vout), false );
1349
1350     /* Destroy the video filters2 */
1351     filter_chain_Delete( p_vout->p->p_vf2_chain );
1352 }
1353
1354 /* Thread helpers */
1355 static picture_t *ChromaGetPicture( filter_t *p_filter )
1356 {
1357     picture_t *p_pic = (picture_t *)p_filter->p_owner;
1358     p_filter->p_owner = NULL;
1359     return p_pic;
1360 }
1361
1362 static int ChromaCreate( vout_thread_t *p_vout )
1363 {
1364     static const char typename[] = "chroma";
1365     filter_t *p_chroma;
1366
1367     /* Choose the best module */
1368     p_chroma = p_vout->p->p_chroma =
1369         vlc_custom_create( p_vout, sizeof(filter_t), VLC_OBJECT_GENERIC,
1370                            typename );
1371
1372     vlc_object_attach( p_chroma, p_vout );
1373
1374     /* TODO: Set the fmt_in and fmt_out stuff here */
1375     p_chroma->fmt_in.video = p_vout->fmt_render;
1376     p_chroma->fmt_out.video = p_vout->fmt_out;
1377     VideoFormatImportRgb( &p_chroma->fmt_in.video, &p_vout->render );
1378     VideoFormatImportRgb( &p_chroma->fmt_out.video, &p_vout->output );
1379
1380     p_chroma->p_module = module_need( p_chroma, "video filter2", NULL, 0 );
1381
1382     if( p_chroma->p_module == NULL )
1383     {
1384         msg_Err( p_vout, "no chroma module for %4.4s to %4.4s i=%dx%d o=%dx%d",
1385                  (char*)&p_vout->render.i_chroma,
1386                  (char*)&p_vout->output.i_chroma,
1387                  p_chroma->fmt_in.video.i_width, p_chroma->fmt_in.video.i_height,
1388                  p_chroma->fmt_out.video.i_width, p_chroma->fmt_out.video.i_height
1389                  );
1390
1391         vlc_object_release( p_vout->p->p_chroma );
1392         p_vout->p->p_chroma = NULL;
1393
1394         return VLC_EGENERIC;
1395     }
1396     p_chroma->pf_vout_buffer_new = ChromaGetPicture;
1397     return VLC_SUCCESS;
1398 }
1399
1400 static void ChromaDestroy( vout_thread_t *p_vout )
1401 {
1402     assert( !p_vout->p->b_direct );
1403
1404     if( !p_vout->p->p_chroma )
1405         return;
1406
1407     module_unneed( p_vout->p->p_chroma, p_vout->p->p_chroma->p_module );
1408     vlc_object_release( p_vout->p->p_chroma );
1409     p_vout->p->p_chroma = NULL;
1410 }
1411
1412 static void DropPicture( vout_thread_t *p_vout, picture_t *p_picture )
1413 {
1414     vlc_mutex_lock( &p_vout->picture_lock );
1415     if( p_picture->i_refcount )
1416     {
1417         /* Pretend we displayed the picture, but don't destroy
1418          * it since the decoder might still need it. */
1419         p_picture->i_status = DISPLAYED_PICTURE;
1420     }
1421     else
1422     {
1423         /* Destroy the picture without displaying it */
1424         p_picture->i_status = DESTROYED_PICTURE;
1425         p_vout->i_heap_size--;
1426         picture_CleanupQuant( p_picture );
1427     }
1428     vlc_mutex_unlock( &p_vout->picture_lock );
1429 }
1430
1431
1432
1433 /* following functions are local */
1434
1435 static int ReduceHeight( int i_ratio )
1436 {
1437     int i_dummy = VOUT_ASPECT_FACTOR;
1438     int i_pgcd  = 1;
1439
1440     if( !i_ratio )
1441     {
1442         return i_pgcd;
1443     }
1444
1445     /* VOUT_ASPECT_FACTOR is (2^7 * 3^3 * 5^3), we just check for 2, 3 and 5 */
1446     while( !(i_ratio & 1) && !(i_dummy & 1) )
1447     {
1448         i_ratio >>= 1;
1449         i_dummy >>= 1;
1450         i_pgcd  <<= 1;
1451     }
1452
1453     while( !(i_ratio % 3) && !(i_dummy % 3) )
1454     {
1455         i_ratio /= 3;
1456         i_dummy /= 3;
1457         i_pgcd  *= 3;
1458     }
1459
1460     while( !(i_ratio % 5) && !(i_dummy % 5) )
1461     {
1462         i_ratio /= 5;
1463         i_dummy /= 5;
1464         i_pgcd  *= 5;
1465     }
1466
1467     return i_pgcd;
1468 }
1469
1470 static void AspectRatio( int i_aspect, int *i_aspect_x, int *i_aspect_y )
1471 {
1472     unsigned int i_pgcd = ReduceHeight( i_aspect );
1473     *i_aspect_x = i_aspect / i_pgcd;
1474     *i_aspect_y = VOUT_ASPECT_FACTOR / i_pgcd;
1475 }
1476
1477 /**
1478  * This function copies all RGB informations from a picture_heap_t into
1479  * a video_format_t
1480  */
1481 static void VideoFormatImportRgb( video_format_t *p_fmt, const picture_heap_t *p_heap )
1482 {
1483     p_fmt->i_rmask = p_heap->i_rmask;
1484     p_fmt->i_gmask = p_heap->i_gmask;
1485     p_fmt->i_bmask = p_heap->i_bmask;
1486     p_fmt->i_rrshift = p_heap->i_rrshift;
1487     p_fmt->i_lrshift = p_heap->i_lrshift;
1488     p_fmt->i_rgshift = p_heap->i_rgshift;
1489     p_fmt->i_lgshift = p_heap->i_lgshift;
1490     p_fmt->i_rbshift = p_heap->i_rbshift;
1491     p_fmt->i_lbshift = p_heap->i_lbshift;
1492 }
1493
1494 /**
1495  * This funtion copes all RGB informations from a video_format_t into
1496  * a picture_heap_t
1497  */
1498 static void VideoFormatExportRgb( const video_format_t *p_fmt, picture_heap_t *p_heap )
1499 {
1500     p_heap->i_rmask = p_fmt->i_rmask;
1501     p_heap->i_gmask = p_fmt->i_gmask;
1502     p_heap->i_bmask = p_fmt->i_bmask;
1503     p_heap->i_rrshift = p_fmt->i_rrshift;
1504     p_heap->i_lrshift = p_fmt->i_lrshift;
1505     p_heap->i_rgshift = p_fmt->i_rgshift;
1506     p_heap->i_lgshift = p_fmt->i_lgshift;
1507     p_heap->i_rbshift = p_fmt->i_rbshift;
1508     p_heap->i_lbshift = p_fmt->i_lbshift;
1509 }
1510
1511 /**
1512  * This function computes rgb shifts from masks
1513  */
1514 static void PictureHeapFixRgb( picture_heap_t *p_heap )
1515 {
1516     video_format_t fmt;
1517
1518     /* */
1519     fmt.i_chroma = p_heap->i_chroma;
1520     VideoFormatImportRgb( &fmt, p_heap );
1521
1522     /* */
1523     video_format_FixRgb( &fmt );
1524
1525     VideoFormatExportRgb( &fmt, p_heap );
1526 }
1527
1528 /*****************************************************************************
1529  * object variables callbacks: a bunch of object variables are used by the
1530  * interfaces to interact with the vout.
1531  *****************************************************************************/
1532 static int DeinterlaceCallback( vlc_object_t *p_this, char const *psz_cmd,
1533                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
1534 {
1535     vout_thread_t *p_vout = (vout_thread_t *)p_this;
1536     input_thread_t *p_input;
1537     vlc_value_t val;
1538
1539     char *psz_mode = newval.psz_string;
1540     char *psz_filter, *psz_deinterlace = NULL;
1541     (void)psz_cmd; (void)oldval; (void)p_data;
1542
1543     var_Get( p_vout, "vout-filter", &val );
1544     psz_filter = val.psz_string;
1545     if( psz_filter ) psz_deinterlace = strstr( psz_filter, "deinterlace" );
1546
1547     if( !psz_mode || !*psz_mode )
1548     {
1549         if( psz_deinterlace )
1550         {
1551             char *psz_src = psz_deinterlace + sizeof("deinterlace") - 1;
1552             if( psz_src[0] == ':' ) psz_src++;
1553             memmove( psz_deinterlace, psz_src, strlen(psz_src) + 1 );
1554         }
1555     }
1556     else if( !psz_deinterlace )
1557     {
1558         psz_filter = realloc( psz_filter, strlen( psz_filter ) +
1559                               sizeof(":deinterlace") );
1560         if( psz_filter )
1561         {
1562             if( *psz_filter )
1563                 strcat( psz_filter, ":" );
1564             strcat( psz_filter, "deinterlace" );
1565         }
1566     }
1567
1568     p_input = (input_thread_t *)vlc_object_find( p_this, VLC_OBJECT_INPUT,
1569                                                  FIND_PARENT );
1570     if( !p_input )
1571     {
1572         free( psz_filter );
1573         return VLC_EGENERIC;
1574     }
1575
1576     if( psz_mode && *psz_mode )
1577     {
1578         /* Modify input as well because the vout might have to be restarted */
1579         val.psz_string = psz_mode;
1580         var_Create( p_input, "deinterlace-mode", VLC_VAR_STRING );
1581         var_Set( p_input, "deinterlace-mode", val );
1582     }
1583     vlc_object_release( p_input );
1584
1585     val.b_bool = true;
1586     var_Set( p_vout, "intf-change", val );
1587
1588     val.psz_string = psz_filter;
1589     var_Set( p_vout, "vout-filter", val );
1590     free( psz_filter );
1591
1592     return VLC_SUCCESS;
1593 }
1594
1595 static int FilterCallback( vlc_object_t *p_this, char const *psz_cmd,
1596                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
1597 {
1598     vout_thread_t *p_vout = (vout_thread_t *)p_this;
1599     input_thread_t *p_input;
1600     vlc_value_t val;
1601     (void)psz_cmd; (void)oldval; (void)p_data;
1602
1603     p_input = (input_thread_t *)vlc_object_find( p_this, VLC_OBJECT_INPUT,
1604                                                  FIND_PARENT );
1605     if (!p_input)
1606     {
1607         msg_Err( p_vout, "Input not found" );
1608         return( VLC_EGENERIC );
1609     }
1610
1611     val.b_bool = true;
1612     var_Set( p_vout, "intf-change", val );
1613
1614     /* Modify input as well because the vout might have to be restarted */
1615     val.psz_string = newval.psz_string;
1616     var_Create( p_input, "vout-filter", VLC_VAR_STRING );
1617
1618     var_Set( p_input, "vout-filter", val );
1619
1620     /* Now restart current video stream */
1621     input_Control( p_input, INPUT_RESTART_ES, -VIDEO_ES );
1622     vlc_object_release( p_input );
1623
1624     return VLC_SUCCESS;
1625 }
1626
1627 /*****************************************************************************
1628  * Video Filter2 stuff
1629  *****************************************************************************/
1630 static int VideoFilter2Callback( vlc_object_t *p_this, char const *psz_cmd,
1631                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
1632 {
1633     vout_thread_t *p_vout = (vout_thread_t *)p_this;
1634     (void)psz_cmd; (void)oldval; (void)p_data;
1635
1636     vlc_mutex_lock( &p_vout->p->vfilter_lock );
1637     p_vout->p->psz_vf2 = strdup( newval.psz_string );
1638     vlc_mutex_unlock( &p_vout->p->vfilter_lock );
1639
1640     return VLC_SUCCESS;
1641 }
1642
1643 static void DisplayTitleOnOSD( vout_thread_t *p_vout )
1644 {
1645     input_thread_t *p_input;
1646     mtime_t i_now, i_stop;
1647
1648     if( !config_GetInt( p_vout, "osd" ) ) return;
1649
1650     p_input = (input_thread_t *)vlc_object_find( p_vout,
1651               VLC_OBJECT_INPUT, FIND_ANYWHERE );
1652     if( p_input )
1653     {
1654         i_now = mdate();
1655         i_stop = i_now + (mtime_t)(p_vout->p->i_title_timeout * 1000);
1656         char *psz_nowplaying =
1657             input_item_GetNowPlaying( input_GetItem( p_input ) );
1658         char *psz_artist = input_item_GetArtist( input_GetItem( p_input ) );
1659         char *psz_name = input_item_GetTitle( input_GetItem( p_input ) );
1660         if( EMPTY_STR( psz_name ) )
1661         {
1662             free( psz_name );
1663             psz_name = input_item_GetName( input_GetItem( p_input ) );
1664         }
1665         if( !EMPTY_STR( psz_nowplaying ) )
1666         {
1667             vout_ShowTextAbsolute( p_vout, DEFAULT_CHAN,
1668                                    psz_nowplaying, NULL,
1669                                    p_vout->p->i_title_position,
1670                                    30 + p_vout->fmt_in.i_width
1671                                       - p_vout->fmt_in.i_visible_width
1672                                       - p_vout->fmt_in.i_x_offset,
1673                                    20 + p_vout->fmt_in.i_y_offset,
1674                                    i_now, i_stop );
1675         }
1676         else if( !EMPTY_STR( psz_artist ) )
1677         {
1678             char *psz_string = NULL;
1679             if( asprintf( &psz_string, "%s - %s", psz_name, psz_artist ) != -1 )
1680             {
1681                 vout_ShowTextAbsolute( p_vout, DEFAULT_CHAN,
1682                                        psz_string, NULL,
1683                                        p_vout->p->i_title_position,
1684                                        30 + p_vout->fmt_in.i_width
1685                                           - p_vout->fmt_in.i_visible_width
1686                                           - p_vout->fmt_in.i_x_offset,
1687                                        20 + p_vout->fmt_in.i_y_offset,
1688                                        i_now, i_stop );
1689                 free( psz_string );
1690             }
1691         }
1692         else
1693         {
1694             vout_ShowTextAbsolute( p_vout, DEFAULT_CHAN,
1695                                    psz_name, NULL,
1696                                    p_vout->p->i_title_position,
1697                                    30 + p_vout->fmt_in.i_width
1698                                       - p_vout->fmt_in.i_visible_width
1699                                       - p_vout->fmt_in.i_x_offset,
1700                                    20 + p_vout->fmt_in.i_y_offset,
1701                                    i_now, i_stop );
1702         }
1703         vlc_object_release( p_input );
1704         free( psz_artist );
1705         free( psz_name );
1706         free( psz_nowplaying );
1707     }
1708 }
1709