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