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