]> git.sesse.net Git - vlc/blob - src/video_output/video_output.c
video_output.c: should fix playback of file with multiple video track,
[vlc] / src / video_output / video_output.c
1 /*****************************************************************************
2  * video_output.c : video output thread
3  * This module describes the programming interface for video output threads.
4  * It includes functions allowing to open a new thread, send pictures to a
5  * thread, and destroy a previously oppened video output thread.
6  *****************************************************************************
7  * Copyright (C) 2000-2001 VideoLAN
8  * $Id: video_output.c,v 1.228 2003/06/28 21:18:58 fenrir Exp $
9  *
10  * Authors: Vincent Seguin <seguin@via.ecp.fr>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #include <stdlib.h>                                                /* free() */
31
32 #include <vlc/vlc.h>
33
34 #ifdef HAVE_SYS_TIMES_H
35 #   include <sys/times.h>
36 #endif
37
38 #include "vlc_video.h"
39 #include "video_output.h"
40 #include <vlc/input.h>                 /* for input_thread_t and i_pts_delay */
41
42 #if defined( SYS_DARWIN )
43 #include "darwin_specific.h"
44 #endif
45
46 /*****************************************************************************
47  * Local prototypes
48  *****************************************************************************/
49 static int      InitThread        ( vout_thread_t * );
50 static void     RunThread         ( vout_thread_t * );
51 static void     ErrorThread       ( vout_thread_t * );
52 static void     EndThread         ( vout_thread_t * );
53 static void     DestroyThread     ( vout_thread_t * );
54
55 static int      ReduceHeight      ( int );
56 static int      BinaryLog         ( uint32_t );
57 static void     MaskToShift       ( int *, int *, uint32_t );
58 static void     InitWindowSize    ( vout_thread_t *, int *, int * );
59
60 /* Object variables callbacks */
61 static int FullscreenCallback( vlc_object_t *, char const *,
62                                vlc_value_t, vlc_value_t, void * );
63 static int DeinterlaceCallback( vlc_object_t *, char const *,
64                                 vlc_value_t, vlc_value_t, void * );
65
66 /*****************************************************************************
67  * vout_Request: find a video output thread, create one, or destroy one.
68  *****************************************************************************
69  * This function looks for a video output thread matching the current
70  * properties. If not found, it spawns a new one.
71  *****************************************************************************/
72 vout_thread_t * __vout_Request ( vlc_object_t *p_this, vout_thread_t *p_vout,
73                                  unsigned int i_width, unsigned int i_height,
74                                  vlc_fourcc_t i_chroma, unsigned int i_aspect )
75 {
76     if( !i_width || !i_height || !i_chroma )
77     {
78         /* Reattach video output to input before bailing out */
79         if( p_vout )
80         {
81             vlc_object_t *p_input;
82
83             p_input = vlc_object_find( p_this, VLC_OBJECT_INPUT, FIND_PARENT );
84
85             if( p_input )
86             {
87                 vlc_object_detach( p_vout );
88                 vlc_object_attach( p_vout, p_input );
89
90                 vlc_object_release( p_input );
91             }
92             else
93             {
94                 vlc_object_detach( p_vout );
95                 /* vlc_object_release( p_vout ); */
96                 vout_Destroy( p_vout );
97             }
98         }
99         return NULL;
100     }
101
102     /* If a video output was provided, lock it, otherwise look for one. */
103     if( p_vout )
104     {
105         vlc_object_yield( p_vout );
106     }
107     else
108     {
109         p_vout = vlc_object_find( p_this, VLC_OBJECT_VOUT, FIND_CHILD );
110
111         if( !p_vout )
112         {
113             vlc_object_t *p_input;
114
115             p_input = vlc_object_find( p_this, VLC_OBJECT_INPUT, FIND_PARENT );
116             if( p_input )
117             {
118                 p_vout = vlc_object_find( p_input, VLC_OBJECT_VOUT,
119                                           FIND_CHILD );
120                 /* only first children of p_input for unused vout */
121                 if( p_vout && p_vout->p_parent != p_input )
122                 {
123                     vlc_object_release( p_vout );
124                     p_vout = NULL;
125                 }
126                 vlc_object_release( p_input );
127             }
128         }
129     }
130
131     /* If we now have a video output, check it has the right properties */
132     if( p_vout )
133     {
134         char *psz_filter_chain;
135
136         /* We don't directly check for the "filter" variable for obvious
137          * performance reasons. */
138         if( p_vout->b_filter_change )
139         {
140             psz_filter_chain = config_GetPsz( p_this, "filter" );
141
142             if( psz_filter_chain && !*psz_filter_chain )
143             {
144                 free( psz_filter_chain );
145                 psz_filter_chain = NULL;
146             }
147             if( p_vout->psz_filter_chain && !*p_vout->psz_filter_chain )
148             {
149                 free( p_vout->psz_filter_chain );
150                 p_vout->psz_filter_chain = NULL;
151             }
152
153             if( ( !psz_filter_chain && !p_vout->psz_filter_chain ) ||
154                 ( psz_filter_chain && p_vout->psz_filter_chain &&
155                   !strcmp( psz_filter_chain, p_vout->psz_filter_chain ) ) )
156             {
157                 p_vout->b_filter_change = VLC_FALSE;
158             }
159
160             if( psz_filter_chain ) free( psz_filter_chain );
161         }
162
163         if( ( p_vout->render.i_width != i_width ) ||
164             ( p_vout->render.i_height != i_height ) ||
165             ( p_vout->render.i_chroma != i_chroma ) ||
166             ( p_vout->render.i_aspect != i_aspect
167                     && !p_vout->b_override_aspect ) ||
168             p_vout->b_filter_change )
169         {
170             /* We are not interested in this format, close this vout */
171             vlc_object_detach( p_vout );
172             vlc_object_release( p_vout );
173             vout_Destroy( p_vout );
174             p_vout = NULL;
175         }
176         else
177         {
178             /* This video output is cool! Hijack it. */
179             vlc_object_detach( p_vout );
180             vlc_object_attach( p_vout, p_this );
181             vlc_object_release( p_vout );
182         }
183     }
184
185     if( !p_vout )
186     {
187         msg_Dbg( p_this, "no usable vout present, spawning one" );
188
189         p_vout = vout_Create( p_this, i_width, i_height, i_chroma, i_aspect );
190     }
191
192     return p_vout;
193 }
194
195 /*****************************************************************************
196  * vout_Create: creates a new video output thread
197  *****************************************************************************
198  * This function creates a new video output thread, and returns a pointer
199  * to its description. On error, it returns NULL.
200  *****************************************************************************/
201 vout_thread_t * __vout_Create( vlc_object_t *p_parent,
202                                unsigned int i_width, unsigned int i_height,
203                                vlc_fourcc_t i_chroma, unsigned int i_aspect )
204 {
205     vout_thread_t  * p_vout;                            /* thread descriptor */
206     input_thread_t * p_input_thread;
207     int              i_index;                               /* loop variable */
208     char           * psz_plugin;
209     vlc_value_t      val, text;
210
211     /* Allocate descriptor */
212     p_vout = vlc_object_create( p_parent, VLC_OBJECT_VOUT );
213     if( p_vout == NULL )
214     {
215         msg_Err( p_parent, "out of memory" );
216         return NULL;
217     }
218
219     var_Create( p_vout, "intf-change", VLC_VAR_BOOL );
220     val.b_bool = VLC_TRUE;
221     var_Set( p_vout, "intf-change", val );
222
223     p_vout->b_override_aspect = VLC_FALSE;
224
225     /* If the parent is not a VOUT object, that means we are at the start of
226      * the video output pipe */
227     if( p_parent->i_object_type != VLC_OBJECT_VOUT )
228     {
229         char *psz_aspect = config_GetPsz( p_parent, "aspect-ratio" );
230
231         /* Check whether the user tried to override aspect ratio */
232         if( psz_aspect )
233         {
234             unsigned int i_new_aspect = i_aspect;
235             char *psz_parser = strchr( psz_aspect, ':' );
236
237             if( psz_parser )
238             {
239                 *psz_parser++ = '\0';
240                 i_new_aspect = atoi( psz_aspect ) * VOUT_ASPECT_FACTOR
241                                                   / atoi( psz_parser );
242             }
243             else
244             {
245                 i_new_aspect = i_width * VOUT_ASPECT_FACTOR
246                                        * atof( psz_aspect )
247                                        / i_height;
248             }
249
250             free( psz_aspect );
251
252             if( i_new_aspect && i_new_aspect != i_aspect )
253             {
254                 int i_pgcd = ReduceHeight( i_new_aspect );
255
256                 msg_Dbg( p_vout, "overriding source aspect ratio to %i:%i",
257                          i_new_aspect / i_pgcd, VOUT_ASPECT_FACTOR / i_pgcd );
258
259                 i_aspect = i_new_aspect;
260
261                 p_vout->b_override_aspect = VLC_TRUE;
262             }
263         }
264
265         /* Look for the default filter configuration */
266         p_vout->psz_filter_chain = config_GetPsz( p_parent, "filter" );
267     }
268     else
269     {
270         /* continue the parent's filter chain */
271         char *psz_end;
272
273         psz_end = strchr( ((vout_thread_t *)p_parent)->psz_filter_chain, ':' );
274         if( psz_end && *(psz_end+1) )
275             p_vout->psz_filter_chain = strdup( psz_end+1 );
276         else p_vout->psz_filter_chain = NULL;
277     }
278
279     /* Choose the video output module */
280     if( !p_vout->psz_filter_chain || !*p_vout->psz_filter_chain )
281     {
282         psz_plugin = config_GetPsz( p_parent, "vout" );
283     }
284     else
285     {
286         /* the filter chain is a string list of filters separated by double
287          * colons */
288         char *psz_end;
289
290         psz_end = strchr( p_vout->psz_filter_chain, ':' );
291         if( psz_end )
292             psz_plugin = strndup( p_vout->psz_filter_chain,
293                                   psz_end - p_vout->psz_filter_chain );
294         else psz_plugin = strdup( p_vout->psz_filter_chain );
295     }
296
297     /* Initialize pictures and subpictures - translation tables and functions
298      * will be initialized later in InitThread */
299     for( i_index = 0; i_index < 2 * VOUT_MAX_PICTURES; i_index++)
300     {
301         p_vout->p_picture[i_index].pf_lock = NULL;
302         p_vout->p_picture[i_index].pf_unlock = NULL;
303         p_vout->p_picture[i_index].i_status = FREE_PICTURE;
304         p_vout->p_picture[i_index].i_type   = EMPTY_PICTURE;
305     }
306
307     for( i_index = 0; i_index < VOUT_MAX_SUBPICTURES; i_index++)
308     {
309         p_vout->p_subpicture[i_index].i_status = FREE_SUBPICTURE;
310         p_vout->p_subpicture[i_index].i_type   = EMPTY_SUBPICTURE;
311     }
312
313     /* No images in the heap */
314     p_vout->i_heap_size = 0;
315
316     /* Initialize the rendering heap */
317     I_RENDERPICTURES = 0;
318     p_vout->render.i_width    = i_width;
319     p_vout->render.i_height   = i_height;
320     p_vout->render.i_chroma   = i_chroma;
321     p_vout->render.i_aspect   = i_aspect;
322
323     p_vout->render.i_rmask    = 0;
324     p_vout->render.i_gmask    = 0;
325     p_vout->render.i_bmask    = 0;
326
327     p_vout->render.i_last_used_pic = -1;
328     p_vout->render.b_allow_modify_pics = 1;
329
330     /* Zero the output heap */
331     I_OUTPUTPICTURES = 0;
332     p_vout->output.i_width    = 0;
333     p_vout->output.i_height   = 0;
334     p_vout->output.i_chroma   = 0;
335     p_vout->output.i_aspect   = 0;
336
337     p_vout->output.i_rmask    = 0;
338     p_vout->output.i_gmask    = 0;
339     p_vout->output.i_bmask    = 0;
340
341     /* Initialize misc stuff */
342     p_vout->i_changes    = 0;
343     p_vout->f_gamma      = 0;
344     p_vout->b_grayscale  = 0;
345     p_vout->b_info       = 0;
346     p_vout->b_interface  = 0;
347     p_vout->b_scale      = 1;
348     p_vout->b_fullscreen = 0;
349     p_vout->render_time  = 10;
350     p_vout->c_fps_samples = 0;
351     p_vout->b_filter_change = 0;
352
353     /* Mouse coordinates */
354     var_Create( p_vout, "mouse-x", VLC_VAR_INTEGER );
355     var_Create( p_vout, "mouse-y", VLC_VAR_INTEGER );
356     var_Create( p_vout, "mouse-button-down", VLC_VAR_INTEGER );
357     var_Create( p_vout, "mouse-moved", VLC_VAR_BOOL );
358     var_Create( p_vout, "mouse-clicked", VLC_VAR_INTEGER );
359     var_Create( p_vout, "key-pressed", VLC_VAR_STRING );
360
361     /* Initialize the dimensions of the video window */
362     InitWindowSize( p_vout, &p_vout->i_window_width,
363                     &p_vout->i_window_height );
364
365     /* Create thread and set locks */
366     vlc_mutex_init( p_vout, &p_vout->picture_lock );
367     vlc_mutex_init( p_vout, &p_vout->subpicture_lock );
368     vlc_mutex_init( p_vout, &p_vout->change_lock );
369
370     vlc_object_attach( p_vout, p_parent );
371
372     p_vout->p_module = module_Need( p_vout,
373                            ( p_vout->psz_filter_chain &&
374                                *p_vout->psz_filter_chain ) ?
375                            "video filter" : "video output",
376                            psz_plugin );
377
378     if( psz_plugin ) free( psz_plugin );
379     if( p_vout->p_module == NULL )
380     {
381         msg_Err( p_vout, "no suitable vout module" );
382         vlc_object_destroy( p_vout );
383         return NULL;
384     }
385
386     /* Create a few object variables for interface interaction */
387     var_Create( p_vout, "fullscreen", VLC_VAR_BOOL );
388     text.psz_string = _("Fullscreen");
389     var_Change( p_vout, "fullscreen", VLC_VAR_SETTEXT, &text, NULL );
390     var_Change( p_vout, "fullscreen", VLC_VAR_INHERITVALUE, &val, NULL );
391     if( val.b_bool )
392     {
393         /* user requested fullscreen */
394         p_vout->i_changes |= VOUT_FULLSCREEN_CHANGE;
395     }
396     var_AddCallback( p_vout, "fullscreen", FullscreenCallback, NULL );
397
398     var_Create( p_vout, "deinterlace", VLC_VAR_STRING | VLC_VAR_HASCHOICE );
399     text.psz_string = _("Deinterlace");
400     var_Change( p_vout, "deinterlace", VLC_VAR_SETTEXT, &text, NULL );
401     val.psz_string = ""; text.psz_string = _("Disable");
402     var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
403     val.psz_string = "discard"; text.psz_string = _("Discard");
404     var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
405     val.psz_string = "blend"; text.psz_string = _("Blend");
406     var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
407     val.psz_string = "mean"; text.psz_string = _("Mean");
408     var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
409     val.psz_string = "bob"; text.psz_string = _("Bob");
410     var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
411     val.psz_string = "linear"; text.psz_string = _("Linear");
412     var_Change( p_vout, "deinterlace", VLC_VAR_ADDCHOICE, &val, &text );
413     if( var_Get( p_vout, "deinterlace-mode", &val ) == VLC_SUCCESS )
414     {
415         var_Set( p_vout, "deinterlace", val );
416     }
417     var_AddCallback( p_vout, "deinterlace", DeinterlaceCallback, NULL );
418
419     /* Calculate delay created by internal caching */
420     p_input_thread = (input_thread_t *)vlc_object_find( p_vout,
421                                            VLC_OBJECT_INPUT, FIND_ANYWHERE );
422     if( p_input_thread )
423     {
424         p_vout->i_pts_delay = p_input_thread->i_pts_delay;
425         vlc_object_release( p_input_thread );
426     }
427     else
428     {
429         p_vout->i_pts_delay = DEFAULT_PTS_DELAY;
430     }
431
432     if( vlc_thread_create( p_vout, "video output", RunThread,
433                            VLC_THREAD_PRIORITY_OUTPUT, VLC_TRUE ) )
434     {
435         msg_Err( p_vout, "out of memory" );
436         module_Unneed( p_vout, p_vout->p_module );
437         vlc_object_destroy( p_vout );
438         return NULL;
439     }
440
441     return p_vout;
442 }
443
444 /*****************************************************************************
445  * vout_Destroy: destroys a previously created video output
446  *****************************************************************************
447  * Destroy a terminated thread.
448  * The function will request a destruction of the specified thread. If pi_error
449  * is NULL, it will return once the thread is destroyed. Else, it will be
450  * update using one of the THREAD_* constants.
451  *****************************************************************************/
452 void vout_Destroy( vout_thread_t *p_vout )
453
454     vlc_object_t *p_playlist;
455     
456     /* Request thread destruction */
457     p_vout->b_die = VLC_TRUE;
458     vlc_thread_join( p_vout );
459
460     var_Destroy( p_vout, "intf-change" );
461
462     p_playlist = vlc_object_find( p_vout, VLC_OBJECT_PLAYLIST, 
463                                   FIND_ANYWHERE );
464
465     /* Free structure */
466     vlc_object_destroy( p_vout );
467
468     /* If it was the last vout, tell the interface to show up */
469     if( p_playlist != NULL )
470     {
471         vout_thread_t *p_another_vout = vlc_object_find( p_playlist, 
472                                             VLC_OBJECT_VOUT, FIND_ANYWHERE );
473         if( p_another_vout == NULL )
474         {
475             vlc_value_t val;
476             val.b_bool = VLC_TRUE;
477             var_Set( p_playlist, "intf-show", val );
478         }
479         else
480         {
481             vlc_object_release( p_another_vout );
482         }
483         vlc_object_release( p_playlist );
484     }
485 }
486
487 /*****************************************************************************
488  * InitThread: initialize video output thread
489  *****************************************************************************
490  * This function is called from RunThread and performs the second step of the
491  * initialization. It returns 0 on success. Note that the thread's flag are not
492  * modified inside this function.
493  *****************************************************************************/
494 static int InitThread( vout_thread_t *p_vout )
495 {
496     int i, i_pgcd;
497
498     vlc_mutex_lock( &p_vout->change_lock );
499
500 #ifdef STATS
501     p_vout->c_loops = 0;
502 #endif
503
504     /* Initialize output method, it allocates direct buffers for us */
505     if( p_vout->pf_init( p_vout ) )
506     {
507         vlc_mutex_unlock( &p_vout->change_lock );
508         return VLC_EGENERIC;
509     }
510
511     if( !I_OUTPUTPICTURES )
512     {
513         msg_Err( p_vout, "plugin was unable to allocate at least "
514                          "one direct buffer" );
515         p_vout->pf_end( p_vout );
516         vlc_mutex_unlock( &p_vout->change_lock );
517         return VLC_EGENERIC;
518     }
519
520     if( I_OUTPUTPICTURES > VOUT_MAX_PICTURES )
521     {
522         msg_Err( p_vout, "plugin allocated too many direct buffers, "
523                          "our internal buffers must have overflown." );
524         p_vout->pf_end( p_vout );
525         vlc_mutex_unlock( &p_vout->change_lock );
526         return VLC_EGENERIC;
527     }
528
529     msg_Dbg( p_vout, "got %i direct buffer(s)", I_OUTPUTPICTURES );
530
531 #if 0
532     if( !p_vout->psz_filter_chain )
533     {
534         char *psz_aspect = config_GetPsz( p_vout, "pixel-ratio" );
535
536         if( psz_aspect )
537         {
538             int i_new_aspect = p_vout->output.i_width * VOUT_ASPECT_FACTOR
539                                                       * atof( psz_aspect )
540                                                       / p_vout->output.i_height;
541             free( psz_aspect );
542
543             if( i_new_aspect && i_new_aspect != p_vout->output.i_aspect )
544             {
545                 int i_pgcd = ReduceHeight( i_new_aspect );
546                 msg_Dbg( p_vout, "output ratio forced to %i:%i\n",
547                          i_new_aspect / i_pgcd, VOUT_ASPECT_FACTOR / i_pgcd );
548                 p_vout->output.i_aspect = i_new_aspect;
549             }
550         }
551     }
552 #endif
553
554     i_pgcd = ReduceHeight( p_vout->render.i_aspect );
555     msg_Dbg( p_vout,
556              "picture in %ix%i, chroma 0x%.8x (%4.4s), aspect ratio %i:%i",
557              p_vout->render.i_width, p_vout->render.i_height,
558              p_vout->render.i_chroma, (char*)&p_vout->render.i_chroma,
559              p_vout->render.i_aspect / i_pgcd, VOUT_ASPECT_FACTOR / i_pgcd );
560
561     i_pgcd = ReduceHeight( p_vout->output.i_aspect );
562     msg_Dbg( p_vout,
563              "picture out %ix%i, chroma 0x%.8x (%4.4s), aspect ratio %i:%i",
564              p_vout->output.i_width, p_vout->output.i_height,
565              p_vout->output.i_chroma, (char*)&p_vout->output.i_chroma,
566              p_vout->output.i_aspect / i_pgcd, VOUT_ASPECT_FACTOR / i_pgcd );
567
568     /* Calculate shifts from system-updated masks */
569     MaskToShift( &p_vout->output.i_lrshift, &p_vout->output.i_rrshift,
570                  p_vout->output.i_rmask );
571     MaskToShift( &p_vout->output.i_lgshift, &p_vout->output.i_rgshift,
572                  p_vout->output.i_gmask );
573     MaskToShift( &p_vout->output.i_lbshift, &p_vout->output.i_rbshift,
574                  p_vout->output.i_bmask );
575
576     /* Check whether we managed to create direct buffers similar to
577      * the render buffers, ie same size and chroma */
578     if( ( p_vout->output.i_width == p_vout->render.i_width )
579      && ( p_vout->output.i_height == p_vout->render.i_height )
580      && ( vout_ChromaCmp( p_vout->output.i_chroma, p_vout->render.i_chroma ) ) )
581     {
582         /* Cool ! We have direct buffers, we can ask the decoder to
583          * directly decode into them ! Map the first render buffers to
584          * the first direct buffers, but keep the first direct buffer
585          * for memcpy operations */
586         p_vout->b_direct = 1;
587
588         for( i = 1; i < VOUT_MAX_PICTURES; i++ )
589         {
590             if( p_vout->p_picture[ i ].i_type != DIRECT_PICTURE &&
591                 I_RENDERPICTURES >= VOUT_MIN_DIRECT_PICTURES - 1 &&
592                 p_vout->p_picture[ i - 1 ].i_type == DIRECT_PICTURE )
593             {
594                 /* We have enough direct buffers so there's no need to
595                  * try to use system memory buffers. */
596                 break;
597             }
598             PP_RENDERPICTURE[ I_RENDERPICTURES ] = &p_vout->p_picture[ i ];
599             I_RENDERPICTURES++;
600         }
601
602         msg_Dbg( p_vout, "direct render, mapping "
603                  "render pictures 0-%i to system pictures 1-%i",
604                  VOUT_MAX_PICTURES - 2, VOUT_MAX_PICTURES - 1 );
605     }
606     else
607     {
608         /* Rats... Something is wrong here, we could not find an output
609          * plugin able to directly render what we decode. See if we can
610          * find a chroma plugin to do the conversion */
611         p_vout->b_direct = 0;
612
613         /* Choose the best module */
614         p_vout->chroma.p_module = module_Need( p_vout, "chroma", NULL );
615
616         if( p_vout->chroma.p_module == NULL )
617         {
618             msg_Err( p_vout, "no chroma module for %4.4s to %4.4s",
619                      (char*)&p_vout->render.i_chroma,
620                      (char*)&p_vout->output.i_chroma );
621             p_vout->pf_end( p_vout );
622             vlc_mutex_unlock( &p_vout->change_lock );
623             return VLC_EGENERIC;
624         }
625
626         msg_Dbg( p_vout, "indirect render, mapping "
627                  "render pictures 0-%i to system pictures %i-%i",
628                  VOUT_MAX_PICTURES - 1, I_OUTPUTPICTURES,
629                  I_OUTPUTPICTURES + VOUT_MAX_PICTURES - 1 );
630
631         /* Append render buffers after the direct buffers */
632         for( i = I_OUTPUTPICTURES; i < 2 * VOUT_MAX_PICTURES; i++ )
633         {
634             PP_RENDERPICTURE[ I_RENDERPICTURES ] = &p_vout->p_picture[ i ];
635             I_RENDERPICTURES++;
636
637             /* Check if we have enough render pictures */
638             if( I_RENDERPICTURES == VOUT_MAX_PICTURES )
639                 break;
640         }
641     }
642
643     /* Link pictures back to their heap */
644     for( i = 0 ; i < I_RENDERPICTURES ; i++ )
645     {
646         PP_RENDERPICTURE[ i ]->p_heap = &p_vout->render;
647     }
648
649     for( i = 0 ; i < I_OUTPUTPICTURES ; i++ )
650     {
651         PP_OUTPUTPICTURE[ i ]->p_heap = &p_vout->output;
652     }
653
654 /* XXX XXX mark thread ready */
655     return VLC_SUCCESS;
656 }
657
658 /*****************************************************************************
659  * RunThread: video output thread
660  *****************************************************************************
661  * Video output thread. This function does only returns when the thread is
662  * terminated. It handles the pictures arriving in the video heap and the
663  * display device events.
664  *****************************************************************************/
665 static void RunThread( vout_thread_t *p_vout)
666 {
667     int             i_index;                                /* index in heap */
668     int             i_idle_loops = 0;  /* loops without displaying a picture */
669     mtime_t         current_date;                            /* current date */
670     mtime_t         display_date;                            /* display date */
671
672     picture_t *     p_picture;                            /* picture pointer */
673     picture_t *     p_last_picture = NULL;                   /* last picture */
674     picture_t *     p_directbuffer;              /* direct buffer to display */
675
676     subpicture_t *  p_subpic;                          /* subpicture pointer */
677
678     /*
679      * Initialize thread
680      */
681     p_vout->b_error = InitThread( p_vout );
682
683     /* signal the creation of the vout */
684     vlc_thread_ready( p_vout );
685
686     if( p_vout->b_error )
687     {
688         /* Destroy thread structures allocated by Create and InitThread */
689         DestroyThread( p_vout );
690         return;
691     }
692
693     /*
694      * Main loop - it is not executed if an error occured during
695      * initialization
696      */
697     while( (!p_vout->b_die) && (!p_vout->b_error) )
698     {
699         /* Initialize loop variables */
700         p_picture = NULL;
701         display_date = 0;
702         current_date = mdate();
703
704 #if 0
705         p_vout->c_loops++;
706         if( !(p_vout->c_loops % VOUT_STATS_NB_LOOPS) )
707         {
708             msg_Dbg( p_vout, "picture heap: %d/%d",
709                      I_RENDERPICTURES, p_vout->i_heap_size );
710         }
711 #endif
712
713         /*
714          * Find the picture to display (the one with the earliest date).
715          * This operation does not need lock, since only READY_PICTUREs
716          * are handled. */
717         for( i_index = 0; i_index < I_RENDERPICTURES; i_index++ )
718         {
719             if( (PP_RENDERPICTURE[i_index]->i_status == READY_PICTURE)
720                 && ( (p_picture == NULL) ||
721                      (PP_RENDERPICTURE[i_index]->date < display_date) ) )
722             {
723                 p_picture = PP_RENDERPICTURE[i_index];
724                 display_date = p_picture->date;
725             }
726         }
727
728         if( p_picture )
729         {
730             /* If we met the last picture, parse again to see whether there is
731              * a more appropriate one. */
732             if( p_picture == p_last_picture )
733             {
734                 for( i_index = 0; i_index < I_RENDERPICTURES; i_index++ )
735                 {
736                     if( (PP_RENDERPICTURE[i_index]->i_status == READY_PICTURE)
737                         && (PP_RENDERPICTURE[i_index] != p_last_picture)
738                         && ((p_picture == p_last_picture) ||
739                             (PP_RENDERPICTURE[i_index]->date < display_date)) )
740                     {
741                         p_picture = PP_RENDERPICTURE[i_index];
742                         display_date = p_picture->date;
743                     }
744                 }
745             }
746
747             /* If we found better than the last picture, destroy it */
748             if( p_last_picture && p_picture != p_last_picture )
749             {
750                 vlc_mutex_lock( &p_vout->picture_lock );
751                 if( p_last_picture->i_refcount )
752                 {
753                     p_last_picture->i_status = DISPLAYED_PICTURE;
754                 }
755                 else
756                 {
757                     p_last_picture->i_status = DESTROYED_PICTURE;
758                     p_vout->i_heap_size--;
759                 }
760                 vlc_mutex_unlock( &p_vout->picture_lock );
761                 p_last_picture = NULL;
762             }
763
764             /* Compute FPS rate */
765             p_vout->p_fps_sample[ p_vout->c_fps_samples++ % VOUT_FPS_SAMPLES ]
766                 = display_date;
767
768             if( !p_picture->b_force &&
769                 p_picture != p_last_picture &&
770                 display_date < current_date + p_vout->render_time )
771             {
772                 /* Picture is late: it will be destroyed and the thread
773                  * will directly choose the next picture */
774                 vlc_mutex_lock( &p_vout->picture_lock );
775                 if( p_picture->i_refcount )
776                 {
777                     /* Pretend we displayed the picture, but don't destroy
778                      * it since the decoder might still need it. */
779                     p_picture->i_status = DISPLAYED_PICTURE;
780                 }
781                 else
782                 {
783                     /* Destroy the picture without displaying it */
784                     p_picture->i_status = DESTROYED_PICTURE;
785                     p_vout->i_heap_size--;
786                 }
787                 msg_Warn( p_vout, "late picture skipped ("I64Fd")",
788                                   current_date - display_date );
789                 vlc_mutex_unlock( &p_vout->picture_lock );
790
791                 continue;
792             }
793
794             if( display_date >
795                 current_date + p_vout->i_pts_delay +  VOUT_BOGUS_DELAY )
796             {
797                 /* Picture is waaay too early: it will be destroyed */
798                 vlc_mutex_lock( &p_vout->picture_lock );
799                 if( p_picture->i_refcount )
800                 {
801                     /* Pretend we displayed the picture, but don't destroy
802                      * it since the decoder might still need it. */
803                     p_picture->i_status = DISPLAYED_PICTURE;
804                 }
805                 else
806                 {
807                     /* Destroy the picture without displaying it */
808                     p_picture->i_status = DESTROYED_PICTURE;
809                     p_vout->i_heap_size--;
810                 }
811                 msg_Warn( p_vout, "vout warning: early picture skipped "
812                           "("I64Fd")", display_date - current_date
813                           - p_vout->i_pts_delay );
814                 vlc_mutex_unlock( &p_vout->picture_lock );
815
816                 continue;
817             }
818
819             if( display_date > current_date + VOUT_DISPLAY_DELAY )
820             {
821                 /* A picture is ready to be rendered, but its rendering date
822                  * is far from the current one so the thread will perform an
823                  * empty loop as if no picture were found. The picture state
824                  * is unchanged */
825                 p_picture    = NULL;
826                 display_date = 0;
827             }
828             else if( p_picture == p_last_picture )
829             {
830                 /* We are asked to repeat the previous picture, but we first
831                  * wait for a couple of idle loops */
832                 if( i_idle_loops < 4 )
833                 {
834                     p_picture    = NULL;
835                     display_date = 0;
836                 }
837                 else
838                 {
839                     /* We set the display date to something high, otherwise
840                      * we'll have lots of problems with late pictures */
841                     display_date = current_date + p_vout->render_time;
842                 }
843             }
844         }
845
846         if( p_picture == NULL )
847         {
848             i_idle_loops++;
849         }
850
851         /*
852          * Check for subpictures to display
853          */
854         p_subpic = vout_SortSubPictures( p_vout, display_date );
855
856         /*
857          * Perform rendering
858          */
859         p_directbuffer = vout_RenderPicture( p_vout, p_picture, p_subpic );
860
861         /*
862          * Call the plugin-specific rendering method if there is one
863          */
864         if( p_picture != NULL && p_directbuffer != NULL && p_vout->pf_render )
865         {
866             /* Render the direct buffer returned by vout_RenderPicture */
867             p_vout->pf_render( p_vout, p_directbuffer );
868         }
869
870         /*
871          * Sleep, wake up
872          */
873         if( display_date != 0 && p_directbuffer != NULL )
874         {
875             /* Store render time using a sliding mean */
876             p_vout->render_time += mdate() - current_date;
877             p_vout->render_time >>= 1;
878         }
879
880         /* Give back change lock */
881         vlc_mutex_unlock( &p_vout->change_lock );
882
883         /* Sleep a while or until a given date */
884         if( display_date != 0 )
885         {
886             mwait( display_date - VOUT_MWAIT_TOLERANCE );
887         }
888         else
889         {
890             msleep( VOUT_IDLE_SLEEP );
891         }
892
893         /* On awakening, take back lock and send immediately picture
894          * to display. */
895         vlc_mutex_lock( &p_vout->change_lock );
896
897         /*
898          * Display the previously rendered picture
899          */
900         if( p_picture != NULL && p_directbuffer != NULL )
901         {
902             /* Display the direct buffer returned by vout_RenderPicture */
903             if( p_vout->pf_display )
904             {
905                 p_vout->pf_display( p_vout, p_directbuffer );
906             }
907
908             /* Reinitialize idle loop count */
909             i_idle_loops = 0;
910
911             /* Tell the vout this was the last picture and that it does not
912              * need to be forced anymore. */
913             p_last_picture = p_picture;
914             p_last_picture->b_force = 0;
915         }
916
917         /*
918          * Check events and manage thread
919          */
920         if( p_vout->pf_manage && p_vout->pf_manage( p_vout ) )
921         {
922             /* A fatal error occured, and the thread must terminate
923              * immediately, without displaying anything - setting b_error to 1
924              * causes the immediate end of the main while() loop. */
925             p_vout->b_error = 1;
926         }
927
928         if( p_vout->i_changes & VOUT_SIZE_CHANGE )
929         {
930             /* this must only happen when the vout plugin is incapable of
931              * rescaling the picture itself. In this case we need to destroy
932              * the current picture buffers and recreate new ones with the right
933              * dimensions */
934             int i;
935
936             p_vout->i_changes &= ~VOUT_SIZE_CHANGE;
937
938             p_vout->pf_end( p_vout );
939             for( i = 0; i < I_OUTPUTPICTURES; i++ )
940                  p_vout->p_picture[ i ].i_status = FREE_PICTURE;
941
942             I_OUTPUTPICTURES = 0;
943             if( p_vout->pf_init( p_vout ) )
944             {
945                 msg_Err( p_vout, "cannot resize display" );
946                 /* FIXME: pf_end will be called again in EndThread() */
947                 p_vout->b_error = 1;
948             }
949
950             /* Need to reinitialise the chroma plugin */
951             if( p_vout->chroma.p_module->pf_deactivate )
952                 p_vout->chroma.p_module->pf_deactivate( VLC_OBJECT(p_vout) );
953             p_vout->chroma.p_module->pf_activate( VLC_OBJECT(p_vout) );
954         }
955     }
956
957     /*
958      * Error loop - wait until the thread destruction is requested
959      */
960     if( p_vout->b_error )
961     {
962         ErrorThread( p_vout );
963     }
964
965     /* End of thread */
966     EndThread( p_vout );
967
968     /* Destroy thread structures allocated by CreateThread */
969     DestroyThread( p_vout );
970 }
971
972 /*****************************************************************************
973  * ErrorThread: RunThread() error loop
974  *****************************************************************************
975  * This function is called when an error occured during thread main's loop. The
976  * thread can still receive feed, but must be ready to terminate as soon as
977  * possible.
978  *****************************************************************************/
979 static void ErrorThread( vout_thread_t *p_vout )
980 {
981     /* Wait until a `die' order */
982     while( !p_vout->b_die )
983     {
984         /* Sleep a while */
985         msleep( VOUT_IDLE_SLEEP );
986     }
987 }
988
989 /*****************************************************************************
990  * EndThread: thread destruction
991  *****************************************************************************
992  * This function is called when the thread ends after a sucessful
993  * initialization. It frees all ressources allocated by InitThread.
994  *****************************************************************************/
995 static void EndThread( vout_thread_t *p_vout )
996 {
997     int     i_index;                                        /* index in heap */
998
999 #ifdef STATS
1000     {
1001         struct tms cpu_usage;
1002         times( &cpu_usage );
1003
1004         msg_Dbg( p_vout, "cpu usage (user: %d, system: %d)",
1005                  cpu_usage.tms_utime, cpu_usage.tms_stime );
1006     }
1007 #endif
1008
1009     if( !p_vout->b_direct )
1010     {
1011         module_Unneed( p_vout, p_vout->chroma.p_module );
1012     }
1013
1014     /* Destroy all remaining pictures */
1015     for( i_index = 0; i_index < 2 * VOUT_MAX_PICTURES; i_index++ )
1016     {
1017         if ( p_vout->p_picture[i_index].i_type == MEMORY_PICTURE )
1018         {
1019             free( p_vout->p_picture[i_index].p_data_orig );
1020         }
1021     }
1022
1023     /* Destroy all remaining subpictures */
1024     for( i_index = 0; i_index < VOUT_MAX_SUBPICTURES; i_index++ )
1025     {
1026         if( p_vout->p_subpicture[i_index].i_status != FREE_SUBPICTURE )
1027         {
1028             vout_DestroySubPicture( p_vout,
1029                                     &p_vout->p_subpicture[i_index] );
1030         }
1031     }
1032
1033     /* Destroy translation tables */
1034     p_vout->pf_end( p_vout );
1035
1036     /* Release the change lock */
1037     vlc_mutex_unlock( &p_vout->change_lock );
1038 }
1039
1040 /*****************************************************************************
1041  * DestroyThread: thread destruction
1042  *****************************************************************************
1043  * This function is called when the thread ends. It frees all ressources
1044  * allocated by CreateThread. Status is available at this stage.
1045  *****************************************************************************/
1046 static void DestroyThread( vout_thread_t *p_vout )
1047 {
1048     /* Destroy the locks */
1049     vlc_mutex_destroy( &p_vout->picture_lock );
1050     vlc_mutex_destroy( &p_vout->subpicture_lock );
1051     vlc_mutex_destroy( &p_vout->change_lock );
1052
1053     /* Release the module */
1054     module_Unneed( p_vout, p_vout->p_module );
1055 }
1056
1057 /* following functions are local */
1058
1059 static int ReduceHeight( int i_ratio )
1060 {
1061     int i_dummy = VOUT_ASPECT_FACTOR;
1062     int i_pgcd  = 1;
1063  
1064     if( !i_ratio )
1065     {
1066         return i_pgcd;
1067     }
1068
1069     /* VOUT_ASPECT_FACTOR is (2^7 * 3^3 * 5^3), we just check for 2, 3 and 5 */
1070     while( !(i_ratio & 1) && !(i_dummy & 1) )
1071     {
1072         i_ratio >>= 1;
1073         i_dummy >>= 1;
1074         i_pgcd  <<= 1;
1075     }
1076
1077     while( !(i_ratio % 3) && !(i_dummy % 3) )
1078     {
1079         i_ratio /= 3;
1080         i_dummy /= 3;
1081         i_pgcd  *= 3;
1082     }
1083
1084     while( !(i_ratio % 5) && !(i_dummy % 5) )
1085     {
1086         i_ratio /= 5;
1087         i_dummy /= 5;
1088         i_pgcd  *= 5;
1089     }
1090
1091     return i_pgcd;
1092 }
1093
1094 /*****************************************************************************
1095  * BinaryLog: computes the base 2 log of a binary value
1096  *****************************************************************************
1097  * This functions is used by MaskToShift, to get a bit index from a binary
1098  * value.
1099  *****************************************************************************/
1100 static int BinaryLog( uint32_t i )
1101 {
1102     int i_log = 0;
1103
1104     if( i == 0 ) return -31337;
1105
1106     if( i & 0xffff0000 ) i_log += 16;
1107     if( i & 0xff00ff00 ) i_log += 8;
1108     if( i & 0xf0f0f0f0 ) i_log += 4;
1109     if( i & 0xcccccccc ) i_log += 2;
1110     if( i & 0xaaaaaaaa ) i_log += 1;
1111
1112     return i_log;
1113 }
1114
1115 /*****************************************************************************
1116  * MaskToShift: transform a color mask into right and left shifts
1117  *****************************************************************************
1118  * This function is used for obtaining color shifts from masks.
1119  *****************************************************************************/
1120 static void MaskToShift( int *pi_left, int *pi_right, uint32_t i_mask )
1121 {
1122     uint32_t i_low, i_high;            /* lower hand higher bits of the mask */
1123
1124     if( !i_mask )
1125     {
1126         *pi_left = *pi_right = 0;
1127         return;
1128     }
1129
1130     /* Get bits */
1131     i_low =  i_mask & (- (int32_t)i_mask);          /* lower bit of the mask */
1132     i_high = i_mask + i_low;                       /* higher bit of the mask */
1133
1134     /* Transform bits into an index */
1135     i_low =  BinaryLog (i_low);
1136     i_high = BinaryLog (i_high);
1137
1138     /* Update pointers and return */
1139     *pi_left =   i_low;
1140     *pi_right = (8 - i_high + i_low);
1141 }
1142
1143 /*****************************************************************************
1144  * InitWindowSize: find the initial dimensions the video window should have.
1145  *****************************************************************************
1146  * This function will check the "width", "height" and "zoom" config options and
1147  * will calculate the size that the video window should have.
1148  *****************************************************************************/
1149 static void InitWindowSize( vout_thread_t *p_vout, int *pi_width,
1150                             int *pi_height )
1151 {
1152     int i_width, i_height;
1153     uint64_t ll_zoom;
1154
1155 #define FP_FACTOR 1000                             /* our fixed point factor */
1156
1157     i_width = config_GetInt( p_vout, "width" );
1158     i_height = config_GetInt( p_vout, "height" );
1159     ll_zoom = (uint64_t)( FP_FACTOR * config_GetFloat( p_vout, "zoom" ) );
1160
1161     if( i_width > 0 && i_height > 0)
1162     {
1163         *pi_width = (int)( i_width * ll_zoom / FP_FACTOR );
1164         *pi_height = (int)( i_height * ll_zoom / FP_FACTOR );
1165         return;
1166     }
1167     else if( i_width > 0 )
1168     {
1169         *pi_width = (int)( i_width * ll_zoom / FP_FACTOR );
1170         *pi_height = (int)( i_width * ll_zoom * VOUT_ASPECT_FACTOR /
1171                             p_vout->render.i_aspect / FP_FACTOR );
1172         return;
1173     }
1174     else if( i_height > 0 )
1175     {
1176         *pi_height = (int)( i_height * ll_zoom / FP_FACTOR );
1177         *pi_width = (int)( i_height * ll_zoom * p_vout->render.i_aspect /
1178                            VOUT_ASPECT_FACTOR / FP_FACTOR );
1179         return;
1180     }
1181
1182     if( p_vout->render.i_height * p_vout->render.i_aspect
1183         >= p_vout->render.i_width * VOUT_ASPECT_FACTOR )
1184     {
1185         *pi_width = (int)( p_vout->render.i_height * ll_zoom
1186           * p_vout->render.i_aspect / VOUT_ASPECT_FACTOR / FP_FACTOR );
1187         *pi_height = (int)( p_vout->render.i_height * ll_zoom / FP_FACTOR );
1188     }
1189     else
1190     {
1191         *pi_width = (int)( p_vout->render.i_width * ll_zoom / FP_FACTOR );
1192         *pi_height = (int)( p_vout->render.i_width * ll_zoom
1193           * VOUT_ASPECT_FACTOR / p_vout->render.i_aspect / FP_FACTOR );
1194     }
1195
1196 #undef FP_FACTOR
1197 }
1198
1199 /*****************************************************************************
1200  * vout_VarCallback: generic callback for intf variables
1201  *****************************************************************************/
1202 int vout_VarCallback( vlc_object_t * p_this, const char * psz_variable,
1203                       vlc_value_t old_value, vlc_value_t new_value,
1204                       void * unused )
1205 {
1206     vout_thread_t * p_vout = (vout_thread_t *)p_this;
1207     vlc_value_t val;
1208     val.b_bool = VLC_TRUE;
1209     var_Set( p_vout, "intf-change", val );
1210     return VLC_SUCCESS;
1211 }
1212
1213 /*****************************************************************************
1214  * object variables callbacks: a bunch of object variables are used by the
1215  * interfaces to interact with the vout.
1216  *****************************************************************************/
1217 static int FullscreenCallback( vlc_object_t *p_this, char const *psz_cmd,
1218                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
1219 {
1220     vout_thread_t *p_vout = (vout_thread_t *)p_this;
1221     input_thread_t *p_input;
1222     vlc_value_t val;
1223
1224     p_vout->i_changes |= VOUT_FULLSCREEN_CHANGE;
1225
1226     p_input = (input_thread_t *)vlc_object_find( p_this, VLC_OBJECT_INPUT,
1227                                                  FIND_PARENT );
1228     if( p_input )
1229     {
1230         /* Modify input as well because the vout might have to be restarted */
1231         var_Create( p_input, "fullscreen", VLC_VAR_BOOL );
1232         var_Set( p_input, "fullscreen", newval );
1233
1234         vlc_object_release( p_input );
1235     }
1236
1237     val.b_bool = VLC_TRUE;
1238     var_Set( p_vout, "intf-change", val );
1239     return VLC_SUCCESS;
1240 }
1241
1242 static int DeinterlaceCallback( vlc_object_t *p_this, char const *psz_cmd,
1243                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
1244 {
1245     vout_thread_t *p_vout = (vout_thread_t *)p_this;
1246     input_thread_t *p_input;
1247     vlc_value_t val;
1248
1249     char *psz_mode = newval.psz_string;
1250     char *psz_filter;
1251     unsigned int  i;
1252
1253     psz_filter = config_GetPsz( p_vout, "filter" );
1254
1255     if( !psz_mode || !*psz_mode )
1256     {
1257         config_PutPsz( p_vout, "filter", "" );
1258     }
1259     else
1260     {
1261         if( !psz_filter || !*psz_filter )
1262         {
1263             config_PutPsz( p_vout, "filter", "deinterlace" );
1264         }
1265         else
1266         {
1267             if( strstr( psz_filter, "deinterlace" ) == NULL )
1268             {
1269                 psz_filter = realloc( psz_filter, strlen( psz_filter ) + 20 );
1270                 strcat( psz_filter, ",deinterlace" );
1271             }
1272             config_PutPsz( p_vout, "filter", psz_filter );
1273         }
1274     }
1275
1276     if( psz_filter ) free( psz_filter );
1277
1278
1279     p_input = (input_thread_t *)vlc_object_find( p_this, VLC_OBJECT_INPUT,
1280                                                  FIND_PARENT );
1281     if( !p_input ) return VLC_EGENERIC;
1282
1283     if( psz_mode && *psz_mode )
1284     {
1285         val.psz_string = psz_mode;
1286         var_Set( p_vout, "deinterlace-mode", val );
1287         /* Modify input as well because the vout might have to be restarted */
1288         var_Create( p_input, "deinterlace-mode", VLC_VAR_STRING );
1289         var_Set( p_input, "deinterlace-mode", val );
1290     }
1291
1292     /* now restart all video streams */
1293     vlc_mutex_lock( &p_input->stream.stream_lock );
1294
1295     p_vout->b_filter_change = VLC_TRUE;
1296
1297 #define ES p_input->stream.pp_es[i]
1298
1299     for( i = 0 ; i < p_input->stream.i_es_number ; i++ )
1300     {
1301         if( ( ES->i_cat == VIDEO_ES ) && ES->p_decoder_fifo != NULL )
1302         {
1303             input_UnselectES( p_input, ES );
1304             input_SelectES( p_input, ES );
1305         }
1306 #undef ES
1307     }
1308     vlc_mutex_unlock( &p_input->stream.stream_lock );
1309
1310     vlc_object_release( p_input );
1311
1312     val.b_bool = VLC_TRUE;
1313     var_Set( p_vout, "intf-change", val );
1314     return VLC_SUCCESS;
1315 }