* src/video_output/video_output.c: fixed my previous commit (input is not a direct...
[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.215 2003/03/25 00:43:26 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_ANYWHERE );
365     if( p_input_thread )
366     {
367         p_vout->i_pts_delay = p_input_thread->i_pts_delay;
368         vlc_object_release( p_input_thread );
369     }
370     else
371     {
372         p_vout->i_pts_delay = DEFAULT_PTS_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 >
718                 current_date + p_vout->i_pts_delay +  VOUT_BOGUS_DELAY )
719             {
720                 /* Picture is waaay too early: it will be destroyed */
721                 vlc_mutex_lock( &p_vout->picture_lock );
722                 if( p_picture->i_refcount )
723                 {
724                     /* Pretend we displayed the picture, but don't destroy
725                      * it since the decoder might still need it. */
726                     p_picture->i_status = DISPLAYED_PICTURE;
727                 }
728                 else
729                 {
730                     /* Destroy the picture without displaying it */
731                     p_picture->i_status = DESTROYED_PICTURE;
732                     p_vout->i_heap_size--;
733                 }
734                 msg_Warn( p_vout, "vout warning: early picture skipped "
735                           "("I64Fd")", display_date - current_date
736                           - p_vout->i_pts_delay );
737                 vlc_mutex_unlock( &p_vout->picture_lock );
738
739                 continue;
740             }
741
742             if( display_date > current_date + VOUT_DISPLAY_DELAY )
743             {
744                 /* A picture is ready to be rendered, but its rendering date
745                  * is far from the current one so the thread will perform an
746                  * empty loop as if no picture were found. The picture state
747                  * is unchanged */
748                 p_picture    = NULL;
749                 display_date = 0;
750             }
751             else if( p_picture == p_last_picture )
752             {
753                 /* We are asked to repeat the previous picture, but we first
754                  * wait for a couple of idle loops */
755                 if( i_idle_loops < 4 )
756                 {
757                     p_picture    = NULL;
758                     display_date = 0;
759                 }
760                 else
761                 {
762                     /* We set the display date to something high, otherwise
763                      * we'll have lots of problems with late pictures */
764                     display_date = current_date + p_vout->render_time;
765                 }
766             }
767         }
768
769         if( p_picture == NULL )
770         {
771             i_idle_loops++;
772         }
773
774         /*
775          * Check for subpictures to display
776          */
777         p_subpic = vout_SortSubPictures( p_vout, display_date );
778
779         /*
780          * Perform rendering
781          */
782         p_directbuffer = vout_RenderPicture( p_vout, p_picture, p_subpic );
783
784         /*
785          * Call the plugin-specific rendering method if there is one
786          */
787         if( p_picture != NULL && p_vout->pf_render )
788         {
789             /* Render the direct buffer returned by vout_RenderPicture */
790             p_vout->pf_render( p_vout, p_directbuffer );
791         }
792
793         /*
794          * Sleep, wake up
795          */
796         if( display_date != 0 )
797         {
798             /* Store render time using a sliding mean */
799             p_vout->render_time += mdate() - current_date;
800             p_vout->render_time >>= 1;
801         }
802
803         /* Give back change lock */
804         vlc_mutex_unlock( &p_vout->change_lock );
805
806         /* Sleep a while or until a given date */
807         if( display_date != 0 )
808         {
809             mwait( display_date - VOUT_MWAIT_TOLERANCE );
810         }
811         else
812         {
813             msleep( VOUT_IDLE_SLEEP );
814         }
815
816         /* On awakening, take back lock and send immediately picture
817          * to display. */
818         vlc_mutex_lock( &p_vout->change_lock );
819
820         /*
821          * Display the previously rendered picture
822          */
823         if( p_picture != NULL )
824         {
825             /* Display the direct buffer returned by vout_RenderPicture */
826             if( p_vout->pf_display )
827             {
828                 p_vout->pf_display( p_vout, p_directbuffer );
829             }
830
831             /* Reinitialize idle loop count */
832             i_idle_loops = 0;
833
834             /* Tell the vout this was the last picture and that it does not
835              * need to be forced anymore. */
836             p_last_picture = p_picture;
837             p_last_picture->b_force = 0;
838         }
839
840         /*
841          * Check events and manage thread
842          */
843         if( p_vout->pf_manage && p_vout->pf_manage( p_vout ) )
844         {
845             /* A fatal error occured, and the thread must terminate
846              * immediately, without displaying anything - setting b_error to 1
847              * causes the immediate end of the main while() loop. */
848             p_vout->b_error = 1;
849         }
850
851         if( p_vout->i_changes & VOUT_SIZE_CHANGE )
852         {
853             /* this must only happen when the vout plugin is incapable of
854              * rescaling the picture itself. In this case we need to destroy
855              * the current picture buffers and recreate new ones with the right
856              * dimensions */
857             int i;
858
859             p_vout->i_changes &= ~VOUT_SIZE_CHANGE;
860
861             p_vout->pf_end( p_vout );
862             for( i = 0; i < I_OUTPUTPICTURES; i++ )
863                  p_vout->p_picture[ i ].i_status = FREE_PICTURE;
864
865             I_OUTPUTPICTURES = 0;
866             if( p_vout->pf_init( p_vout ) )
867             {
868                 msg_Err( p_vout, "cannot resize display" );
869                 /* FIXME: pf_end will be called again in EndThread() */
870                 p_vout->b_error = 1;
871             }
872
873             /* Need to reinitialise the chroma plugin */
874             p_vout->chroma.p_module->pf_deactivate( VLC_OBJECT(p_vout) );
875             p_vout->chroma.p_module->pf_activate( VLC_OBJECT(p_vout) );
876         }
877     }
878
879     /*
880      * Error loop - wait until the thread destruction is requested
881      */
882     if( p_vout->b_error )
883     {
884         ErrorThread( p_vout );
885     }
886
887     /* End of thread */
888     EndThread( p_vout );
889
890     /* Destroy thread structures allocated by CreateThread */
891     DestroyThread( p_vout );
892 }
893
894 /*****************************************************************************
895  * ErrorThread: RunThread() error loop
896  *****************************************************************************
897  * This function is called when an error occured during thread main's loop. The
898  * thread can still receive feed, but must be ready to terminate as soon as
899  * possible.
900  *****************************************************************************/
901 static void ErrorThread( vout_thread_t *p_vout )
902 {
903     /* Wait until a `die' order */
904     while( !p_vout->b_die )
905     {
906         /* Sleep a while */
907         msleep( VOUT_IDLE_SLEEP );
908     }
909 }
910
911 /*****************************************************************************
912  * EndThread: thread destruction
913  *****************************************************************************
914  * This function is called when the thread ends after a sucessful
915  * initialization. It frees all ressources allocated by InitThread.
916  *****************************************************************************/
917 static void EndThread( vout_thread_t *p_vout )
918 {
919     int     i_index;                                        /* index in heap */
920
921 #ifdef STATS
922     {
923         struct tms cpu_usage;
924         times( &cpu_usage );
925
926         msg_Dbg( p_vout, "cpu usage (user: %d, system: %d)",
927                  cpu_usage.tms_utime, cpu_usage.tms_stime );
928     }
929 #endif
930
931     if( !p_vout->b_direct )
932     {
933         module_Unneed( p_vout, p_vout->chroma.p_module );
934     }
935
936     /* Destroy all remaining pictures */
937     for( i_index = 0; i_index < 2 * VOUT_MAX_PICTURES; i_index++ )
938     {
939         if ( p_vout->p_picture[i_index].i_type == MEMORY_PICTURE )
940         {
941             free( p_vout->p_picture[i_index].p_data_orig );
942         }
943     }
944
945     /* Destroy all remaining subpictures */
946     for( i_index = 0; i_index < VOUT_MAX_SUBPICTURES; i_index++ )
947     {
948         if( p_vout->p_subpicture[i_index].i_status != FREE_SUBPICTURE )
949         {
950             vout_DestroySubPicture( p_vout,
951                                     &p_vout->p_subpicture[i_index] );
952         }
953     }
954
955     /* Destroy translation tables */
956     p_vout->pf_end( p_vout );
957
958     /* Release the change lock */
959     vlc_mutex_unlock( &p_vout->change_lock );
960 }
961
962 /*****************************************************************************
963  * DestroyThread: thread destruction
964  *****************************************************************************
965  * This function is called when the thread ends. It frees all ressources
966  * allocated by CreateThread. Status is available at this stage.
967  *****************************************************************************/
968 static void DestroyThread( vout_thread_t *p_vout )
969 {
970     /* Destroy the locks */
971     vlc_mutex_destroy( &p_vout->picture_lock );
972     vlc_mutex_destroy( &p_vout->subpicture_lock );
973     vlc_mutex_destroy( &p_vout->change_lock );
974
975     /* Release the module */
976     module_Unneed( p_vout, p_vout->p_module );
977 }
978
979 /* following functions are local */
980
981 static int ReduceHeight( int i_ratio )
982 {
983     int i_dummy = VOUT_ASPECT_FACTOR;
984     int i_pgcd  = 1;
985  
986     if( !i_ratio )
987     {
988         return i_pgcd;
989     }
990
991     /* VOUT_ASPECT_FACTOR is (2^7 * 3^3 * 5^3), we just check for 2, 3 and 5 */
992     while( !(i_ratio & 1) && !(i_dummy & 1) )
993     {
994         i_ratio >>= 1;
995         i_dummy >>= 1;
996         i_pgcd  <<= 1;
997     }
998
999     while( !(i_ratio % 3) && !(i_dummy % 3) )
1000     {
1001         i_ratio /= 3;
1002         i_dummy /= 3;
1003         i_pgcd  *= 3;
1004     }
1005
1006     while( !(i_ratio % 5) && !(i_dummy % 5) )
1007     {
1008         i_ratio /= 5;
1009         i_dummy /= 5;
1010         i_pgcd  *= 5;
1011     }
1012
1013     return i_pgcd;
1014 }
1015
1016 /*****************************************************************************
1017  * BinaryLog: computes the base 2 log of a binary value
1018  *****************************************************************************
1019  * This functions is used by MaskToShift, to get a bit index from a binary
1020  * value.
1021  *****************************************************************************/
1022 static int BinaryLog( uint32_t i )
1023 {
1024     int i_log = 0;
1025
1026     if( i == 0 ) return -31337;
1027
1028     if( i & 0xffff0000 ) i_log += 16;
1029     if( i & 0xff00ff00 ) i_log += 8;
1030     if( i & 0xf0f0f0f0 ) i_log += 4;
1031     if( i & 0xcccccccc ) i_log += 2;
1032     if( i & 0xaaaaaaaa ) i_log += 1;
1033
1034     return i_log;
1035 }
1036
1037 /*****************************************************************************
1038  * MaskToShift: transform a color mask into right and left shifts
1039  *****************************************************************************
1040  * This function is used for obtaining color shifts from masks.
1041  *****************************************************************************/
1042 static void MaskToShift( int *pi_left, int *pi_right, uint32_t i_mask )
1043 {
1044     uint32_t i_low, i_high;            /* lower hand higher bits of the mask */
1045
1046     if( !i_mask )
1047     {
1048         *pi_left = *pi_right = 0;
1049         return;
1050     }
1051
1052     /* Get bits */
1053     i_low =  i_mask & (- (int32_t)i_mask);          /* lower bit of the mask */
1054     i_high = i_mask + i_low;                       /* higher bit of the mask */
1055
1056     /* Transform bits into an index */
1057     i_low =  BinaryLog (i_low);
1058     i_high = BinaryLog (i_high);
1059
1060     /* Update pointers and return */
1061     *pi_left =   i_low;
1062     *pi_right = (8 - i_high + i_low);
1063 }
1064
1065 /*****************************************************************************
1066  * InitWindowSize: find the initial dimensions the video window should have.
1067  *****************************************************************************
1068  * This function will check the "width", "height" and "zoom" config options and
1069  * will calculate the size that the video window should have.
1070  *****************************************************************************/
1071 static void InitWindowSize( vout_thread_t *p_vout, int *pi_width,
1072                             int *pi_height )
1073 {
1074     int i_width, i_height;
1075     uint64_t ll_zoom;
1076
1077 #define FP_FACTOR 1000                             /* our fixed point factor */
1078
1079     i_width = config_GetInt( p_vout, "width" );
1080     i_height = config_GetInt( p_vout, "height" );
1081     ll_zoom = (uint64_t)( FP_FACTOR * config_GetFloat( p_vout, "zoom" ) );
1082
1083     if( (i_width >= 0) && (i_height >= 0))
1084     {
1085         *pi_width = (int)( i_width * ll_zoom / FP_FACTOR );
1086         *pi_height = (int)( i_height * ll_zoom / FP_FACTOR );
1087         return;
1088     }
1089     else if( i_width >= 0 )
1090     {
1091         *pi_width = (int)( i_width * ll_zoom / FP_FACTOR );
1092         *pi_height = (int)( i_width * ll_zoom * VOUT_ASPECT_FACTOR /
1093                             p_vout->render.i_aspect / FP_FACTOR );
1094         return;
1095     }
1096     else if( i_height >= 0 )
1097     {
1098         *pi_height = (int)( i_height * ll_zoom / FP_FACTOR );
1099         *pi_width = (int)( i_height * ll_zoom * p_vout->render.i_aspect /
1100                            VOUT_ASPECT_FACTOR / FP_FACTOR );
1101         return;
1102     }
1103
1104     if( p_vout->render.i_height * p_vout->render.i_aspect
1105         >= p_vout->render.i_width * VOUT_ASPECT_FACTOR )
1106     {
1107         *pi_width = (int)( p_vout->render.i_height * ll_zoom
1108           * p_vout->render.i_aspect / VOUT_ASPECT_FACTOR / FP_FACTOR );
1109         *pi_height = (int)( p_vout->render.i_height * ll_zoom / FP_FACTOR );
1110     }
1111     else
1112     {
1113         *pi_width = (int)( p_vout->render.i_width * ll_zoom / FP_FACTOR );
1114         *pi_height = (int)( p_vout->render.i_width * ll_zoom
1115           * VOUT_ASPECT_FACTOR / p_vout->render.i_aspect / FP_FACTOR );
1116     }
1117
1118 #undef FP_FACTOR
1119 }
1120
1121 /*****************************************************************************
1122  * vout_VarCallback: generic callback for intf variables
1123  *****************************************************************************/
1124 int vout_VarCallback( vlc_object_t * p_this, const char * psz_variable,
1125                       vlc_value_t old_value, vlc_value_t new_value,
1126                       void * unused )
1127 {
1128     vout_thread_t * p_vout = (vout_thread_t *)p_this;
1129     vlc_value_t val;
1130     val.b_bool = 1;
1131     var_Set( p_vout, "intf-change", val );
1132     return 0;
1133 }