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