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