]> git.sesse.net Git - vlc/blob - src/video_output/video_output.c
Ahem: (v)asprintf requires stdio.h; strndup requires string.h
[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-2004 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 #include <vlc/vlc.h>
33
34 #include <stdlib.h>                                                /* free() */
35 #include <string.h>
36
37
38 #ifdef HAVE_SYS_TIMES_H
39 #   include <sys/times.h>
40 #endif
41
42 #include "vlc_video.h"
43 #include "video_output.h"
44 #include "vlc_spu.h"
45 #include <vlc/input.h>                 /* for input_thread_t and i_pts_delay */
46 #include "vlc_playlist.h"
47
48 #include "vlc_filter.h"
49 #include <vlc/sout.h> /* sout_CfgParse */
50
51 #if defined( __APPLE__ )
52 #include "darwin_specific.h"
53 #endif
54
55 /*****************************************************************************
56  * Local prototypes
57  *****************************************************************************/
58 static int      InitThread        ( vout_thread_t * );
59 static void     RunThread         ( vout_thread_t * );
60 static void     ErrorThread       ( vout_thread_t * );
61 static void     EndThread         ( vout_thread_t * );
62 static void     DestroyThread     ( vout_thread_t * );
63
64 static void     AspectRatio       ( int, int *, int * );
65 static int      BinaryLog         ( uint32_t );
66 static void     MaskToShift       ( int *, int *, uint32_t );
67
68 /* Object variables callbacks */
69 static int DeinterlaceCallback( vlc_object_t *, char const *,
70                                 vlc_value_t, vlc_value_t, void * );
71 static int FilterCallback( vlc_object_t *, char const *,
72                            vlc_value_t, vlc_value_t, void * );
73 static int VideoFilter2Callback( vlc_object_t *, char const *,
74                                  vlc_value_t, vlc_value_t, void * );
75
76 /* From vout_intf.c */
77 int vout_Snapshot( vout_thread_t *, picture_t * );
78
79 /* Video filter2 parsing */
80 static int ParseVideoFilter2Chain( vout_thread_t *, char * );
81 static void RemoveVideoFilters2( vout_thread_t *p_vout );
82
83 /*****************************************************************************
84  * Video Filter2 functions
85  *****************************************************************************/
86 struct filter_owner_sys_t
87 {
88     vout_thread_t *p_vout;
89 };
90
91 static picture_t *video_new_buffer_filter( filter_t *p_filter )
92 {
93     picture_t *p_picture;
94     vout_thread_t *p_vout = p_filter->p_owner->p_vout;
95
96     p_picture = vout_CreatePicture( p_vout, 0, 0, 0 );
97
98     return p_picture;
99 }
100
101 static void video_del_buffer_filter( filter_t *p_filter, picture_t *p_pic )
102 {
103     vout_DestroyPicture( p_filter->p_owner->p_vout, p_pic );
104 }
105
106 /*****************************************************************************
107  * vout_Request: find a video output thread, create one, or destroy one.
108  *****************************************************************************
109  * This function looks for a video output thread matching the current
110  * properties. If not found, it spawns a new one.
111  *****************************************************************************/
112 vout_thread_t *__vout_Request( vlc_object_t *p_this, vout_thread_t *p_vout,
113                                video_format_t *p_fmt )
114 {
115     if( !p_fmt )
116     {
117         /* Reattach video output to input before bailing out */
118         if( p_vout )
119         {
120             vlc_object_t *p_playlist;
121
122             p_playlist = vlc_object_find( p_this, VLC_OBJECT_PLAYLIST,
123                                           FIND_ANYWHERE );
124
125             if( p_playlist )
126             {
127                 spu_Attach( p_vout->p_spu, p_this, VLC_FALSE );
128                 vlc_object_detach( p_vout );
129                 vlc_object_attach( p_vout, p_playlist );
130
131                 vlc_object_release( p_playlist );
132             }
133             else
134             {
135                 msg_Dbg( p_this, "cannot find playlist, destroying vout" );
136                 vlc_object_detach( p_vout );
137                 vout_Destroy( p_vout );
138             }
139         }
140         return NULL;
141     }
142
143     /* If a video output was provided, lock it, otherwise look for one. */
144     if( p_vout )
145     {
146         vlc_object_yield( p_vout );
147     }
148     else
149     {
150         p_vout = vlc_object_find( p_this, VLC_OBJECT_VOUT, FIND_CHILD );
151
152         if( !p_vout )
153         {
154             playlist_t *p_playlist;
155
156             p_playlist = vlc_object_find( p_this,
157                                           VLC_OBJECT_PLAYLIST, FIND_ANYWHERE );
158             if( p_playlist )
159             {
160                 vlc_mutex_lock( &p_playlist->gc_lock );
161                 p_vout = vlc_object_find( p_playlist,
162                                           VLC_OBJECT_VOUT, FIND_CHILD );
163                 /* only first children of p_input for unused vout */
164                 if( p_vout && p_vout->p_parent != (vlc_object_t *)p_playlist )
165                 {
166                     vlc_object_release( p_vout );
167                     p_vout = NULL;
168                 }
169                 vlc_mutex_unlock( &p_playlist->gc_lock );
170                 vlc_object_release( p_playlist );
171             }
172         }
173     }
174
175     /* If we now have a video output, check it has the right properties */
176     if( p_vout )
177     {
178         char *psz_filter_chain;
179         vlc_value_t val;
180
181         /* We don't directly check for the "vout-filter" variable for obvious
182          * performance reasons. */
183         if( p_vout->b_filter_change )
184         {
185             var_Get( p_vout, "vout-filter", &val );
186             psz_filter_chain = val.psz_string;
187
188             if( psz_filter_chain && !*psz_filter_chain )
189             {
190                 free( psz_filter_chain );
191                 psz_filter_chain = NULL;
192             }
193             if( p_vout->psz_filter_chain && !*p_vout->psz_filter_chain )
194             {
195                 free( p_vout->psz_filter_chain );
196                 p_vout->psz_filter_chain = NULL;
197             }
198
199             if( !psz_filter_chain && !p_vout->psz_filter_chain )
200             {
201                 p_vout->b_filter_change = VLC_FALSE;
202             }
203
204             if( psz_filter_chain ) free( psz_filter_chain );
205         }
206
207         if( ( p_vout->fmt_render.i_width != p_fmt->i_width ) ||
208             ( p_vout->fmt_render.i_height != p_fmt->i_height ) ||
209             ( p_vout->fmt_render.i_chroma != p_fmt->i_chroma ) ||
210             ( p_vout->fmt_render.i_aspect != p_fmt->i_aspect ) ||
211             p_vout->b_filter_change )
212         {
213             /* We are not interested in this format, close this vout */
214             vlc_object_detach( p_vout );
215             vlc_object_release( p_vout );
216             vout_Destroy( p_vout );
217             p_vout = NULL;
218         }
219         else
220         {
221             /* This video output is cool! Hijack it. */
222             vlc_object_detach( p_vout );
223             spu_Attach( p_vout->p_spu, p_this, VLC_TRUE );
224             vlc_object_attach( p_vout, p_this );
225             vlc_object_release( p_vout );
226         }
227     }
228
229     if( !p_vout )
230     {
231         msg_Dbg( p_this, "no usable vout present, spawning one" );
232
233         p_vout = vout_Create( p_this, p_fmt );
234     }
235
236     return p_vout;
237 }
238
239 /*****************************************************************************
240  * vout_Create: creates a new video output thread
241  *****************************************************************************
242  * This function creates a new video output thread, and returns a pointer
243  * to its description. On error, it returns NULL.
244  *****************************************************************************/
245 vout_thread_t * __vout_Create( vlc_object_t *p_parent, video_format_t *p_fmt )
246 {
247     vout_thread_t  * p_vout;                            /* thread descriptor */
248     input_thread_t * p_input_thread;
249     int              i_index;                               /* loop variable */
250     char           * psz_plugin;
251     vlc_value_t      val, text;
252
253     unsigned int i_width = p_fmt->i_width;
254     unsigned int i_height = p_fmt->i_height;
255     vlc_fourcc_t i_chroma = p_fmt->i_chroma;
256     unsigned int i_aspect = p_fmt->i_aspect;
257
258     /* Allocate descriptor */
259     p_vout = vlc_object_create( p_parent, VLC_OBJECT_VOUT );
260     if( p_vout == NULL )
261     {
262         msg_Err( p_parent, "out of memory" );
263         return NULL;
264     }
265
266     /* Initialize pictures - translation tables and functions
267      * will be initialized later in InitThread */
268     for( i_index = 0; i_index < 2 * VOUT_MAX_PICTURES + 1; i_index++)
269     {
270         p_vout->p_picture[i_index].pf_lock = NULL;
271         p_vout->p_picture[i_index].pf_unlock = NULL;
272         p_vout->p_picture[i_index].i_status = FREE_PICTURE;
273         p_vout->p_picture[i_index].i_type   = EMPTY_PICTURE;
274         p_vout->p_picture[i_index].b_slow   = 0;
275     }
276
277     /* No images in the heap */
278     p_vout->i_heap_size = 0;
279
280     /* Initialize the rendering heap */
281     I_RENDERPICTURES = 0;
282
283     vlc_ureduce( &p_fmt->i_sar_num, &p_fmt->i_sar_den,
284                  p_fmt->i_sar_num, p_fmt->i_sar_den, 50000 );
285     p_vout->fmt_render        = *p_fmt;   /* FIXME palette */
286     p_vout->fmt_in            = *p_fmt;   /* FIXME palette */
287
288     p_vout->render.i_width    = i_width;
289     p_vout->render.i_height   = i_height;
290     p_vout->render.i_chroma   = i_chroma;
291     p_vout->render.i_aspect   = i_aspect;
292
293     p_vout->render.i_rmask    = 0;
294     p_vout->render.i_gmask    = 0;
295     p_vout->render.i_bmask    = 0;
296
297     p_vout->render.i_last_used_pic = -1;
298     p_vout->render.b_allow_modify_pics = 1;
299
300     /* Zero the output heap */
301     I_OUTPUTPICTURES = 0;
302     p_vout->output.i_width    = 0;
303     p_vout->output.i_height   = 0;
304     p_vout->output.i_chroma   = 0;
305     p_vout->output.i_aspect   = 0;
306
307     p_vout->output.i_rmask    = 0;
308     p_vout->output.i_gmask    = 0;
309     p_vout->output.i_bmask    = 0;
310
311     /* Initialize misc stuff */
312     p_vout->i_changes    = 0;
313     p_vout->f_gamma      = 0;
314     p_vout->b_grayscale  = 0;
315     p_vout->b_info       = 0;
316     p_vout->b_interface  = 0;
317     p_vout->b_scale      = 1;
318     p_vout->b_fullscreen = 0;
319     p_vout->i_alignment  = 0;
320     p_vout->render_time  = 10;
321     p_vout->c_fps_samples = 0;
322     p_vout->b_filter_change = 0;
323     p_vout->pf_control = 0;
324     p_vout->p_parent_intf = 0;
325     p_vout->i_par_num = p_vout->i_par_den = 1;
326
327     /* Initialize locks */
328     vlc_mutex_init( p_vout, &p_vout->picture_lock );
329     vlc_mutex_init( p_vout, &p_vout->change_lock );
330
331     /* Mouse coordinates */
332     var_Create( p_vout, "mouse-x", VLC_VAR_INTEGER );
333     var_Create( p_vout, "mouse-y", VLC_VAR_INTEGER );
334     var_Create( p_vout, "mouse-button-down", VLC_VAR_INTEGER );
335     var_Create( p_vout, "mouse-moved", VLC_VAR_BOOL );
336     var_Create( p_vout, "mouse-clicked", VLC_VAR_INTEGER );
337
338     /* Initialize subpicture unit */
339     p_vout->p_spu = spu_Create( p_vout );
340     spu_Attach( p_vout->p_spu, p_parent, VLC_TRUE );
341
342     /* Attach the new object now so we can use var inheritance below */
343     vlc_object_attach( p_vout, p_parent );
344
345     spu_Init( p_vout->p_spu );
346
347     /* Take care of some "interface/control" related initialisations */
348     vout_IntfInit( p_vout );
349
350     /* If the parent is not a VOUT object, that means we are at the start of
351      * the video output pipe */
352     if( p_parent->i_object_type != VLC_OBJECT_VOUT )
353     {
354         /* Look for the default filter configuration */
355         var_Create( p_vout, "vout-filter", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
356         var_Get( p_vout, "vout-filter", &val );
357         p_vout->psz_filter_chain = val.psz_string;
358
359         /* Apply video filter2 objects on the first vout */
360         var_Create( p_vout, "video-filter",
361                     VLC_VAR_STRING | VLC_VAR_DOINHERIT );
362         var_Get( p_vout, "video-filter", &val );
363         ParseVideoFilter2Chain( p_vout, val.psz_string );
364         free( val.psz_string );
365     }
366     else
367     {
368         /* continue the parent's filter chain */
369         char *psz_end;
370
371         psz_end = strchr( ((vout_thread_t *)p_parent)->psz_filter_chain, ':' );
372         if( psz_end && *(psz_end+1) )
373             p_vout->psz_filter_chain = strdup( psz_end+1 );
374         else p_vout->psz_filter_chain = NULL;
375
376         /* Create a video filter2 var ... but don't inherit values */
377         var_Create( p_vout, "video-filter", VLC_VAR_STRING );
378         ParseVideoFilter2Chain( p_vout, NULL );
379     }
380
381     var_AddCallback( p_vout, "video-filter", VideoFilter2Callback, NULL );
382     p_vout->b_vfilter_change = VLC_TRUE;
383     p_vout->i_vfilters = 0;
384
385     /* Choose the video output module */
386     if( !p_vout->psz_filter_chain || !*p_vout->psz_filter_chain )
387     {
388         var_Create( p_vout, "vout", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
389         var_Get( p_vout, "vout", &val );
390         psz_plugin = val.psz_string;
391     }
392     else
393     {
394         /* the filter chain is a string list of filters separated by double
395          * colons */
396         char *psz_end;
397
398         psz_end = strchr( p_vout->psz_filter_chain, ':' );
399         if( psz_end )
400             psz_plugin = strndup( p_vout->psz_filter_chain,
401                                   psz_end - p_vout->psz_filter_chain );
402         else psz_plugin = strdup( p_vout->psz_filter_chain );
403     }
404
405     /* Create the vout thread */
406     p_vout->p_module = module_Need( p_vout,
407         ( p_vout->psz_filter_chain && *p_vout->psz_filter_chain ) ?
408         "video filter" : "video output", psz_plugin, 0 );
409
410     if( psz_plugin ) free( psz_plugin );
411     if( p_vout->p_module == NULL )
412     {
413         msg_Err( p_vout, "no suitable vout module" );
414         vlc_object_detach( p_vout );
415         vlc_object_destroy( p_vout );
416         return NULL;
417     }
418
419     /* Create a few object variables for interface interaction */
420     var_Create( p_vout, "deinterlace", VLC_VAR_STRING | VLC_VAR_HASCHOICE );
421     text.psz_string = _("Deinterlace");
422     var_Change( p_vout, "deinterlace", VLC_VAR_SETTEXT, &text, NULL );
423     val.psz_string = ""; text.psz_string = _("Disable");
424     var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
425     val.psz_string = "discard"; text.psz_string = _("Discard");
426     var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
427     val.psz_string = "blend"; text.psz_string = _("Blend");
428     var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
429     val.psz_string = "mean"; text.psz_string = _("Mean");
430     var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
431     val.psz_string = "bob"; text.psz_string = _("Bob");
432     var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
433     val.psz_string = "linear"; text.psz_string = _("Linear");
434     var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
435     val.psz_string = "x"; text.psz_string = "X";
436     var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
437
438     if( var_Get( p_vout, "deinterlace-mode", &val ) == VLC_SUCCESS )
439     {
440         var_Set( p_vout, "deinterlace", val );
441         if( val.psz_string ) free( val.psz_string );
442     }
443     var_AddCallback( p_vout, "deinterlace", DeinterlaceCallback, NULL );
444
445
446     var_Create( p_vout, "vout-filter", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
447     text.psz_string = _("Filters");
448     var_Change( p_vout, "vout-filter", VLC_VAR_SETTEXT, &text, NULL );
449     var_AddCallback( p_vout, "vout-filter", FilterCallback, NULL );
450
451     /* Calculate delay created by internal caching */
452     p_input_thread = (input_thread_t *)vlc_object_find( p_vout,
453                                            VLC_OBJECT_INPUT, FIND_ANYWHERE );
454     if( p_input_thread )
455     {
456         p_vout->i_pts_delay = p_input_thread->i_pts_delay;
457         vlc_object_release( p_input_thread );
458     }
459     else
460     {
461         p_vout->i_pts_delay = DEFAULT_PTS_DELAY;
462     }
463
464     if( vlc_thread_create( p_vout, "video output", RunThread,
465                            VLC_THREAD_PRIORITY_OUTPUT, VLC_TRUE ) )
466     {
467         msg_Err( p_vout, "out of memory" );
468         module_Unneed( p_vout, p_vout->p_module );
469         vlc_object_detach( p_vout );
470         vlc_object_destroy( p_vout );
471         return NULL;
472     }
473
474     if( p_vout->b_error )
475     {
476         msg_Err( p_vout, "video output creation failed" );
477
478         /* Make sure the thread is destroyed */
479         p_vout->b_die = VLC_TRUE;
480
481         vlc_thread_join( p_vout );
482
483         vlc_object_detach( p_vout );
484         vlc_object_destroy( p_vout );
485         return NULL;
486     }
487
488     return p_vout;
489 }
490
491 /*****************************************************************************
492  * vout_Destroy: destroys a previously created video output
493  *****************************************************************************
494  * Destroy a terminated thread.
495  * The function will request a destruction of the specified thread. If pi_error
496  * is NULL, it will return once the thread is destroyed. Else, it will be
497  * update using one of the THREAD_* constants.
498  *****************************************************************************/
499 void vout_Destroy( vout_thread_t *p_vout )
500 {
501     vlc_object_t *p_playlist;
502
503     /* Request thread destruction */
504     p_vout->b_die = VLC_TRUE;
505     vlc_thread_join( p_vout );
506
507     var_Destroy( p_vout, "intf-change" );
508
509     p_playlist = vlc_object_find( p_vout, VLC_OBJECT_PLAYLIST,
510                                   FIND_ANYWHERE );
511
512     if( p_vout->psz_filter_chain ) free( p_vout->psz_filter_chain );
513
514     /* Free structure */
515     vlc_object_destroy( p_vout );
516
517     /* If it was the last vout, tell the interface to show up */
518     if( p_playlist != NULL )
519     {
520         vout_thread_t *p_another_vout = vlc_object_find( p_playlist,
521                                             VLC_OBJECT_VOUT, FIND_ANYWHERE );
522         if( p_another_vout == NULL )
523         {
524             vlc_value_t val;
525             val.b_bool = VLC_TRUE;
526             var_Set( p_playlist, "intf-show", val );
527         }
528         else
529         {
530             vlc_object_release( p_another_vout );
531         }
532         vlc_object_release( p_playlist );
533     }
534 }
535
536 /*****************************************************************************
537  * InitThread: initialize video output thread
538  *****************************************************************************
539  * This function is called from RunThread and performs the second step of the
540  * initialization. It returns 0 on success. Note that the thread's flag are not
541  * modified inside this function.
542  *****************************************************************************/
543 static int InitThread( vout_thread_t *p_vout )
544 {
545     int i, i_aspect_x, i_aspect_y;
546
547     vlc_mutex_lock( &p_vout->change_lock );
548
549 #ifdef STATS
550     p_vout->c_loops = 0;
551 #endif
552
553     /* Initialize output method, it allocates direct buffers for us */
554     if( p_vout->pf_init( p_vout ) )
555     {
556         vlc_mutex_unlock( &p_vout->change_lock );
557         return VLC_EGENERIC;
558     }
559
560     if( !I_OUTPUTPICTURES )
561     {
562         msg_Err( p_vout, "plugin was unable to allocate at least "
563                          "one direct buffer" );
564         p_vout->pf_end( p_vout );
565         vlc_mutex_unlock( &p_vout->change_lock );
566         return VLC_EGENERIC;
567     }
568
569     if( I_OUTPUTPICTURES > VOUT_MAX_PICTURES )
570     {
571         msg_Err( p_vout, "plugin allocated too many direct buffers, "
572                          "our internal buffers must have overflown." );
573         p_vout->pf_end( p_vout );
574         vlc_mutex_unlock( &p_vout->change_lock );
575         return VLC_EGENERIC;
576     }
577
578     msg_Dbg( p_vout, "got %i direct buffer(s)", I_OUTPUTPICTURES );
579
580     AspectRatio( p_vout->fmt_render.i_aspect, &i_aspect_x, &i_aspect_y );
581
582     msg_Dbg( p_vout, "picture in %ix%i (%i,%i,%ix%i), "
583              "chroma %4.4s, ar %i:%i, sar %i:%i",
584              p_vout->fmt_render.i_width, p_vout->fmt_render.i_height,
585              p_vout->fmt_render.i_x_offset, p_vout->fmt_render.i_y_offset,
586              p_vout->fmt_render.i_visible_width,
587              p_vout->fmt_render.i_visible_height,
588              (char*)&p_vout->fmt_render.i_chroma,
589              i_aspect_x, i_aspect_y,
590              p_vout->fmt_render.i_sar_num, p_vout->fmt_render.i_sar_den );
591
592     AspectRatio( p_vout->fmt_in.i_aspect, &i_aspect_x, &i_aspect_y );
593
594     msg_Dbg( p_vout, "picture user %ix%i (%i,%i,%ix%i), "
595              "chroma %4.4s, ar %i:%i, sar %i:%i",
596              p_vout->fmt_in.i_width, p_vout->fmt_in.i_height,
597              p_vout->fmt_in.i_x_offset, p_vout->fmt_in.i_y_offset,
598              p_vout->fmt_in.i_visible_width,
599              p_vout->fmt_in.i_visible_height,
600              (char*)&p_vout->fmt_in.i_chroma,
601              i_aspect_x, i_aspect_y,
602              p_vout->fmt_in.i_sar_num, p_vout->fmt_in.i_sar_den );
603
604     if( !p_vout->fmt_out.i_width || !p_vout->fmt_out.i_height )
605     {
606         p_vout->fmt_out.i_width = p_vout->fmt_out.i_visible_width =
607             p_vout->output.i_width;
608         p_vout->fmt_out.i_height = p_vout->fmt_out.i_visible_height =
609             p_vout->output.i_height;
610         p_vout->fmt_out.i_x_offset =  p_vout->fmt_out.i_y_offset = 0;
611
612         p_vout->fmt_out.i_aspect = p_vout->output.i_aspect;
613         p_vout->fmt_out.i_chroma = p_vout->output.i_chroma;
614     }
615     if( !p_vout->fmt_out.i_sar_num || !p_vout->fmt_out.i_sar_num )
616     {
617         p_vout->fmt_out.i_sar_num = p_vout->fmt_out.i_aspect *
618             p_vout->fmt_out.i_height;
619         p_vout->fmt_out.i_sar_den = VOUT_ASPECT_FACTOR *
620             p_vout->fmt_out.i_width;
621     }
622
623     vlc_ureduce( &p_vout->fmt_out.i_sar_num, &p_vout->fmt_out.i_sar_den,
624                  p_vout->fmt_out.i_sar_num, p_vout->fmt_out.i_sar_den, 0 );
625
626     AspectRatio( p_vout->fmt_out.i_aspect, &i_aspect_x, &i_aspect_y );
627
628     msg_Dbg( p_vout, "picture out %ix%i (%i,%i,%ix%i), "
629              "chroma %4.4s, ar %i:%i, sar %i:%i",
630              p_vout->fmt_out.i_width, p_vout->fmt_out.i_height,
631              p_vout->fmt_out.i_x_offset, p_vout->fmt_out.i_y_offset,
632              p_vout->fmt_out.i_visible_width,
633              p_vout->fmt_out.i_visible_height,
634              (char*)&p_vout->fmt_out.i_chroma,
635              i_aspect_x, i_aspect_y,
636              p_vout->fmt_out.i_sar_num, p_vout->fmt_out.i_sar_den );
637
638     /* Calculate shifts from system-updated masks */
639     MaskToShift( &p_vout->output.i_lrshift, &p_vout->output.i_rrshift,
640                  p_vout->output.i_rmask );
641     MaskToShift( &p_vout->output.i_lgshift, &p_vout->output.i_rgshift,
642                  p_vout->output.i_gmask );
643     MaskToShift( &p_vout->output.i_lbshift, &p_vout->output.i_rbshift,
644                  p_vout->output.i_bmask );
645
646     /* Check whether we managed to create direct buffers similar to
647      * the render buffers, ie same size and chroma */
648     if( ( p_vout->output.i_width == p_vout->render.i_width )
649      && ( p_vout->output.i_height == p_vout->render.i_height )
650      && ( vout_ChromaCmp( p_vout->output.i_chroma, p_vout->render.i_chroma ) ) )
651     {
652         /* Cool ! We have direct buffers, we can ask the decoder to
653          * directly decode into them ! Map the first render buffers to
654          * the first direct buffers, but keep the first direct buffer
655          * for memcpy operations */
656         p_vout->b_direct = 1;
657
658         for( i = 1; i < VOUT_MAX_PICTURES; i++ )
659         {
660             if( p_vout->p_picture[ i ].i_type != DIRECT_PICTURE &&
661                 I_RENDERPICTURES >= VOUT_MIN_DIRECT_PICTURES - 1 &&
662                 p_vout->p_picture[ i - 1 ].i_type == DIRECT_PICTURE )
663             {
664                 /* We have enough direct buffers so there's no need to
665                  * try to use system memory buffers. */
666                 break;
667             }
668             PP_RENDERPICTURE[ I_RENDERPICTURES ] = &p_vout->p_picture[ i ];
669             I_RENDERPICTURES++;
670         }
671
672         msg_Dbg( p_vout, "direct render, mapping "
673                  "render pictures 0-%i to system pictures 1-%i",
674                  VOUT_MAX_PICTURES - 2, VOUT_MAX_PICTURES - 1 );
675     }
676     else
677     {
678         /* Rats... Something is wrong here, we could not find an output
679          * plugin able to directly render what we decode. See if we can
680          * find a chroma plugin to do the conversion */
681         p_vout->b_direct = 0;
682
683         /* Choose the best module */
684         p_vout->chroma.p_module = module_Need( p_vout, "chroma", NULL, 0 );
685
686         if( p_vout->chroma.p_module == NULL )
687         {
688             msg_Err( p_vout, "no chroma module for %4.4s to %4.4s",
689                      (char*)&p_vout->render.i_chroma,
690                      (char*)&p_vout->output.i_chroma );
691             p_vout->pf_end( p_vout );
692             vlc_mutex_unlock( &p_vout->change_lock );
693             return VLC_EGENERIC;
694         }
695
696         msg_Dbg( p_vout, "indirect render, mapping "
697                  "render pictures 0-%i to system pictures %i-%i",
698                  VOUT_MAX_PICTURES - 1, I_OUTPUTPICTURES,
699                  I_OUTPUTPICTURES + VOUT_MAX_PICTURES - 1 );
700
701         /* Append render buffers after the direct buffers */
702         for( i = I_OUTPUTPICTURES; i < 2 * VOUT_MAX_PICTURES; i++ )
703         {
704             PP_RENDERPICTURE[ I_RENDERPICTURES ] = &p_vout->p_picture[ i ];
705             I_RENDERPICTURES++;
706
707             /* Check if we have enough render pictures */
708             if( I_RENDERPICTURES == VOUT_MAX_PICTURES )
709                 break;
710         }
711     }
712
713     /* Link pictures back to their heap */
714     for( i = 0 ; i < I_RENDERPICTURES ; i++ )
715     {
716         PP_RENDERPICTURE[ i ]->p_heap = &p_vout->render;
717     }
718
719     for( i = 0 ; i < I_OUTPUTPICTURES ; i++ )
720     {
721         PP_OUTPUTPICTURE[ i ]->p_heap = &p_vout->output;
722     }
723
724 /* XXX XXX mark thread ready */
725     return VLC_SUCCESS;
726 }
727
728 /*****************************************************************************
729  * RunThread: video output thread
730  *****************************************************************************
731  * Video output thread. This function does only returns when the thread is
732  * terminated. It handles the pictures arriving in the video heap and the
733  * display device events.
734  *****************************************************************************/
735 static void RunThread( vout_thread_t *p_vout)
736 {
737     int             i_index;                                /* index in heap */
738     int             i_idle_loops = 0;  /* loops without displaying a picture */
739     mtime_t         current_date;                            /* current date */
740     mtime_t         display_date;                            /* display date */
741
742     picture_t *     p_picture;                            /* picture pointer */
743     picture_t *     p_last_picture = NULL;                   /* last picture */
744     picture_t *     p_directbuffer;              /* direct buffer to display */
745
746     subpicture_t *  p_subpic = NULL;                   /* subpicture pointer */
747
748     input_thread_t *p_input = NULL ;           /* Parent input, if it exists */
749
750     vlc_value_t     val;
751     vlc_bool_t      b_drop_late;
752
753     int             i_displayed = 0, i_lost = 0, i_loops = 0;
754
755     /*
756      * Initialize thread
757      */
758     p_vout->b_error = InitThread( p_vout );
759
760     var_Create( p_vout, "drop-late-frames", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
761     var_Get( p_vout, "drop-late-frames", &val );
762     b_drop_late = val.b_bool;
763
764     /* signal the creation of the vout */
765     vlc_thread_ready( p_vout );
766
767     if( p_vout->b_error )
768     {
769         /* Destroy thread structures allocated by Create and InitThread */
770         DestroyThread( p_vout );
771         return;
772     }
773
774     /*
775      * Main loop - it is not executed if an error occurred during
776      * initialization
777      */
778     while( (!p_vout->b_die) && (!p_vout->b_error) )
779     {
780         /* Initialize loop variables */
781         p_picture = NULL;
782         display_date = 0;
783         current_date = mdate();
784
785         if( p_input && p_input->b_die )
786         {
787             vlc_object_release( p_input );
788             p_input = NULL;
789         }
790
791         i_loops++;
792         if( i_loops % 20 == 0 )
793         {
794             if( !p_input )
795             {
796                 p_input = vlc_object_find( p_vout, VLC_OBJECT_INPUT,
797                                            FIND_PARENT );
798             }
799             if( p_input )
800             {
801                 vlc_mutex_lock( &p_input->counters.counters_lock );
802                 stats_UpdateInteger( p_vout, p_input->counters.p_lost_pictures,
803                                      i_lost , NULL);
804                 stats_UpdateInteger( p_vout,
805                                      p_input->counters.p_displayed_pictures,
806                                      i_displayed , NULL);
807                 i_displayed = i_lost = 0;
808                 vlc_mutex_unlock( &p_input->counters.counters_lock );
809             }
810         }
811 #if 0
812         p_vout->c_loops++;
813         if( !(p_vout->c_loops % VOUT_STATS_NB_LOOPS) )
814         {
815             msg_Dbg( p_vout, "picture heap: %d/%d",
816                      I_RENDERPICTURES, p_vout->i_heap_size );
817         }
818 #endif
819
820         /*
821          * Find the picture to display (the one with the earliest date).
822          * This operation does not need lock, since only READY_PICTUREs
823          * are handled. */
824         for( i_index = 0; i_index < I_RENDERPICTURES; i_index++ )
825         {
826             if( (PP_RENDERPICTURE[i_index]->i_status == READY_PICTURE)
827                 && ( (p_picture == NULL) ||
828                      (PP_RENDERPICTURE[i_index]->date < display_date) ) )
829             {
830                 p_picture = PP_RENDERPICTURE[i_index];
831                 display_date = p_picture->date;
832             }
833         }
834
835         if( p_picture )
836         {
837             /* If we met the last picture, parse again to see whether there is
838              * a more appropriate one. */
839             if( p_picture == p_last_picture )
840             {
841                 for( i_index = 0; i_index < I_RENDERPICTURES; i_index++ )
842                 {
843                     if( (PP_RENDERPICTURE[i_index]->i_status == READY_PICTURE)
844                         && (PP_RENDERPICTURE[i_index] != p_last_picture)
845                         && ((p_picture == p_last_picture) ||
846                             (PP_RENDERPICTURE[i_index]->date < display_date)) )
847                     {
848                         p_picture = PP_RENDERPICTURE[i_index];
849                         display_date = p_picture->date;
850                     }
851                 }
852             }
853
854             /* If we found better than the last picture, destroy it */
855             if( p_last_picture && p_picture != p_last_picture )
856             {
857                 vlc_mutex_lock( &p_vout->picture_lock );
858                 if( p_last_picture->i_refcount )
859                 {
860                     p_last_picture->i_status = DISPLAYED_PICTURE;
861                 }
862                 else
863                 {
864                     p_last_picture->i_status = DESTROYED_PICTURE;
865                     p_vout->i_heap_size--;
866                 }
867                 vlc_mutex_unlock( &p_vout->picture_lock );
868                 p_last_picture = NULL;
869             }
870
871             /* Compute FPS rate */
872             p_vout->p_fps_sample[ p_vout->c_fps_samples++ % VOUT_FPS_SAMPLES ]
873                 = display_date;
874
875             if( !p_picture->b_force &&
876                 p_picture != p_last_picture &&
877                 display_date < current_date + p_vout->render_time &&
878                 b_drop_late )
879             {
880                 /* Picture is late: it will be destroyed and the thread
881                  * will directly choose the next picture */
882                 vlc_mutex_lock( &p_vout->picture_lock );
883                 if( p_picture->i_refcount )
884                 {
885                     /* Pretend we displayed the picture, but don't destroy
886                      * it since the decoder might still need it. */
887                     p_picture->i_status = DISPLAYED_PICTURE;
888                 }
889                 else
890                 {
891                     /* Destroy the picture without displaying it */
892                     p_picture->i_status = DESTROYED_PICTURE;
893                     p_vout->i_heap_size--;
894                 }
895                 msg_Warn( p_vout, "late picture skipped ("I64Fd")",
896                                   current_date - display_date );
897                 i_lost++;
898                 vlc_mutex_unlock( &p_vout->picture_lock );
899
900                 continue;
901             }
902
903             if( display_date >
904                 current_date + p_vout->i_pts_delay + VOUT_BOGUS_DELAY )
905             {
906                 /* Picture is waaay too early: it will be destroyed */
907                 vlc_mutex_lock( &p_vout->picture_lock );
908                 if( p_picture->i_refcount )
909                 {
910                     /* Pretend we displayed the picture, but don't destroy
911                      * it since the decoder might still need it. */
912                     p_picture->i_status = DISPLAYED_PICTURE;
913                 }
914                 else
915                 {
916                     /* Destroy the picture without displaying it */
917                     p_picture->i_status = DESTROYED_PICTURE;
918                     p_vout->i_heap_size--;
919                 }
920                 i_lost++;
921                 msg_Warn( p_vout, "vout warning: early picture skipped "
922                           "("I64Fd")", display_date - current_date
923                           - p_vout->i_pts_delay );
924                 vlc_mutex_unlock( &p_vout->picture_lock );
925
926                 continue;
927             }
928
929             if( display_date > current_date + VOUT_DISPLAY_DELAY )
930             {
931                 /* A picture is ready to be rendered, but its rendering date
932                  * is far from the current one so the thread will perform an
933                  * empty loop as if no picture were found. The picture state
934                  * is unchanged */
935                 p_picture    = NULL;
936                 display_date = 0;
937             }
938             else if( p_picture == p_last_picture )
939             {
940                 /* We are asked to repeat the previous picture, but we first
941                  * wait for a couple of idle loops */
942                 if( i_idle_loops < 4 )
943                 {
944                     p_picture    = NULL;
945                     display_date = 0;
946                 }
947                 else
948                 {
949                     /* We set the display date to something high, otherwise
950                      * we'll have lots of problems with late pictures */
951                     display_date = current_date + p_vout->render_time;
952                 }
953             }
954         }
955
956         if( p_picture == NULL )
957         {
958             i_idle_loops++;
959         }
960
961         /* Video Filter2 stuff */
962         if( p_vout->b_vfilter_change == VLC_TRUE )
963         {
964             int i;
965             RemoveVideoFilters2( p_vout );
966             for( i = 0; i < p_vout->i_vfilters_cfg; i++ )
967             {
968                 filter_t *p_vfilter =
969                     p_vout->pp_vfilters[p_vout->i_vfilters] =
970                         vlc_object_create( p_vout, VLC_OBJECT_FILTER );
971
972                 vlc_object_attach( p_vfilter, p_vout );
973
974                 p_vfilter->pf_vout_buffer_new = video_new_buffer_filter;
975                 p_vfilter->pf_vout_buffer_del = video_del_buffer_filter;
976
977                 if( !p_vout->i_vfilters )
978                 {
979                     p_vfilter->fmt_in.video = p_vout->fmt_render;
980                 }
981                 else
982                 {
983                     p_vfilter->fmt_in.video = (p_vfilter-1)->fmt_out.video;
984                 }
985                 /* TODO: one day filters in the middle of the chain might
986                  * have a different fmt_out.video than fmt_render ... */
987                 p_vfilter->fmt_out.video = p_vout->fmt_render;
988
989                 p_vfilter->p_cfg = p_vout->p_vfilters_cfg[i];
990                 p_vfilter->p_module = module_Need( p_vfilter, "video filter2",
991                                                  p_vout->psz_vfilters[i], 0 );
992
993                 if( p_vfilter->p_module )
994                 {
995                     p_vfilter->p_owner =
996                         malloc( sizeof( filter_owner_sys_t ) );
997                     p_vfilter->p_owner->p_vout = p_vout;
998                     p_vout->i_vfilters++;
999                     msg_Dbg( p_vout, "video filter found (%s)",
1000                              p_vout->psz_vfilters[i] );
1001                 }
1002                 else
1003                 {
1004                     msg_Err( p_vout, "no video filter found (%s)",
1005                              p_vout->psz_vfilters[i] );
1006                     vlc_object_detach( p_vfilter );
1007                     vlc_object_destroy( p_vfilter );
1008                 }
1009             }
1010             p_vout->b_vfilter_change = VLC_FALSE;
1011         }
1012
1013         if( p_picture )
1014         {
1015             int i;
1016             for( i = 0; i < p_vout->i_vfilters; i++ )
1017             {
1018                 picture_t *p_old = p_picture;
1019                 p_picture  = p_vout->pp_vfilters[i]->pf_video_filter(
1020                                  p_vout->pp_vfilters[i], p_picture );
1021                 if( !p_picture )
1022                 {
1023                     break;
1024                 }
1025                 /* FIXME: this is kind of wrong
1026                  * if you have 2 or more vfilters and the 2nd breaks,
1027                  * on the next loop the 1st one will be applied again */
1028
1029                 /* if p_old and p_picture are the same (ie the filter
1030                  * worked on the old picture), then following code is
1031                  * still alright since i_status gets changed back to
1032                  * the right value */
1033                 if( p_old->i_refcount )
1034                 {
1035                     p_old->i_status = DISPLAYED_PICTURE;
1036                 }
1037                 else
1038                 {
1039                     p_old->i_status = DESTROYED_PICTURE;
1040                 }
1041                 p_picture->i_status = READY_PICTURE;
1042             }
1043         }
1044
1045         if( p_picture && p_vout->b_snapshot )
1046         {
1047             p_vout->b_snapshot = VLC_FALSE;
1048             vout_Snapshot( p_vout, p_picture );
1049         }
1050
1051         /*
1052          * Check for subpictures to display
1053          */
1054         if( display_date > 0 )
1055         {
1056             if( !p_input )
1057             {
1058                 p_input = vlc_object_find( p_vout, VLC_OBJECT_INPUT,
1059                                            FIND_PARENT );
1060             }
1061             p_subpic = spu_SortSubpictures( p_vout->p_spu, display_date,
1062             p_input ? var_GetBool( p_input, "state" ) == PAUSE_S : VLC_FALSE );
1063         }
1064
1065         /*
1066          * Perform rendering
1067          */
1068         i_displayed++;
1069         p_directbuffer = vout_RenderPicture( p_vout, p_picture, p_subpic );
1070
1071         /*
1072          * Call the plugin-specific rendering method if there is one
1073          */
1074         if( p_picture != NULL && p_directbuffer != NULL && p_vout->pf_render )
1075         {
1076             /* Render the direct buffer returned by vout_RenderPicture */
1077             p_vout->pf_render( p_vout, p_directbuffer );
1078         }
1079
1080         /*
1081          * Sleep, wake up
1082          */
1083         if( display_date != 0 && p_directbuffer != NULL )
1084         {
1085             mtime_t current_render_time = mdate() - current_date;
1086             /* if render time is very large we don't include it in the mean */
1087             if( current_render_time < p_vout->render_time +
1088                 VOUT_DISPLAY_DELAY )
1089             {
1090                 /* Store render time using a sliding mean weighting to
1091                  * current value in a 3 to 1 ratio*/
1092                 p_vout->render_time *= 3;
1093                 p_vout->render_time += current_render_time;
1094                 p_vout->render_time >>= 2;
1095             }
1096         }
1097
1098         /* Give back change lock */
1099         vlc_mutex_unlock( &p_vout->change_lock );
1100
1101         /* Sleep a while or until a given date */
1102         if( display_date != 0 )
1103         {
1104             /* If there are filters in the chain, better give them the picture
1105              * in advance */
1106             if( !p_vout->psz_filter_chain || !*p_vout->psz_filter_chain )
1107             {
1108                 mwait( display_date - VOUT_MWAIT_TOLERANCE );
1109             }
1110         }
1111         else
1112         {
1113             msleep( VOUT_IDLE_SLEEP );
1114         }
1115
1116         /* On awakening, take back lock and send immediately picture
1117          * to display. */
1118         vlc_mutex_lock( &p_vout->change_lock );
1119
1120         /*
1121          * Display the previously rendered picture
1122          */
1123         if( p_picture != NULL && p_directbuffer != NULL )
1124         {
1125             /* Display the direct buffer returned by vout_RenderPicture */
1126             if( p_vout->pf_display )
1127             {
1128                 p_vout->pf_display( p_vout, p_directbuffer );
1129             }
1130
1131             /* Tell the vout this was the last picture and that it does not
1132              * need to be forced anymore. */
1133             p_last_picture = p_picture;
1134             p_last_picture->b_force = 0;
1135         }
1136
1137         if( p_picture != NULL )
1138         {
1139             /* Reinitialize idle loop count */
1140             i_idle_loops = 0;
1141         }
1142
1143         /*
1144          * Check events and manage thread
1145          */
1146         if( p_vout->pf_manage && p_vout->pf_manage( p_vout ) )
1147         {
1148             /* A fatal error occurred, and the thread must terminate
1149              * immediately, without displaying anything - setting b_error to 1
1150              * causes the immediate end of the main while() loop. */
1151             p_vout->b_error = 1;
1152         }
1153
1154         if( p_vout->i_changes & VOUT_SIZE_CHANGE )
1155         {
1156             /* this must only happen when the vout plugin is incapable of
1157              * rescaling the picture itself. In this case we need to destroy
1158              * the current picture buffers and recreate new ones with the right
1159              * dimensions */
1160             int i;
1161
1162             p_vout->i_changes &= ~VOUT_SIZE_CHANGE;
1163
1164             p_vout->pf_end( p_vout );
1165             for( i = 0; i < I_OUTPUTPICTURES; i++ )
1166                  p_vout->p_picture[ i ].i_status = FREE_PICTURE;
1167
1168             I_OUTPUTPICTURES = 0;
1169             if( p_vout->pf_init( p_vout ) )
1170             {
1171                 msg_Err( p_vout, "cannot resize display" );
1172                 /* FIXME: pf_end will be called again in EndThread() */
1173                 p_vout->b_error = 1;
1174             }
1175
1176             /* Need to reinitialise the chroma plugin */
1177             if( p_vout->chroma.p_module )
1178             {
1179                 if( p_vout->chroma.p_module->pf_deactivate )
1180                     p_vout->chroma.p_module->pf_deactivate( VLC_OBJECT(p_vout) );
1181                 p_vout->chroma.p_module->pf_activate( VLC_OBJECT(p_vout) );
1182             }
1183         }
1184
1185         if( p_vout->i_changes & VOUT_PICTURE_BUFFERS_CHANGE )
1186         {
1187             /* This happens when the picture buffers need to be recreated.
1188              * This is useful on multimonitor displays for instance.
1189              *
1190              * Warning: This only works when the vout creates only 1 picture
1191              * buffer!! */
1192             p_vout->i_changes &= ~VOUT_PICTURE_BUFFERS_CHANGE;
1193
1194             if( !p_vout->b_direct )
1195             {
1196                 module_Unneed( p_vout, p_vout->chroma.p_module );
1197             }
1198
1199             vlc_mutex_lock( &p_vout->picture_lock );
1200
1201             p_vout->pf_end( p_vout );
1202
1203             I_OUTPUTPICTURES = I_RENDERPICTURES = 0;
1204
1205             p_vout->b_error = InitThread( p_vout );
1206
1207             vlc_mutex_unlock( &p_vout->picture_lock );
1208         }
1209     }
1210
1211     if( p_input )
1212     {
1213         vlc_object_release( p_input );
1214     }
1215
1216     /*
1217      * Error loop - wait until the thread destruction is requested
1218      */
1219     if( p_vout->b_error )
1220     {
1221         ErrorThread( p_vout );
1222     }
1223
1224     /* End of thread */
1225     EndThread( p_vout );
1226
1227     /* Destroy thread structures allocated by CreateThread */
1228     DestroyThread( p_vout );
1229 }
1230
1231 /*****************************************************************************
1232  * ErrorThread: RunThread() error loop
1233  *****************************************************************************
1234  * This function is called when an error occurred during thread main's loop.
1235  * The thread can still receive feed, but must be ready to terminate as soon
1236  * as possible.
1237  *****************************************************************************/
1238 static void ErrorThread( vout_thread_t *p_vout )
1239 {
1240     /* Wait until a `die' order */
1241     while( !p_vout->b_die )
1242     {
1243         /* Sleep a while */
1244         msleep( VOUT_IDLE_SLEEP );
1245     }
1246 }
1247
1248 /*****************************************************************************
1249  * EndThread: thread destruction
1250  *****************************************************************************
1251  * This function is called when the thread ends after a sucessful
1252  * initialization. It frees all resources allocated by InitThread.
1253  *****************************************************************************/
1254 static void EndThread( vout_thread_t *p_vout )
1255 {
1256     int     i_index;                                        /* index in heap */
1257
1258 #ifdef STATS
1259     {
1260         struct tms cpu_usage;
1261         times( &cpu_usage );
1262
1263         msg_Dbg( p_vout, "cpu usage (user: %d, system: %d)",
1264                  cpu_usage.tms_utime, cpu_usage.tms_stime );
1265     }
1266 #endif
1267
1268     if( !p_vout->b_direct )
1269     {
1270         module_Unneed( p_vout, p_vout->chroma.p_module );
1271     }
1272
1273     /* Destroy all remaining pictures */
1274     for( i_index = 0; i_index < 2 * VOUT_MAX_PICTURES + 1; i_index++ )
1275     {
1276         if ( p_vout->p_picture[i_index].i_type == MEMORY_PICTURE )
1277         {
1278             free( p_vout->p_picture[i_index].p_data_orig );
1279         }
1280     }
1281
1282     /* Destroy subpicture unit */
1283     spu_Attach( p_vout->p_spu, VLC_OBJECT(p_vout), VLC_FALSE );
1284     spu_Destroy( p_vout->p_spu );
1285
1286     /* Destroy the video filters2 */
1287     RemoveVideoFilters2( p_vout );
1288
1289     /* Destroy translation tables */
1290     p_vout->pf_end( p_vout );
1291
1292     /* Release the change lock */
1293     vlc_mutex_unlock( &p_vout->change_lock );
1294 }
1295
1296 /*****************************************************************************
1297  * DestroyThread: thread destruction
1298  *****************************************************************************
1299  * This function is called when the thread ends. It frees all ressources
1300  * allocated by CreateThread. Status is available at this stage.
1301  *****************************************************************************/
1302 static void DestroyThread( vout_thread_t *p_vout )
1303 {
1304     /* Destroy the locks */
1305     vlc_mutex_destroy( &p_vout->picture_lock );
1306     vlc_mutex_destroy( &p_vout->change_lock );
1307
1308     /* Release the module */
1309     if( p_vout && p_vout->p_module )
1310     {
1311         module_Unneed( p_vout, p_vout->p_module );
1312     }
1313 }
1314
1315 /* following functions are local */
1316
1317 static int ReduceHeight( int i_ratio )
1318 {
1319     int i_dummy = VOUT_ASPECT_FACTOR;
1320     int i_pgcd  = 1;
1321
1322     if( !i_ratio )
1323     {
1324         return i_pgcd;
1325     }
1326
1327     /* VOUT_ASPECT_FACTOR is (2^7 * 3^3 * 5^3), we just check for 2, 3 and 5 */
1328     while( !(i_ratio & 1) && !(i_dummy & 1) )
1329     {
1330         i_ratio >>= 1;
1331         i_dummy >>= 1;
1332         i_pgcd  <<= 1;
1333     }
1334
1335     while( !(i_ratio % 3) && !(i_dummy % 3) )
1336     {
1337         i_ratio /= 3;
1338         i_dummy /= 3;
1339         i_pgcd  *= 3;
1340     }
1341
1342     while( !(i_ratio % 5) && !(i_dummy % 5) )
1343     {
1344         i_ratio /= 5;
1345         i_dummy /= 5;
1346         i_pgcd  *= 5;
1347     }
1348
1349     return i_pgcd;
1350 }
1351
1352 static void AspectRatio( int i_aspect, int *i_aspect_x, int *i_aspect_y )
1353 {
1354     unsigned int i_pgcd = ReduceHeight( i_aspect );
1355     *i_aspect_x = i_aspect / i_pgcd;
1356     *i_aspect_y = VOUT_ASPECT_FACTOR / i_pgcd;
1357 }
1358
1359 /*****************************************************************************
1360  * BinaryLog: computes the base 2 log of a binary value
1361  *****************************************************************************
1362  * This functions is used by MaskToShift, to get a bit index from a binary
1363  * value.
1364  *****************************************************************************/
1365 static int BinaryLog( uint32_t i )
1366 {
1367     int i_log = 0;
1368
1369     if( i == 0 ) return -31337;
1370
1371     if( i & 0xffff0000 ) i_log += 16;
1372     if( i & 0xff00ff00 ) i_log += 8;
1373     if( i & 0xf0f0f0f0 ) i_log += 4;
1374     if( i & 0xcccccccc ) i_log += 2;
1375     if( i & 0xaaaaaaaa ) i_log += 1;
1376
1377     return i_log;
1378 }
1379
1380 /*****************************************************************************
1381  * MaskToShift: transform a color mask into right and left shifts
1382  *****************************************************************************
1383  * This function is used for obtaining color shifts from masks.
1384  *****************************************************************************/
1385 static void MaskToShift( int *pi_left, int *pi_right, uint32_t i_mask )
1386 {
1387     uint32_t i_low, i_high;            /* lower hand higher bits of the mask */
1388
1389     if( !i_mask )
1390     {
1391         *pi_left = *pi_right = 0;
1392         return;
1393     }
1394
1395     /* Get bits */
1396     i_low = i_high = i_mask;
1397
1398     i_low &= - (int32_t)i_low;          /* lower bit of the mask */
1399     i_high += i_low;                    /* higher bit of the mask */
1400
1401     /* Transform bits into an index. Also deal with i_high overflow, which
1402      * is faster than changing the BinaryLog code to handle 64 bit integers. */
1403     i_low =  BinaryLog (i_low);
1404     i_high = i_high ? BinaryLog (i_high) : 32;
1405
1406     /* Update pointers and return */
1407     *pi_left =   i_low;
1408     *pi_right = (8 - i_high + i_low);
1409 }
1410
1411 /*****************************************************************************
1412  * vout_VarCallback: generic callback for intf variables
1413  *****************************************************************************/
1414 int vout_VarCallback( vlc_object_t * p_this, const char * psz_variable,
1415                       vlc_value_t old_value, vlc_value_t new_value,
1416                       void * unused )
1417 {
1418     vout_thread_t * p_vout = (vout_thread_t *)p_this;
1419     vlc_value_t val;
1420     val.b_bool = VLC_TRUE;
1421     var_Set( p_vout, "intf-change", val );
1422     return VLC_SUCCESS;
1423 }
1424
1425 /*****************************************************************************
1426  * Helper thread for object variables callbacks.
1427  * Only used to avoid deadlocks when using the video embedded mode.
1428  *****************************************************************************/
1429 typedef struct suxor_thread_t
1430 {
1431     VLC_COMMON_MEMBERS
1432     input_thread_t *p_input;
1433
1434 } suxor_thread_t;
1435
1436 static void SuxorRestartVideoES( suxor_thread_t *p_this )
1437 {
1438     vlc_value_t val;
1439
1440     vlc_thread_ready( p_this );
1441
1442     /* Now restart current video stream */
1443     var_Get( p_this->p_input, "video-es", &val );
1444     if( val.i_int >= 0 )
1445     {
1446         vlc_value_t val_es;
1447         val_es.i_int = -VIDEO_ES;
1448         var_Set( p_this->p_input, "video-es", val_es );
1449         var_Set( p_this->p_input, "video-es", val );
1450     }
1451
1452     vlc_object_release( p_this->p_input );
1453
1454 #ifdef WIN32
1455     CloseHandle( p_this->thread_id );
1456 #endif
1457
1458     vlc_object_destroy( p_this );
1459 }
1460
1461 /*****************************************************************************
1462  * object variables callbacks: a bunch of object variables are used by the
1463  * interfaces to interact with the vout.
1464  *****************************************************************************/
1465 static int DeinterlaceCallback( vlc_object_t *p_this, char const *psz_cmd,
1466                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
1467 {
1468     vout_thread_t *p_vout = (vout_thread_t *)p_this;
1469     input_thread_t *p_input;
1470     vlc_value_t val;
1471
1472     char *psz_mode = newval.psz_string;
1473     char *psz_filter, *psz_deinterlace = NULL;
1474
1475     var_Get( p_vout, "vout-filter", &val );
1476     psz_filter = val.psz_string;
1477     if( psz_filter ) psz_deinterlace = strstr( psz_filter, "deinterlace" );
1478
1479     if( !psz_mode || !*psz_mode )
1480     {
1481         if( psz_deinterlace )
1482         {
1483             char *psz_src = psz_deinterlace + sizeof("deinterlace") - 1;
1484             if( psz_src[0] == ':' ) psz_src++;
1485             memmove( psz_deinterlace, psz_src, strlen(psz_src) + 1 );
1486         }
1487     }
1488     else if( !psz_deinterlace )
1489     {
1490         psz_filter = realloc( psz_filter, strlen( psz_filter ) +
1491                               sizeof(":deinterlace") );
1492         if( psz_filter && *psz_filter ) strcat( psz_filter, ":" );
1493         strcat( psz_filter, "deinterlace" );
1494     }
1495
1496     p_input = (input_thread_t *)vlc_object_find( p_this, VLC_OBJECT_INPUT,
1497                                                  FIND_PARENT );
1498     if( !p_input ) return VLC_EGENERIC;
1499
1500     if( psz_mode && *psz_mode )
1501     {
1502         /* Modify input as well because the vout might have to be restarted */
1503         val.psz_string = psz_mode;
1504         var_Create( p_input, "deinterlace-mode", VLC_VAR_STRING );
1505         var_Set( p_input, "deinterlace-mode", val );
1506     }
1507     vlc_object_release( p_input );
1508
1509     val.b_bool = VLC_TRUE;
1510     var_Set( p_vout, "intf-change", val );
1511
1512     val.psz_string = psz_filter;
1513     var_Set( p_vout, "vout-filter", val );
1514     if( psz_filter ) free( psz_filter );
1515
1516     return VLC_SUCCESS;
1517 }
1518
1519 static int FilterCallback( vlc_object_t *p_this, char const *psz_cmd,
1520                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
1521 {
1522     vout_thread_t *p_vout = (vout_thread_t *)p_this;
1523     input_thread_t *p_input;
1524     vlc_value_t val;
1525
1526     p_input = (input_thread_t *)vlc_object_find( p_this, VLC_OBJECT_INPUT,
1527                                                  FIND_PARENT );
1528     if (!p_input)
1529     {
1530         msg_Err( p_vout, "Input not found" );
1531         return( VLC_EGENERIC );
1532     }
1533
1534     val.b_bool = VLC_TRUE;
1535     var_Set( p_vout, "intf-change", val );
1536
1537     /* Modify input as well because the vout might have to be restarted */
1538     val.psz_string = newval.psz_string;
1539     var_Create( p_input, "vout-filter", VLC_VAR_STRING );
1540
1541     var_Set( p_input, "vout-filter", val );
1542
1543     /* Now restart current video stream */
1544     var_Get( p_input, "video-es", &val );
1545     if( val.i_int >= 0 )
1546     {
1547         suxor_thread_t *p_suxor =
1548             vlc_object_create( p_vout, sizeof(suxor_thread_t) );
1549         p_suxor->p_input = p_input;
1550         p_vout->b_filter_change = VLC_TRUE;
1551         vlc_object_yield( p_input );
1552         vlc_thread_create( p_suxor, "suxor", SuxorRestartVideoES,
1553                            VLC_THREAD_PRIORITY_LOW, VLC_FALSE );
1554     }
1555
1556     vlc_object_release( p_input );
1557
1558     return VLC_SUCCESS;
1559 }
1560
1561 /*****************************************************************************
1562  * Video Filter2 stuff
1563  *****************************************************************************/
1564 static int ParseVideoFilter2Chain( vout_thread_t *p_vout, char *psz_vfilters )
1565 {
1566     int i;
1567     for( i = 0; i < p_vout->i_vfilters_cfg; i++ )
1568     {
1569         /* FIXME: this should be moved in a separate function */
1570         struct sout_cfg_t *p_cfg =
1571             p_vout->p_vfilters_cfg[p_vout->i_vfilters_cfg];
1572         while( p_cfg )
1573         {
1574             struct sout_cfg_t *p_next = p_cfg->p_next;
1575             free( p_cfg->psz_name );
1576             free( p_cfg->psz_value );
1577             free( p_cfg );
1578             p_cfg = p_next;
1579         }
1580         /* </FIXME> */
1581
1582         free( p_vout->psz_vfilters[p_vout->i_vfilters_cfg] );
1583     }
1584     p_vout->i_vfilters_cfg = 0;
1585     if( psz_vfilters && *psz_vfilters )
1586     {
1587         char *psz_parser = psz_vfilters;
1588
1589         while( psz_parser && *psz_parser )
1590         {
1591             psz_parser = sout_CfgCreate(
1592                             &p_vout->psz_vfilters[p_vout->i_vfilters_cfg],
1593                             &p_vout->p_vfilters_cfg[p_vout->i_vfilters_cfg],
1594                             psz_parser );
1595             msg_Dbg( p_vout, "adding vfilter: %s\n",
1596                      p_vout->psz_vfilters[p_vout->i_vfilters_cfg] );
1597             p_vout->i_vfilters_cfg++;
1598             if( psz_parser && psz_parser )
1599             {
1600                 if( p_vout->i_vfilters_cfg == MAX_VFILTERS )
1601                 {
1602                     msg_Warn( p_vout,
1603                   "maximum number of video filters reached. \"%s\" discarded",
1604                               psz_parser );
1605                     break;
1606                 }
1607             }
1608         }
1609     }
1610     return VLC_SUCCESS;
1611 }
1612
1613 static int VideoFilter2Callback( vlc_object_t *p_this, char const *psz_cmd,
1614                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
1615 {
1616     vout_thread_t *p_vout = (vout_thread_t *)p_this;
1617
1618     ParseVideoFilter2Chain( p_vout, newval.psz_string );
1619     p_vout->b_vfilter_change = VLC_TRUE;
1620
1621     return VLC_SUCCESS;
1622 }
1623
1624 static void RemoveVideoFilters2( vout_thread_t *p_vout )
1625 {
1626     int i;
1627     for( i = 0; i < p_vout->i_vfilters; i++ )
1628     {
1629         vlc_object_detach( p_vout->pp_vfilters[i] );
1630         if( p_vout->pp_vfilters[i]->p_module )
1631         {
1632             module_Unneed( p_vout->pp_vfilters[i],
1633                            p_vout->pp_vfilters[i]->p_module );
1634         }
1635
1636         free( p_vout->pp_vfilters[i]->p_owner );
1637         vlc_object_destroy( p_vout->pp_vfilters[i] );
1638     }
1639     p_vout->i_vfilters = 0;
1640 }