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