]> git.sesse.net Git - vlc/blob - modules/video_output/x11/xcommon.c
Remove stdlib.h
[vlc] / modules / video_output / x11 / xcommon.c
1 /*****************************************************************************
2  * xcommon.c: Functions common to the X11 and XVideo plugins
3  *****************************************************************************
4  * Copyright (C) 1998-2006 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Vincent Seguin <seguin@via.ecp.fr>
8  *          Sam Hocevar <sam@zoy.org>
9  *          David Kennedy <dkennedy@tinytoad.com>
10  *          Gildas Bazin <gbazin@videolan.org>
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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #include <errno.h>                                                 /* ENOMEM */
31 #include <string.h>                                            /* strerror() */
32
33 #include <vlc/vlc.h>
34 #include <vlc_interface.h>
35 #include <vlc_playlist.h>
36 #include <vlc_vout.h>
37 #include <vlc_keys.h>
38
39 #ifdef HAVE_MACHINE_PARAM_H
40     /* BSD */
41 #   include <machine/param.h>
42 #   include <sys/types.h>                                  /* typedef ushort */
43 #   include <sys/ipc.h>
44 #endif
45
46 #ifndef WIN32
47 #   include <netinet/in.h>                            /* BSD: struct in_addr */
48 #endif
49
50 #ifdef HAVE_XSP
51 #include <X11/extensions/Xsp.h>
52 #endif
53
54 #ifdef HAVE_SYS_SHM_H
55 #   include <sys/shm.h>                                /* shmget(), shmctl() */
56 #endif
57
58 #include <X11/Xlib.h>
59 #include <X11/Xproto.h>
60 #include <X11/Xmd.h>
61 #include <X11/Xutil.h>
62 #include <X11/keysym.h>
63 #include <X11/XF86keysym.h>
64 #ifdef HAVE_SYS_SHM_H
65 #   include <X11/extensions/XShm.h>
66 #endif
67 #ifdef DPMSINFO_IN_DPMS_H
68 #   include <X11/extensions/dpms.h>
69 #endif
70
71 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
72 #   include <X11/extensions/Xv.h>
73 #   include <X11/extensions/Xvlib.h>
74 #endif
75
76 #ifdef MODULE_NAME_IS_glx
77 #   include <GL/glx.h>
78 #endif
79
80 #ifdef HAVE_XINERAMA
81 #   include <X11/extensions/Xinerama.h>
82 #endif
83
84 #ifdef HAVE_X11_EXTENSIONS_XF86VMODE_H
85 #   include <X11/extensions/xf86vmode.h>
86 #endif
87
88 #ifdef MODULE_NAME_IS_xvmc
89 #   include <X11/extensions/vldXvMC.h>
90 #   include "../../codec/xvmc/accel_xvmc.h"
91 #endif
92
93 #include "xcommon.h"
94
95 /*****************************************************************************
96  * Local prototypes
97  *****************************************************************************/
98 int  E_(Activate)   ( vlc_object_t * );
99 void E_(Deactivate) ( vlc_object_t * );
100
101 static int  InitVideo      ( vout_thread_t * );
102 static void EndVideo       ( vout_thread_t * );
103 static void DisplayVideo   ( vout_thread_t *, picture_t * );
104 static int  ManageVideo    ( vout_thread_t * );
105 static int  Control        ( vout_thread_t *, int, va_list );
106
107 static int  InitDisplay    ( vout_thread_t * );
108
109 static int  CreateWindow   ( vout_thread_t *, x11_window_t * );
110 static void DestroyWindow  ( vout_thread_t *, x11_window_t * );
111
112 static int  NewPicture     ( vout_thread_t *, picture_t * );
113 static void FreePicture    ( vout_thread_t *, picture_t * );
114
115 static IMAGE_TYPE *CreateImage    ( vout_thread_t *,
116                                     Display *, EXTRA_ARGS, int, int );
117 #ifdef HAVE_SYS_SHM_H
118 static IMAGE_TYPE *CreateShmImage ( vout_thread_t *,
119                                     Display *, EXTRA_ARGS_SHM, int, int );
120 static vlc_bool_t b_shm = VLC_TRUE;
121 #endif
122
123 static void ToggleFullScreen      ( vout_thread_t * );
124
125 static void EnableXScreenSaver    ( vout_thread_t * );
126 static void DisableXScreenSaver   ( vout_thread_t * );
127
128 static void CreateCursor   ( vout_thread_t * );
129 static void DestroyCursor  ( vout_thread_t * );
130 static void ToggleCursor   ( vout_thread_t * );
131
132 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
133 static int  XVideoGetPort    ( vout_thread_t *, vlc_fourcc_t, vlc_fourcc_t * );
134 static void XVideoReleasePort( vout_thread_t *, int );
135 #endif
136
137 #ifdef MODULE_NAME_IS_x11
138 static void SetPalette     ( vout_thread_t *,
139                              uint16_t *, uint16_t *, uint16_t * );
140 #endif
141
142 #ifdef MODULE_NAME_IS_xvmc
143 static void RenderVideo    ( vout_thread_t *, picture_t * );
144 static int  xvmc_check_yv12( Display *display, XvPortID port );
145 static void xvmc_update_XV_DOUBLE_BUFFER( vout_thread_t *p_vout );
146 #endif
147
148 static void TestNetWMSupport( vout_thread_t * );
149 static int ConvertKey( int );
150
151 static int WindowOnTop( vout_thread_t *, vlc_bool_t );
152
153 static int X11ErrorHandler( Display *, XErrorEvent * );
154
155 #ifdef HAVE_XSP
156 static void EnablePixelDoubling( vout_thread_t *p_vout );
157 static void DisablePixelDoubling( vout_thread_t *p_vout );
158 #endif
159
160 #ifdef HAVE_OSSO
161 static const int i_backlight_on_interval = 300;
162 #endif
163
164
165
166 /*****************************************************************************
167  * Activate: allocate X11 video thread output method
168  *****************************************************************************
169  * This function allocate and initialize a X11 vout method. It uses some of the
170  * vout properties to choose the window size, and change them according to the
171  * actual properties of the display.
172  *****************************************************************************/
173 int E_(Activate) ( vlc_object_t *p_this )
174 {
175     vout_thread_t *p_vout = (vout_thread_t *)p_this;
176     char *        psz_display;
177     vlc_value_t   val;
178 #if defined(MODULE_NAME_IS_xvmc)
179     char *psz_value;
180 #endif
181 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
182     char *       psz_chroma;
183     vlc_fourcc_t i_chroma = 0;
184     vlc_bool_t   b_chroma = 0;
185 #endif
186
187     p_vout->pf_init = InitVideo;
188     p_vout->pf_end = EndVideo;
189     p_vout->pf_manage = ManageVideo;
190 #ifdef MODULE_NAME_IS_xvmc
191     p_vout->pf_render = RenderVideo;
192 #else
193     p_vout->pf_render = NULL;
194 #endif
195     p_vout->pf_display = DisplayVideo;
196     p_vout->pf_control = Control;
197
198     /* Allocate structure */
199     p_vout->p_sys = malloc( sizeof( vout_sys_t ) );
200     if( p_vout->p_sys == NULL )
201     {
202         msg_Err( p_vout, "out of memory" );
203         return VLC_ENOMEM;
204     }
205
206     vlc_mutex_init( p_vout, &p_vout->p_sys->lock );
207
208     /* Open display, using the "display" config variable or the DISPLAY
209      * environment variable */
210     psz_display = config_GetPsz( p_vout, MODULE_STRING "-display" );
211
212     p_vout->p_sys->p_display = XOpenDisplay( psz_display );
213
214     if( p_vout->p_sys->p_display == NULL )                          /* error */
215     {
216         msg_Err( p_vout, "cannot open display %s",
217                          XDisplayName( psz_display ) );
218         free( p_vout->p_sys );
219         if( psz_display ) free( psz_display );
220         return VLC_EGENERIC;
221     }
222     if( psz_display ) free( psz_display );
223
224     /* Replace error handler so we can intercept some non-fatal errors */
225     XSetErrorHandler( X11ErrorHandler );
226
227     /* Get a screen ID matching the XOpenDisplay return value */
228     p_vout->p_sys->i_screen = DefaultScreen( p_vout->p_sys->p_display );
229
230 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
231     psz_chroma = config_GetPsz( p_vout, "xvideo-chroma" );
232     if( psz_chroma )
233     {
234         if( strlen( psz_chroma ) >= 4 )
235         {
236             /* Do not use direct assignment because we are not sure of the
237              * alignment. */
238             memcpy(&i_chroma, psz_chroma, 4);
239             b_chroma = 1;
240         }
241
242         free( psz_chroma );
243     }
244
245     if( b_chroma )
246     {
247         msg_Dbg( p_vout, "forcing chroma 0x%.8x (%4.4s)",
248                  i_chroma, (char*)&i_chroma );
249     }
250     else
251     {
252         i_chroma = p_vout->render.i_chroma;
253     }
254
255     /* Check that we have access to an XVideo port providing this chroma */
256     p_vout->p_sys->i_xvport = XVideoGetPort( p_vout, VLC2X11_FOURCC(i_chroma),
257                                              &p_vout->output.i_chroma );
258     if( p_vout->p_sys->i_xvport < 0 )
259     {
260         /* If a specific chroma format was requested, then we don't try to
261          * be cleverer than the user. He knew pretty well what he wanted. */
262         if( b_chroma )
263         {
264             XCloseDisplay( p_vout->p_sys->p_display );
265             free( p_vout->p_sys );
266             return VLC_EGENERIC;
267         }
268
269         /* It failed, but it's not completely lost ! We try to open an
270          * XVideo port for an YUY2 picture. We'll need to do an YUV
271          * conversion, but at least it has got scaling. */
272         p_vout->p_sys->i_xvport =
273                         XVideoGetPort( p_vout, X11_FOURCC('Y','U','Y','2'),
274                                                &p_vout->output.i_chroma );
275         if( p_vout->p_sys->i_xvport < 0 )
276         {
277             /* It failed, but it's not completely lost ! We try to open an
278              * XVideo port for a simple 16bpp RGB picture. We'll need to do
279              * an YUV conversion, but at least it has got scaling. */
280             p_vout->p_sys->i_xvport =
281                             XVideoGetPort( p_vout, X11_FOURCC('R','V','1','6'),
282                                                    &p_vout->output.i_chroma );
283             if( p_vout->p_sys->i_xvport < 0 )
284             {
285                 XCloseDisplay( p_vout->p_sys->p_display );
286                 free( p_vout->p_sys );
287                 return VLC_EGENERIC;
288             }
289         }
290     }
291     p_vout->output.i_chroma = X112VLC_FOURCC(p_vout->output.i_chroma);
292 #elif defined(MODULE_NAME_IS_glx)
293     {
294         int i_opcode, i_evt, i_err = 0;
295         int i_maj, i_min = 0;
296
297         /* Check for GLX extension */
298         if( !XQueryExtension( p_vout->p_sys->p_display, "GLX",
299                               &i_opcode, &i_evt, &i_err ) )
300         {
301             msg_Err( p_this, "GLX extension not supported" );
302             XCloseDisplay( p_vout->p_sys->p_display );
303             free( p_vout->p_sys );
304             return VLC_EGENERIC;
305         }
306         if( !glXQueryExtension( p_vout->p_sys->p_display, &i_err, &i_evt ) )
307         {
308             msg_Err( p_this, "glXQueryExtension failed" );
309             XCloseDisplay( p_vout->p_sys->p_display );
310             free( p_vout->p_sys );
311             return VLC_EGENERIC;
312         }
313
314         /* Check GLX version */
315         if (!glXQueryVersion( p_vout->p_sys->p_display, &i_maj, &i_min ) )
316         {
317             msg_Err( p_this, "glXQueryVersion failed" );
318             XCloseDisplay( p_vout->p_sys->p_display );
319             free( p_vout->p_sys );
320             return VLC_EGENERIC;
321         }
322         if( i_maj <= 0 || ((i_maj == 1) && (i_min < 3)) )
323         {
324             p_vout->p_sys->b_glx13 = VLC_FALSE;
325             msg_Dbg( p_this, "using GLX 1.2 API" );
326         }
327         else
328         {
329             p_vout->p_sys->b_glx13 = VLC_TRUE;
330             msg_Dbg( p_this, "using GLX 1.3 API" );
331         }
332     }
333 #endif
334
335     /* Create blank cursor (for mouse cursor autohiding) */
336     p_vout->p_sys->i_time_mouse_last_moved = mdate();
337     p_vout->p_sys->b_mouse_pointer_visible = 1;
338     CreateCursor( p_vout );
339
340     /* Set main window's size */
341     p_vout->p_sys->original_window.i_width = p_vout->i_window_width;
342     p_vout->p_sys->original_window.i_height = p_vout->i_window_height;
343     var_Create( p_vout, "video-title", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
344     /* Spawn base window - this window will include the video output window,
345      * but also command buttons, subtitles and other indicators */
346     if( CreateWindow( p_vout, &p_vout->p_sys->original_window ) )
347     {
348         msg_Err( p_vout, "cannot create X11 window" );
349         DestroyCursor( p_vout );
350         XCloseDisplay( p_vout->p_sys->p_display );
351         free( p_vout->p_sys );
352         return VLC_EGENERIC;
353     }
354
355     /* Open and initialize device. */
356     if( InitDisplay( p_vout ) )
357     {
358         msg_Err( p_vout, "cannot initialize X11 display" );
359         DestroyCursor( p_vout );
360         DestroyWindow( p_vout, &p_vout->p_sys->original_window );
361         XCloseDisplay( p_vout->p_sys->p_display );
362         free( p_vout->p_sys );
363         return VLC_EGENERIC;
364     }
365
366     /* Disable screen saver */
367     DisableXScreenSaver( p_vout );
368
369     /* Misc init */
370     p_vout->p_sys->b_altfullscreen = 0;
371     p_vout->p_sys->i_time_button_last_pressed = 0;
372
373     TestNetWMSupport( p_vout );
374
375 #ifdef MODULE_NAME_IS_xvmc
376     p_vout->p_sys->p_last_subtitle_save = NULL;
377     psz_value = config_GetPsz( p_vout, "xvmc-deinterlace-mode" );
378
379     /* Look what method was requested */
380     //var_Create( p_vout, "xvmc-deinterlace-mode", VLC_VAR_STRING );
381     //var_Change( p_vout, "xvmc-deinterlace-mode", VLC_VAR_INHERITVALUE, &val, NULL );
382     if( psz_value )
383     {
384         if( (strcmp(psz_value, "bob") == 0) ||
385             (strcmp(psz_value, "blend") == 0) )
386            p_vout->p_sys->xvmc_deinterlace_method = 2;
387         else if (strcmp(psz_value, "discard") == 0)
388            p_vout->p_sys->xvmc_deinterlace_method = 1;
389         else
390            p_vout->p_sys->xvmc_deinterlace_method = 0;
391         free(psz_value );
392     }
393     else
394         p_vout->p_sys->xvmc_deinterlace_method = 0;
395
396     /* Look what method was requested */
397     //var_Create( p_vout, "xvmc-crop-style", VLC_VAR_STRING );
398     //var_Change( p_vout, "xvmc-crop-style", VLC_VAR_INHERITVALUE, &val, NULL );
399     psz_value = config_GetPsz( p_vout, "xvmc-crop-style" );
400
401     if( psz_value )
402     {
403         if( strncmp( psz_value, "eq", 2 ) == 0 )
404            p_vout->p_sys->xvmc_crop_style = 1;
405         else if( strncmp( psz_value, "4-16", 4 ) == 0)
406            p_vout->p_sys->xvmc_crop_style = 2;
407         else if( strncmp( psz_value, "16-4", 4 ) == 0)
408            p_vout->p_sys->xvmc_crop_style = 3;
409         else
410            p_vout->p_sys->xvmc_crop_style = 0;
411         free( psz_value );
412     }
413     else
414         p_vout->p_sys->xvmc_crop_style = 0;
415
416     msg_Dbg(p_vout, "Deinterlace = %d", p_vout->p_sys->xvmc_deinterlace_method);
417     msg_Dbg(p_vout, "Crop = %d", p_vout->p_sys->xvmc_crop_style);
418
419     if( !checkXvMCCap( p_vout ) )
420     {
421         msg_Err( p_vout, "no XVMC capability found" );
422         E_(Deactivate)( p_vout );
423         return VLC_EGENERIC;
424     }
425     sub_pic.p_sys = NULL;
426     p_vout->p_sys->last_date = 0;
427 #endif
428
429 #ifdef HAVE_XSP
430     p_vout->p_sys->i_hw_scale = 1;
431 #endif
432
433 #ifdef HAVE_OSSO
434     p_vout->p_sys->i_backlight_on_counter = i_backlight_on_interval; 
435     p_vout->p_sys->p_octx = osso_initialize( "vlc", VERSION, 0, NULL );
436     if ( p_vout->p_sys->p_octx == NULL ) {
437         msg_Err( p_vout, "Could not get osso context" );
438     } else {
439         msg_Dbg( p_vout, "Initialized osso context" );
440     }
441 #endif
442
443     /* Variable to indicate if the window should be on top of others */
444     /* Trigger a callback right now */
445     var_Get( p_vout, "video-on-top", &val );
446     var_Set( p_vout, "video-on-top", val );
447
448     return VLC_SUCCESS;
449 }
450
451 /*****************************************************************************
452  * Deactivate: destroy X11 video thread output method
453  *****************************************************************************
454  * Terminate an output method created by Open
455  *****************************************************************************/
456 void E_(Deactivate) ( vlc_object_t *p_this )
457 {
458     vout_thread_t *p_vout = (vout_thread_t *)p_this;
459
460     /* If the fullscreen window is still open, close it */
461     if( p_vout->b_fullscreen )
462     {
463         ToggleFullScreen( p_vout );
464     }
465
466     /* Restore cursor if it was blanked */
467     if( !p_vout->p_sys->b_mouse_pointer_visible )
468     {
469         ToggleCursor( p_vout );
470     }
471
472 #ifdef MODULE_NAME_IS_x11
473     /* Destroy colormap */
474     if( XDefaultDepth(p_vout->p_sys->p_display, p_vout->p_sys->i_screen) == 8 )
475     {
476         XFreeColormap( p_vout->p_sys->p_display, p_vout->p_sys->colormap );
477     }
478 #elif defined(MODULE_NAME_IS_xvideo)
479     XVideoReleasePort( p_vout, p_vout->p_sys->i_xvport );
480 #elif defined(MODULE_NAME_IS_xvmc)
481     if( p_vout->p_sys->xvmc_cap )
482     {
483         xvmc_context_writer_lock( &p_vout->p_sys->xvmc_lock );
484         xxmc_dispose_context( p_vout );
485         if( p_vout->p_sys->old_subpic )
486         {
487             xxmc_xvmc_free_subpicture( p_vout, p_vout->p_sys->old_subpic );
488             p_vout->p_sys->old_subpic = NULL;
489         }
490         if( p_vout->p_sys->new_subpic )
491         {
492             xxmc_xvmc_free_subpicture( p_vout, p_vout->p_sys->new_subpic );
493             p_vout->p_sys->new_subpic = NULL;
494         }
495         free( p_vout->p_sys->xvmc_cap );
496         xvmc_context_writer_unlock( &p_vout->p_sys->xvmc_lock );
497     }
498 #endif
499
500 #ifdef HAVE_XSP
501     DisablePixelDoubling(p_vout);
502 #endif
503             
504     DestroyCursor( p_vout );
505     EnableXScreenSaver( p_vout );
506     DestroyWindow( p_vout, &p_vout->p_sys->original_window );
507     XCloseDisplay( p_vout->p_sys->p_display );
508
509     /* Destroy structure */
510     vlc_mutex_destroy( &p_vout->p_sys->lock );
511 #ifdef MODULE_NAME_IS_xvmc
512     free_context_lock( &p_vout->p_sys->xvmc_lock );
513 #endif
514
515 #ifdef HAVE_OSSO
516     if ( p_vout->p_sys->p_octx != NULL ) {
517         msg_Dbg( p_vout, "Deinitializing osso context" );
518         osso_deinitialize( p_vout->p_sys->p_octx );
519     }
520 #endif
521
522     free( p_vout->p_sys );
523 }
524
525 #ifdef MODULE_NAME_IS_xvmc
526
527 #define XINE_IMGFMT_YV12 (('2'<<24)|('1'<<16)|('V'<<8)|'Y')
528
529 /* called xlocked */
530 static int xvmc_check_yv12( Display *display, XvPortID port )
531 {
532     XvImageFormatValues *formatValues;
533     int                  formats;
534     int                  i;
535
536     formatValues = XvListImageFormats( display, port, &formats );
537
538     for( i = 0; i < formats; i++ )
539     {
540         if( ( formatValues[i].id == XINE_IMGFMT_YV12 ) &&
541             ( !( strncmp( formatValues[i].guid, "YV12", 4 ) ) ) )
542         {
543             XFree (formatValues);
544             return 0;
545         }
546     }
547
548     XFree (formatValues);
549     return 1;
550 }
551
552 static void xvmc_sync_surface( vout_thread_t *p_vout, XvMCSurface * srf )
553 {
554     XvMCSyncSurface( p_vout->p_sys->p_display, srf );
555 }
556
557 static void xvmc_update_XV_DOUBLE_BUFFER( vout_thread_t *p_vout )
558 {
559     Atom         atom;
560     int          xv_double_buffer;
561
562     xv_double_buffer = 1;
563
564     XLockDisplay( p_vout->p_sys->p_display );
565     atom = XInternAtom( p_vout->p_sys->p_display, "XV_DOUBLE_BUFFER", False );
566 #if 0
567     XvSetPortAttribute (p_vout->p_sys->p_display, p_vout->p_sys->i_xvport, atom, xv_double_buffer);
568 #endif
569     XvMCSetAttribute( p_vout->p_sys->p_display, &p_vout->p_sys->context, atom, xv_double_buffer );
570     XUnlockDisplay( p_vout->p_sys->p_display );
571
572     //xprintf(this->xine, XINE_VERBOSITY_DEBUG,
573     //    "video_out_xxmc: double buffering mode = %d\n", xv_double_buffer);
574 }
575
576 static void RenderVideo( vout_thread_t *p_vout, picture_t *p_pic )
577 {
578     vlc_xxmc_t *xxmc = NULL;
579
580     vlc_mutex_lock( &p_vout->p_sys->lock );
581     xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
582
583     xxmc = &p_pic->p_sys->xxmc_data;
584     if( (!xxmc->decoded ||
585         !xxmc_xvmc_surface_valid( p_vout, p_pic->p_sys->xvmc_surf )) )
586     {
587         vlc_mutex_unlock( &p_vout->p_sys->lock );
588         xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
589         return;
590     }
591
592     vlc_mutex_lock( &p_vout->lastsubtitle_lock );
593
594     if (p_vout->p_last_subtitle != NULL)
595     {
596         if( p_vout->p_sys->p_last_subtitle_save != p_vout->p_last_subtitle )
597         {
598             p_vout->p_sys->new_subpic =
599                 xxmc_xvmc_alloc_subpicture( p_vout, &p_vout->p_sys->context,
600                     p_vout->p_sys->xvmc_width,
601                     p_vout->p_sys->xvmc_height,
602                     p_vout->p_sys->xvmc_cap[p_vout->p_sys->xvmc_cur_cap].subPicType.id );
603
604             if (p_vout->p_sys->new_subpic)
605             {
606                 XVMCLOCKDISPLAY( p_vout->p_sys->p_display );
607                 XvMCClearSubpicture( p_vout->p_sys->p_display,
608                         p_vout->p_sys->new_subpic,
609                         0,
610                         0,
611                         p_vout->p_sys->xvmc_width,
612                         p_vout->p_sys->xvmc_height,
613                         0x00 );
614                 XVMCUNLOCKDISPLAY( p_vout->p_sys->p_display );
615                 clear_xx44_palette( &p_vout->p_sys->palette );
616
617                 if( sub_pic.p_sys == NULL )
618                 {
619                     sub_pic.p_sys = malloc( sizeof( picture_sys_t ) );
620                     if( sub_pic.p_sys != NULL )
621                     {
622                         sub_pic.p_sys->p_vout = p_vout;
623                         sub_pic.p_sys->xvmc_surf = NULL;
624                         sub_pic.p_sys->p_image = p_vout->p_sys->subImage;
625                     }
626                 }
627                 sub_pic.p_sys->p_image = p_vout->p_sys->subImage;
628                 sub_pic.p->p_pixels = sub_pic.p_sys->p_image->data;
629                 sub_pic.p->i_pitch = p_vout->output.i_width;
630
631                 memset( p_vout->p_sys->subImage->data, 0,
632                         (p_vout->p_sys->subImage->width * p_vout->p_sys->subImage->height) );
633
634                 if (p_vout->p_last_subtitle != NULL)
635                 {
636                     blend_xx44( p_vout->p_sys->subImage->data,
637                                 p_vout->p_last_subtitle,
638                                 p_vout->p_sys->subImage->width,
639                                 p_vout->p_sys->subImage->height,
640                                 p_vout->p_sys->subImage->width,
641                                 &p_vout->p_sys->palette,
642                                 (p_vout->p_sys->subImage->id == FOURCC_IA44) );
643                 }
644
645                 XVMCLOCKDISPLAY( p_vout->p_sys->p_display );
646                 XvMCCompositeSubpicture( p_vout->p_sys->p_display,
647                                          p_vout->p_sys->new_subpic,
648                                          p_vout->p_sys->subImage,
649                                          0, /* overlay->x */
650                                          0, /* overlay->y */
651                                          p_vout->output.i_width, /* overlay->width, */
652                                          p_vout->output.i_height, /* overlay->height */
653                                          0, /* overlay->x */
654                                          0 ); /*overlay->y */
655                 XVMCUNLOCKDISPLAY( p_vout->p_sys->p_display );
656                 if (p_vout->p_sys->old_subpic)
657                 {
658                     xxmc_xvmc_free_subpicture( p_vout,
659                                                p_vout->p_sys->old_subpic);
660                     p_vout->p_sys->old_subpic = NULL;
661                 }
662                 if (p_vout->p_sys->new_subpic)
663                 {
664                     p_vout->p_sys->old_subpic = p_vout->p_sys->new_subpic;
665                     p_vout->p_sys->new_subpic = NULL;
666                     xx44_to_xvmc_palette( &p_vout->p_sys->palette,
667                             p_vout->p_sys->xvmc_palette,
668                             0,
669                             p_vout->p_sys->old_subpic->num_palette_entries,
670                             p_vout->p_sys->old_subpic->entry_bytes,
671                             p_vout->p_sys->old_subpic->component_order );
672                     XVMCLOCKDISPLAY( p_vout->p_sys->p_display );
673                     XvMCSetSubpicturePalette( p_vout->p_sys->p_display,
674                                               p_vout->p_sys->old_subpic,
675                                               p_vout->p_sys->xvmc_palette );
676                     XvMCFlushSubpicture( p_vout->p_sys->p_display,
677                                          p_vout->p_sys->old_subpic);
678                     XvMCSyncSubpicture( p_vout->p_sys->p_display,
679                                         p_vout->p_sys->old_subpic );
680                     XVMCUNLOCKDISPLAY( p_vout->p_sys->p_display );
681                 }
682
683                 XVMCLOCKDISPLAY( p_vout->p_sys->p_display);
684                 if (p_vout->p_sys->xvmc_backend_subpic )
685                 {
686                     XvMCBlendSubpicture( p_vout->p_sys->p_display,
687                                          p_pic->p_sys->xvmc_surf,
688                                          p_vout->p_sys->old_subpic,
689                                          0,
690                                          0,
691                                          p_vout->p_sys->xvmc_width,
692                                          p_vout->p_sys->xvmc_height,
693                                          0,
694                                          0,
695                                          p_vout->p_sys->xvmc_width,
696                                          p_vout->p_sys->xvmc_height );
697                 }
698                 else
699                 {
700                     XvMCBlendSubpicture2( p_vout->p_sys->p_display,
701                                           p_pic->p_sys->xvmc_surf,
702                                           p_pic->p_sys->xvmc_surf,
703                                           p_vout->p_sys->old_subpic,
704                                           0,
705                                           0,
706                                           p_vout->p_sys->xvmc_width,
707                                           p_vout->p_sys->xvmc_height,
708                                           0,
709                                           0,
710                                           p_vout->p_sys->xvmc_width,
711                                           p_vout->p_sys->xvmc_height );
712                }
713                XVMCUNLOCKDISPLAY(p_vout->p_sys->p_display);
714             }
715         }
716         else
717         {
718             XVMCLOCKDISPLAY( p_vout->p_sys->p_display );
719             if( p_vout->p_sys->xvmc_backend_subpic )
720             {
721                 XvMCBlendSubpicture( p_vout->p_sys->p_display,
722                                      p_pic->p_sys->xvmc_surf,
723                                      p_vout->p_sys->old_subpic,
724                                      0, 0,
725                                      p_vout->p_sys->xvmc_width,
726                                      p_vout->p_sys->xvmc_height,
727                                      0, 0,
728                                      p_vout->p_sys->xvmc_width,
729                                      p_vout->p_sys->xvmc_height );
730             }
731             else
732             {
733                 XvMCBlendSubpicture2( p_vout->p_sys->p_display,
734                                       p_pic->p_sys->xvmc_surf,
735                                       p_pic->p_sys->xvmc_surf,
736                                       p_vout->p_sys->old_subpic,
737                                       0, 0,
738                                       p_vout->p_sys->xvmc_width,
739                                       p_vout->p_sys->xvmc_height,
740                                       0, 0,
741                                       p_vout->p_sys->xvmc_width,
742                                       p_vout->p_sys->xvmc_height );
743             }
744             XVMCUNLOCKDISPLAY( p_vout->p_sys->p_display );
745         }
746     }
747     p_vout->p_sys->p_last_subtitle_save = p_vout->p_last_subtitle;
748
749     vlc_mutex_unlock( &p_vout->lastsubtitle_lock );
750     xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
751
752     vlc_mutex_unlock( &p_vout->p_sys->lock );
753 }
754 #endif
755
756 #ifdef HAVE_XSP
757 /*****************************************************************************
758  * EnablePixelDoubling: Enables pixel doubling
759  *****************************************************************************
760  * Checks if the double size image fits in current window, and enables pixel
761  * doubling accordingly. The i_hw_scale is the integer scaling factor.
762  *****************************************************************************/
763 static void EnablePixelDoubling( vout_thread_t *p_vout )
764 {
765     int i_hor_scale = ( p_vout->p_sys->p_win->i_width ) / p_vout->render.i_width;
766     int i_vert_scale =  ( p_vout->p_sys->p_win->i_height ) / p_vout->render.i_height;
767     if ( ( i_hor_scale > 1 ) && ( i_vert_scale > 1 ) ) {
768         p_vout->p_sys->i_hw_scale = 2;
769         msg_Dbg( p_vout, "Enabling pixel doubling, scaling factor %d", p_vout->p_sys->i_hw_scale );
770         XSPSetPixelDoubling( p_vout->p_sys->p_display, 0, 1 );
771     }
772 }
773
774 /*****************************************************************************
775  * DisablePixelDoubling: Disables pixel doubling
776  *****************************************************************************
777  * The scaling factor i_hw_scale is reset to the no-scaling value 1.
778  *****************************************************************************/
779 static void DisablePixelDoubling( vout_thread_t *p_vout )
780 {
781     if ( p_vout->p_sys->i_hw_scale > 1 ) {
782         msg_Dbg( p_vout, "Disabling pixel doubling" );
783         XSPSetPixelDoubling( p_vout->p_sys->p_display, 0, 0 );
784         p_vout->p_sys->i_hw_scale = 1;
785     }
786 }
787 #endif
788
789
790
791 /*****************************************************************************
792  * InitVideo: initialize X11 video thread output method
793  *****************************************************************************
794  * This function create the XImages needed by the output thread. It is called
795  * at the beginning of the thread, but also each time the window is resized.
796  *****************************************************************************/
797 static int InitVideo( vout_thread_t *p_vout )
798 {
799     unsigned int i_index = 0;
800     picture_t *p_pic;
801
802     I_OUTPUTPICTURES = 0;
803
804 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
805     /* Initialize the output structure; we already found an XVideo port,
806      * and the corresponding chroma we will be using. Since we can
807      * arbitrary scale, stick to the coordinates and aspect. */
808     p_vout->output.i_width  = p_vout->render.i_width;
809     p_vout->output.i_height = p_vout->render.i_height;
810     p_vout->output.i_aspect = p_vout->render.i_aspect;
811
812     p_vout->fmt_out = p_vout->fmt_in;
813     p_vout->fmt_out.i_chroma = p_vout->output.i_chroma;
814
815     switch( p_vout->output.i_chroma )
816     {
817         case VLC_FOURCC('R','V','1','6'):
818 #if defined( WORDS_BIGENDIAN )
819             p_vout->output.i_rmask = 0xf800;
820             p_vout->output.i_gmask = 0x07e0;
821             p_vout->output.i_bmask = 0x001f;
822 #else
823             p_vout->output.i_rmask = 0x001f;
824             p_vout->output.i_gmask = 0x07e0;
825             p_vout->output.i_bmask = 0xf800;
826 #endif
827             break;
828         case VLC_FOURCC('R','V','1','5'):
829 #if defined( WORDS_BIGENDIAN )
830             p_vout->output.i_rmask = 0x7c00;
831             p_vout->output.i_gmask = 0x03e0;
832             p_vout->output.i_bmask = 0x001f;
833 #else
834             p_vout->output.i_rmask = 0x001f;
835             p_vout->output.i_gmask = 0x03e0;
836             p_vout->output.i_bmask = 0x7c00;
837 #endif
838             break;
839     }
840
841 #elif defined(MODULE_NAME_IS_x11)
842     /* Initialize the output structure: RGB with square pixels, whatever
843      * the input format is, since it's the only format we know */
844     switch( p_vout->p_sys->i_screen_depth )
845     {
846         case 8: /* FIXME: set the palette */
847             p_vout->output.i_chroma = VLC_FOURCC('R','G','B','2'); break;
848         case 15:
849             p_vout->output.i_chroma = VLC_FOURCC('R','V','1','5'); break;
850         case 16:
851             p_vout->output.i_chroma = VLC_FOURCC('R','V','1','6'); break;
852         case 24:
853         case 32:
854             p_vout->output.i_chroma = VLC_FOURCC('R','V','3','2'); break;
855         default:
856             msg_Err( p_vout, "unknown screen depth %i",
857                      p_vout->p_sys->i_screen_depth );
858             return VLC_SUCCESS;
859     }
860
861 #ifdef HAVE_XSP
862     vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width  / p_vout->p_sys->i_hw_scale,
863                        p_vout->p_sys->p_win->i_height  / p_vout->p_sys->i_hw_scale,
864                        &i_index, &i_index,
865                        &p_vout->fmt_out.i_visible_width,
866                        &p_vout->fmt_out.i_visible_height );
867 #else
868     vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width,
869                        p_vout->p_sys->p_win->i_height,
870                        &i_index, &i_index,
871                        &p_vout->fmt_out.i_visible_width,
872                        &p_vout->fmt_out.i_visible_height );
873 #endif
874
875     p_vout->fmt_out.i_chroma = p_vout->output.i_chroma;
876
877     p_vout->output.i_width = p_vout->fmt_out.i_width =
878         p_vout->fmt_out.i_visible_width * p_vout->fmt_in.i_width /
879         p_vout->fmt_in.i_visible_width;
880     p_vout->output.i_height = p_vout->fmt_out.i_height =
881         p_vout->fmt_out.i_visible_height * p_vout->fmt_in.i_height /
882         p_vout->fmt_in.i_visible_height;
883     p_vout->fmt_out.i_x_offset =
884         p_vout->fmt_out.i_visible_width * p_vout->fmt_in.i_x_offset /
885         p_vout->fmt_in.i_visible_width;
886     p_vout->fmt_out.i_y_offset =
887         p_vout->fmt_out.i_visible_height * p_vout->fmt_in.i_y_offset /
888         p_vout->fmt_in.i_visible_height;
889
890     p_vout->fmt_out.i_sar_num = p_vout->fmt_out.i_sar_den = 1;
891     p_vout->output.i_aspect = p_vout->fmt_out.i_aspect =
892         p_vout->fmt_out.i_width * VOUT_ASPECT_FACTOR /p_vout->fmt_out.i_height;
893
894     msg_Dbg( p_vout, "x11 image size %ix%i (%i,%i,%ix%i)",
895              p_vout->fmt_out.i_width, p_vout->fmt_out.i_height,
896              p_vout->fmt_out.i_x_offset, p_vout->fmt_out.i_y_offset,
897              p_vout->fmt_out.i_visible_width,
898              p_vout->fmt_out.i_visible_height );
899 #endif
900
901     /* Try to initialize up to MAX_DIRECTBUFFERS direct buffers */
902     while( I_OUTPUTPICTURES < MAX_DIRECTBUFFERS )
903     {
904         p_pic = NULL;
905
906         /* Find an empty picture slot */
907         for( i_index = 0 ; i_index < VOUT_MAX_PICTURES ; i_index++ )
908         {
909           if( p_vout->p_picture[ i_index ].i_status == FREE_PICTURE )
910             {
911                 p_pic = p_vout->p_picture + i_index;
912                 break;
913             }
914         }
915
916         /* Allocate the picture */
917         if( p_pic == NULL || NewPicture( p_vout, p_pic ) )
918         {
919             break;
920         }
921
922         p_pic->i_status = DESTROYED_PICTURE;
923         p_pic->i_type   = DIRECT_PICTURE;
924
925         PP_OUTPUTPICTURE[ I_OUTPUTPICTURES ] = p_pic;
926
927         I_OUTPUTPICTURES++;
928     }
929
930     if( p_vout->output.i_chroma == VLC_FOURCC('Y','V','1','2') )
931     {
932         /* U and V inverted compared to I420
933          * Fixme: this should be handled by the vout core */
934         p_vout->output.i_chroma = VLC_FOURCC('I','4','2','0');
935         p_vout->fmt_out.i_chroma = VLC_FOURCC('I','4','2','0');
936     }
937
938     return VLC_SUCCESS;
939 }
940
941 /*****************************************************************************
942  * DisplayVideo: displays previously rendered output
943  *****************************************************************************
944  * This function sends the currently rendered image to X11 server.
945  * (The Xv extension takes care of "double-buffering".)
946  *****************************************************************************/
947 static void DisplayVideo( vout_thread_t *p_vout, picture_t *p_pic )
948 {
949     unsigned int i_width, i_height, i_x, i_y;
950
951     vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width,
952                        p_vout->p_sys->p_win->i_height,
953                        &i_x, &i_y, &i_width, &i_height );
954
955     vlc_mutex_lock( &p_vout->p_sys->lock );
956
957 #ifdef MODULE_NAME_IS_xvmc
958     xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
959
960     vlc_xxmc_t *xxmc = &p_picture->p_sys->xxmc_data;
961     if( !xxmc->decoded ||
962         !xxmc_xvmc_surface_valid( p_vout, p_picture->p_sys->xvmc_surf ) )
963     {
964       msg_Dbg( p_vout, "DisplayVideo decoded=%d\tsurfacevalid=%d",
965                xxmc->decoded,
966                xxmc_xvmc_surface_valid( p_vout, p_picture->p_sys->xvmc_surf ) );
967       vlc_mutex_unlock( &p_vout->p_sys->lock );
968       xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
969       return;
970     }
971
972     src_width = p_vout->output.i_width;
973     src_height = p_vout->output.i_height;
974
975     if( p_vout->p_sys->xvmc_crop_style == 1 )
976     {
977         src_x = 20;
978         src_y = 20;
979         src_width -= 40;
980         src_height -= 40;
981     }
982     else if( p_vout->p_sys->xvmc_crop_style == 2 )
983     {
984         src_x = 20;
985         src_y = 40;
986         src_width -= 40;
987         src_height -= 80;
988     }
989     else if( p_vout->p_sys->xvmc_crop_style == 3 )
990     {
991         src_x = 40;
992         src_y = 20;
993         src_width -= 80;
994         src_height -= 40;
995     }
996     else
997     {
998         src_x = 0;
999         src_y = 0;
1000     }
1001
1002     if( p_vout->p_sys->xvmc_deinterlace_method > 0 )
1003     {   /* BOB DEINTERLACE */
1004         if( (p_picture->p_sys->nb_display == 0) ||
1005             (p_vout->p_sys->xvmc_deinterlace_method == 1) )
1006         {
1007             first_field = (p_picture->b_top_field_first) ?
1008                                 XVMC_BOTTOM_FIELD : XVMC_TOP_FIELD;
1009         }
1010         else
1011         {
1012             first_field = (p_picture->b_top_field_first) ?
1013                                 XVMC_TOP_FIELD : XVMC_BOTTOM_FIELD;
1014         }
1015     }
1016     else
1017     {
1018         first_field = XVMC_FRAME_PICTURE;
1019      }
1020
1021     XVMCLOCKDISPLAY( p_vout->p_sys->p_display );
1022     XvMCFlushSurface( p_vout->p_sys->p_display, p_picture->p_sys->xvmc_surf );
1023     /* XvMCSyncSurface(p_vout->p_sys->p_display, p_picture->p_sys->xvmc_surf); */
1024     XvMCPutSurface( p_vout->p_sys->p_display,
1025                     p_picture->p_sys->xvmc_surf,
1026                     p_vout->p_sys->p_win->video_window,
1027                     src_x,
1028                     src_y,
1029                     src_width,
1030                     src_height,
1031                     0 /*dest_x*/,
1032                     0 /*dest_y*/,
1033                     i_width,
1034                     i_height,
1035                     first_field);
1036
1037     XVMCUNLOCKDISPLAY( p_vout->p_sys->p_display );
1038     if( p_vout->p_sys->xvmc_deinterlace_method == 2 ) 
1039     {   /* BOB DEINTERLACE */
1040         if( p_picture->p_sys->nb_display == 0 )/* && ((t2-t1) < 15000)) */
1041         {
1042             mtime_t last_date = p_picture->date;
1043
1044             vlc_mutex_lock( &p_vout->picture_lock );
1045             if( !p_vout->p_sys->last_date )
1046             {
1047                 p_picture->date += 20000;
1048             }
1049             else
1050             {
1051                 p_picture->date = ((3 * p_picture->date -
1052                                     p_vout->p_sys->last_date) / 2 );
1053             }
1054             p_vout->p_sys->last_date = last_date;
1055             p_picture->b_force = 1;
1056             p_picture->p_sys->nb_display = 1;
1057             vlc_mutex_unlock( &p_vout->picture_lock );
1058         }
1059         else
1060         {
1061             p_picture->p_sys->nb_display = 0;
1062             p_picture->b_force = 0;
1063         }
1064     }
1065     xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
1066 #endif
1067
1068 #ifdef HAVE_SYS_SHM_H
1069     if( p_vout->p_sys->b_shm )
1070     {
1071         /* Display rendered image using shared memory extension */
1072 #   if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
1073         XvShmPutImage( p_vout->p_sys->p_display, p_vout->p_sys->i_xvport,
1074                        p_vout->p_sys->p_win->video_window,
1075                        p_vout->p_sys->p_win->gc, p_pic->p_sys->p_image,
1076                        p_vout->fmt_out.i_x_offset,
1077                        p_vout->fmt_out.i_y_offset,
1078                        p_vout->fmt_out.i_visible_width,
1079                        p_vout->fmt_out.i_visible_height,
1080                        0 /*dest_x*/, 0 /*dest_y*/, i_width, i_height,
1081                        False /* Don't put True here or you'll waste your CPU */ );
1082 #   else
1083         XShmPutImage( p_vout->p_sys->p_display,
1084                       p_vout->p_sys->p_win->video_window,
1085                       p_vout->p_sys->p_win->gc, p_pic->p_sys->p_image,
1086                       p_vout->fmt_out.i_x_offset,
1087                       p_vout->fmt_out.i_y_offset,
1088                       0 /*dest_x*/, 0 /*dest_y*/,
1089                       p_vout->fmt_out.i_visible_width,
1090                       p_vout->fmt_out.i_visible_height,
1091                       False /* Don't put True here ! */ );
1092 #   endif
1093     }
1094     else
1095 #endif /* HAVE_SYS_SHM_H */
1096     {
1097         /* Use standard XPutImage -- this is gonna be slow ! */
1098 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
1099         XvPutImage( p_vout->p_sys->p_display, p_vout->p_sys->i_xvport,
1100                     p_vout->p_sys->p_win->video_window,
1101                     p_vout->p_sys->p_win->gc, p_pic->p_sys->p_image,
1102                     p_vout->fmt_out.i_x_offset,
1103                     p_vout->fmt_out.i_y_offset,
1104                     p_vout->fmt_out.i_visible_width,
1105                     p_vout->fmt_out.i_visible_height,
1106                     0 /*dest_x*/, 0 /*dest_y*/, i_width, i_height );
1107 #else
1108         XPutImage( p_vout->p_sys->p_display,
1109                    p_vout->p_sys->p_win->video_window,
1110                    p_vout->p_sys->p_win->gc, p_pic->p_sys->p_image,
1111                    p_vout->fmt_out.i_x_offset,
1112                    p_vout->fmt_out.i_y_offset,
1113                    0 /*dest_x*/, 0 /*dest_y*/,
1114                    p_vout->fmt_out.i_visible_width,
1115                    p_vout->fmt_out.i_visible_height );
1116 #endif
1117     }
1118
1119     /* Make sure the command is sent now - do NOT use XFlush !*/
1120     XSync( p_vout->p_sys->p_display, False );
1121
1122     vlc_mutex_unlock( &p_vout->p_sys->lock );
1123 }
1124
1125 /*****************************************************************************
1126  * ManageVideo: handle X11 events
1127  *****************************************************************************
1128  * This function should be called regularly by video output thread. It manages
1129  * X11 events and allows window resizing. It returns a non null value on
1130  * error.
1131  *****************************************************************************/
1132 static int ManageVideo( vout_thread_t *p_vout )
1133 {
1134     XEvent      xevent;                                         /* X11 event */
1135     vlc_value_t val;
1136
1137     vlc_mutex_lock( &p_vout->p_sys->lock );
1138
1139 #ifdef MODULE_NAME_IS_xvmc
1140     xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
1141 #endif
1142
1143     /* Handle events from the owner window */
1144     if( p_vout->p_sys->p_win->owner_window )
1145     {
1146         while( XCheckWindowEvent( p_vout->p_sys->p_display,
1147                                   p_vout->p_sys->p_win->owner_window,
1148                                   StructureNotifyMask, &xevent ) == True )
1149         {
1150             /* ConfigureNotify event: prepare  */
1151             if( xevent.type == ConfigureNotify )
1152             {
1153                 /* Update dimensions */
1154                 XResizeWindow( p_vout->p_sys->p_display,
1155                                p_vout->p_sys->p_win->base_window,
1156                                xevent.xconfigure.width,
1157                                xevent.xconfigure.height );
1158             }
1159         }
1160     }
1161
1162     /* Handle X11 events: ConfigureNotify events are parsed to know if the
1163      * output window's size changed, MapNotify and UnmapNotify to know if the
1164      * window is mapped (and if the display is useful), and ClientMessages
1165      * to intercept window destruction requests */
1166
1167     while( XCheckWindowEvent( p_vout->p_sys->p_display,
1168                               p_vout->p_sys->p_win->base_window,
1169                               StructureNotifyMask | KeyPressMask |
1170                               ButtonPressMask | ButtonReleaseMask |
1171                               PointerMotionMask | Button1MotionMask , &xevent )
1172            == True )
1173     {
1174         /* ConfigureNotify event: prepare  */
1175         if( xevent.type == ConfigureNotify )
1176         {
1177             if( (unsigned int)xevent.xconfigure.width
1178                    != p_vout->p_sys->p_win->i_width
1179               || (unsigned int)xevent.xconfigure.height
1180                     != p_vout->p_sys->p_win->i_height )
1181             {
1182                 /* Update dimensions */
1183                 p_vout->i_changes |= VOUT_SIZE_CHANGE;
1184                 p_vout->p_sys->p_win->i_width = xevent.xconfigure.width;
1185                 p_vout->p_sys->p_win->i_height = xevent.xconfigure.height;
1186             }
1187         }
1188         /* Keyboard event */
1189         else if( xevent.type == KeyPress )
1190         {
1191             unsigned int state = xevent.xkey.state;
1192             KeySym x_key_symbol;
1193             char i_key;                                   /* ISO Latin-1 key */
1194
1195             /* We may have keys like F1 trough F12, ESC ... */
1196             x_key_symbol = XKeycodeToKeysym( p_vout->p_sys->p_display,
1197                                              xevent.xkey.keycode, 0 );
1198             val.i_int = ConvertKey( (int)x_key_symbol );
1199
1200             xevent.xkey.state &= ~ShiftMask;
1201             xevent.xkey.state &= ~ControlMask;
1202             xevent.xkey.state &= ~Mod1Mask;
1203
1204             if( !val.i_int &&
1205                 XLookupString( &xevent.xkey, &i_key, 1, NULL, NULL ) )
1206             {
1207                 /* "Normal Keys"
1208                  * The reason why I use this instead of XK_0 is that
1209                  * with XLookupString, we don't have to care about
1210                  * keymaps. */
1211                 val.i_int = i_key;
1212             }
1213
1214             if( val.i_int )
1215             {
1216                 if( state & ShiftMask )
1217                 {
1218                     val.i_int |= KEY_MODIFIER_SHIFT;
1219                 }
1220                 if( state & ControlMask )
1221                 {
1222                     val.i_int |= KEY_MODIFIER_CTRL;
1223                 }
1224                 if( state & Mod1Mask )
1225                 {
1226                     val.i_int |= KEY_MODIFIER_ALT;
1227                 }
1228                 var_Set( p_vout->p_libvlc, "key-pressed", val );
1229             }
1230         }
1231         /* Mouse click */
1232         else if( xevent.type == ButtonPress )
1233         {
1234             switch( ((XButtonEvent *)&xevent)->button )
1235             {
1236                 case Button1:
1237                     var_Get( p_vout, "mouse-button-down", &val );
1238                     val.i_int |= 1;
1239                     var_Set( p_vout, "mouse-button-down", val );
1240
1241                     /* detect double-clicks */
1242                     if( ( ((XButtonEvent *)&xevent)->time -
1243                           p_vout->p_sys->i_time_button_last_pressed ) < 300 )
1244                     {
1245                         p_vout->i_changes |= VOUT_FULLSCREEN_CHANGE;
1246                     }
1247
1248                     p_vout->p_sys->i_time_button_last_pressed =
1249                         ((XButtonEvent *)&xevent)->time;
1250                     break;
1251                 case Button2:
1252                     var_Get( p_vout, "mouse-button-down", &val );
1253                     val.i_int |= 2;
1254                     var_Set( p_vout, "mouse-button-down", val );
1255                     break;
1256
1257                 case Button3:
1258                     var_Get( p_vout, "mouse-button-down", &val );
1259                     val.i_int |= 4;
1260                     var_Set( p_vout, "mouse-button-down", val );
1261                     break;
1262
1263                 case Button4:
1264                     var_Get( p_vout, "mouse-button-down", &val );
1265                     val.i_int |= 8;
1266                     var_Set( p_vout, "mouse-button-down", val );
1267                     break;
1268
1269                 case Button5:
1270                     var_Get( p_vout, "mouse-button-down", &val );
1271                     val.i_int |= 16;
1272                     var_Set( p_vout, "mouse-button-down", val );
1273                     break;
1274             }
1275         }
1276         /* Mouse release */
1277         else if( xevent.type == ButtonRelease )
1278         {
1279             switch( ((XButtonEvent *)&xevent)->button )
1280             {
1281                 case Button1:
1282                     var_Get( p_vout, "mouse-button-down", &val );
1283                     val.i_int &= ~1;
1284                     var_Set( p_vout, "mouse-button-down", val );
1285
1286                     val.b_bool = VLC_TRUE;
1287                     var_Set( p_vout, "mouse-clicked", val );
1288                     break;
1289
1290                 case Button2:
1291                     {
1292                         playlist_t *p_playlist;
1293
1294                         var_Get( p_vout, "mouse-button-down", &val );
1295                         val.i_int &= ~2;
1296                         var_Set( p_vout, "mouse-button-down", val );
1297
1298                         p_playlist = vlc_object_find( p_vout,
1299                                                       VLC_OBJECT_PLAYLIST,
1300                                                       FIND_ANYWHERE );
1301                         if( p_playlist != NULL )
1302                         {
1303                             vlc_value_t val;
1304                             var_Get( p_playlist, "intf-show", &val );
1305                             val.b_bool = !val.b_bool;
1306                             var_Set( p_playlist, "intf-show", val );
1307                             vlc_object_release( p_playlist );
1308                         }
1309                     }
1310                     break;
1311
1312                 case Button3:
1313                     {
1314                         intf_thread_t *p_intf;
1315                         playlist_t *p_playlist;
1316
1317                         var_Get( p_vout, "mouse-button-down", &val );
1318                         val.i_int &= ~4;
1319                         var_Set( p_vout, "mouse-button-down", val );
1320                         p_intf = vlc_object_find( p_vout, VLC_OBJECT_INTF,
1321                                                           FIND_ANYWHERE );
1322                         if( p_intf )
1323                         {
1324                             p_intf->b_menu_change = 1;
1325                             vlc_object_release( p_intf );
1326                         }
1327
1328                         p_playlist = vlc_object_find( p_vout,
1329                                                       VLC_OBJECT_PLAYLIST,
1330                                                       FIND_ANYWHERE );
1331                         if( p_playlist != NULL )
1332                         {
1333                             vlc_value_t val; val.b_bool = VLC_TRUE;
1334                             var_Set( p_playlist, "intf-popupmenu", val );
1335                             vlc_object_release( p_playlist );
1336                         }
1337                     }
1338                     break;
1339
1340                 case Button4:
1341                     var_Get( p_vout, "mouse-button-down", &val );
1342                     val.i_int &= ~8;
1343                     var_Set( p_vout, "mouse-button-down", val );
1344                     break;
1345
1346                 case Button5:
1347                     var_Get( p_vout, "mouse-button-down", &val );
1348                     val.i_int &= ~16;
1349                     var_Set( p_vout, "mouse-button-down", val );
1350                     break;
1351
1352             }
1353         }
1354         /* Mouse move */
1355         else if( xevent.type == MotionNotify )
1356         {
1357             unsigned int i_width, i_height, i_x, i_y;
1358             vlc_value_t val;
1359
1360             /* somewhat different use for vout_PlacePicture:
1361              * here the values are needed to give to mouse coordinates
1362              * in the original picture space */
1363             vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width,
1364                                p_vout->p_sys->p_win->i_height,
1365                                &i_x, &i_y, &i_width, &i_height );
1366
1367             val.i_int = ( xevent.xmotion.x - i_x ) *
1368                 p_vout->fmt_in.i_visible_width / i_width +
1369                 p_vout->fmt_in.i_x_offset;
1370             var_Set( p_vout, "mouse-x", val );
1371             val.i_int = ( xevent.xmotion.y - i_y ) *
1372                 p_vout->fmt_in.i_visible_height / i_height +
1373                 p_vout->fmt_in.i_y_offset;
1374             var_Set( p_vout, "mouse-y", val );
1375
1376             val.b_bool = VLC_TRUE;
1377             var_Set( p_vout, "mouse-moved", val );
1378
1379             p_vout->p_sys->i_time_mouse_last_moved = mdate();
1380             if( ! p_vout->p_sys->b_mouse_pointer_visible )
1381             {
1382                 ToggleCursor( p_vout );
1383             }
1384         }
1385         else if( xevent.type == ReparentNotify /* XXX: why do we get this? */
1386                   || xevent.type == MapNotify
1387                   || xevent.type == UnmapNotify )
1388         {
1389             /* Ignore these events */
1390         }
1391         else /* Other events */
1392         {
1393             msg_Warn( p_vout, "unhandled event %d received", xevent.type );
1394         }
1395     }
1396
1397     /* Handle events for video output sub-window */
1398     while( XCheckWindowEvent( p_vout->p_sys->p_display,
1399                               p_vout->p_sys->p_win->video_window,
1400                               ExposureMask, &xevent ) == True )
1401     {
1402         /* Window exposed (only handled if stream playback is paused) */
1403         if( xevent.type == Expose )
1404         {
1405             if( ((XExposeEvent *)&xevent)->count == 0 )
1406             {
1407                 /* (if this is the last a collection of expose events...) */
1408 #if 0
1409                 if( p_vout->p_libvlc->p_input_bank->pp_input[0] != NULL )
1410                 {
1411                     if( PAUSE_S == p_vout->p_libvlc->p_input_bank->pp_input[0]
1412                                                    ->stream.control.i_status )
1413                     {
1414                         /* XVideoDisplay( p_vout )*/;
1415                     }
1416                 }
1417 #endif
1418             }
1419         }
1420     }
1421
1422     /* ClientMessage event - only WM_PROTOCOLS with WM_DELETE_WINDOW data
1423      * are handled - according to the man pages, the format is always 32
1424      * in this case */
1425     while( XCheckTypedEvent( p_vout->p_sys->p_display,
1426                              ClientMessage, &xevent ) )
1427     {
1428         if( (xevent.xclient.message_type == p_vout->p_sys->p_win->wm_protocols)
1429                && ((Atom)xevent.xclient.data.l[0]
1430                      == p_vout->p_sys->p_win->wm_delete_window ) )
1431         {
1432             /* the user wants to close the window */
1433             playlist_t * p_playlist =
1434                 (playlist_t *)vlc_object_find( p_vout, VLC_OBJECT_PLAYLIST,
1435                                                FIND_ANYWHERE );
1436             if( p_playlist != NULL )
1437             {
1438                 playlist_Stop( p_playlist );
1439                 vlc_object_release( p_playlist );
1440             }
1441         }
1442     }
1443
1444     /*
1445      * Fullscreen Change
1446      */
1447     if ( p_vout->i_changes & VOUT_FULLSCREEN_CHANGE )
1448     {
1449         vlc_value_t val;
1450
1451         /* Update the object variable and trigger callback */
1452         val.b_bool = !p_vout->b_fullscreen;
1453
1454         /*
1455          * FIXME FIXME FIXME FIXME: EXPLICIT HACK.
1456          * On the one hand, we cannot hold the lock while triggering a
1457          * callback, as it causes a deadlock with video-on-top handling.
1458          * On the other hand, we have to lock while triggering the
1459          * callback to:
1460          *  1/ make sure video-on-top remains in sync with fullscreen
1461          *    (i.e. unlocking creates a race condition if fullscreen is
1462          *     switched on and off VERY FAST).
1463          *  2/ avoid possible corruption bugs if another thread gets the
1464          *     mutex and modifies our data in-between.
1465          *
1466          * This is obviously contradictory. Correct solutions may include:
1467          *  - putting the fullscreen NAND video-on-top logic out of libvlc,
1468          *    back into the video output plugins (ugly code duplication...),
1469          *  - serializing fullscreen and video-on-top handling properly
1470          *    instead of doing it via the fullscreen callback. That's got to
1471          *    be the correct one.
1472          */
1473 #ifdef MODULE_NAME_IS_xvmc
1474         xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
1475 #endif
1476         vlc_mutex_unlock( &p_vout->p_sys->lock );
1477
1478         var_Set( p_vout, "fullscreen", val );
1479
1480         vlc_mutex_lock( &p_vout->p_sys->lock );
1481 #ifdef MODULE_NAME_IS_xvmc
1482         xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
1483 #endif
1484
1485         ToggleFullScreen( p_vout );
1486         p_vout->i_changes &= ~VOUT_FULLSCREEN_CHANGE;
1487     }
1488
1489     if( p_vout->i_changes & VOUT_CROP_CHANGE ||
1490         p_vout->i_changes & VOUT_ASPECT_CHANGE )
1491     {
1492         p_vout->i_changes &= ~VOUT_CROP_CHANGE;
1493         p_vout->i_changes &= ~VOUT_ASPECT_CHANGE;
1494
1495         p_vout->fmt_out.i_x_offset = p_vout->fmt_in.i_x_offset;
1496         p_vout->fmt_out.i_y_offset = p_vout->fmt_in.i_y_offset;
1497         p_vout->fmt_out.i_visible_width = p_vout->fmt_in.i_visible_width;
1498         p_vout->fmt_out.i_visible_height = p_vout->fmt_in.i_visible_height;
1499         p_vout->fmt_out.i_aspect = p_vout->fmt_in.i_aspect;
1500         p_vout->fmt_out.i_sar_num = p_vout->fmt_in.i_sar_num;
1501         p_vout->fmt_out.i_sar_den = p_vout->fmt_in.i_sar_den;
1502         p_vout->output.i_aspect = p_vout->fmt_in.i_aspect;
1503
1504         p_vout->i_changes |= VOUT_SIZE_CHANGE;
1505     }
1506
1507     /*
1508      * Size change
1509      *
1510      * (Needs to be placed after VOUT_FULLSREEN_CHANGE because we can activate
1511      *  the size flag inside the fullscreen routine)
1512      */
1513     if( p_vout->i_changes & VOUT_SIZE_CHANGE )
1514     {
1515         unsigned int i_width, i_height, i_x, i_y;
1516
1517         p_vout->i_changes &= ~VOUT_SIZE_CHANGE;
1518
1519 #ifdef MODULE_NAME_IS_x11
1520         /* We need to signal the vout thread about the size change because it
1521          * is doing the rescaling */
1522         p_vout->i_changes |= VOUT_SIZE_CHANGE;
1523 #endif
1524
1525         vout_PlacePicture( p_vout, p_vout->p_sys->p_win->i_width,
1526                            p_vout->p_sys->p_win->i_height,
1527                            &i_x, &i_y, &i_width, &i_height );
1528
1529         XMoveResizeWindow( p_vout->p_sys->p_display,
1530                            p_vout->p_sys->p_win->video_window,
1531                            i_x, i_y, i_width, i_height );
1532     }
1533
1534     /* Autohide Cursour */
1535     if( mdate() - p_vout->p_sys->i_time_mouse_last_moved > 2000000 )
1536     {
1537         /* Hide the mouse automatically */
1538         if( p_vout->p_sys->b_mouse_pointer_visible )
1539         {
1540             ToggleCursor( p_vout );
1541         }
1542     }
1543
1544 #ifdef MODULE_NAME_IS_xvmc
1545     xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
1546 #endif
1547     
1548 #ifdef HAVE_OSSO
1549     if ( p_vout->p_sys->p_octx != NULL ) {
1550         if ( p_vout->p_sys->i_backlight_on_counter == i_backlight_on_interval ) {
1551             if ( osso_display_blanking_pause( p_vout->p_sys->p_octx ) != OSSO_OK ) {
1552                 msg_Err( p_vout, "Could not disable backlight blanking" );
1553             } else {
1554                 msg_Dbg( p_vout, "Backlight blanking disabled" );
1555             }
1556             p_vout->p_sys->i_backlight_on_counter = 0;
1557         } else {
1558             p_vout->p_sys->i_backlight_on_counter ++;
1559         }
1560     }
1561 #endif
1562             
1563     vlc_mutex_unlock( &p_vout->p_sys->lock );
1564     return 0;
1565 }
1566
1567 /*****************************************************************************
1568  * EndVideo: terminate X11 video thread output method
1569  *****************************************************************************
1570  * Destroy the X11 XImages created by Init. It is called at the end of
1571  * the thread, but also each time the window is resized.
1572  *****************************************************************************/
1573 static void EndVideo( vout_thread_t *p_vout )
1574 {
1575     int i_index;
1576
1577     /* Free the direct buffers we allocated */
1578     for( i_index = I_OUTPUTPICTURES ; i_index ; )
1579     {
1580         i_index--;
1581         FreePicture( p_vout, PP_OUTPUTPICTURE[ i_index ] );
1582     }
1583 }
1584
1585 /* following functions are local */
1586
1587 /*****************************************************************************
1588  * CreateWindow: open and set-up X11 main window
1589  *****************************************************************************/
1590 static int CreateWindow( vout_thread_t *p_vout, x11_window_t *p_win )
1591 {
1592     XSizeHints              xsize_hints;
1593     XSetWindowAttributes    xwindow_attributes;
1594     XGCValues               xgcvalues;
1595     XEvent                  xevent;
1596
1597     vlc_bool_t              b_expose = VLC_FALSE;
1598     vlc_bool_t              b_configure_notify = VLC_FALSE;
1599     vlc_bool_t              b_map_notify = VLC_FALSE;
1600     vlc_value_t             val;
1601
1602     /* Prepare window manager hints and properties */
1603     p_win->wm_protocols =
1604              XInternAtom( p_vout->p_sys->p_display, "WM_PROTOCOLS", True );
1605     p_win->wm_delete_window =
1606              XInternAtom( p_vout->p_sys->p_display, "WM_DELETE_WINDOW", True );
1607
1608     /* Never have a 0-pixel-wide window */
1609     xsize_hints.min_width = 2;
1610     xsize_hints.min_height = 1;
1611
1612     /* Prepare window attributes */
1613     xwindow_attributes.backing_store = Always;       /* save the hidden part */
1614     xwindow_attributes.background_pixel = BlackPixel(p_vout->p_sys->p_display,
1615                                                      p_vout->p_sys->i_screen);
1616     xwindow_attributes.event_mask = ExposureMask | StructureNotifyMask;
1617
1618     if( !p_vout->b_fullscreen )
1619     {
1620         p_win->owner_window =
1621             (Window)vout_RequestWindow( p_vout, &p_win->i_x, &p_win->i_y,
1622                                         &p_win->i_width, &p_win->i_height );
1623
1624         xsize_hints.base_width  = xsize_hints.width = p_win->i_width;
1625         xsize_hints.base_height = xsize_hints.height = p_win->i_height;
1626         xsize_hints.flags       = PSize | PMinSize;
1627
1628         if( p_win->i_x >=0 || p_win->i_y >= 0 )
1629         {
1630             xsize_hints.x = p_win->i_x;
1631             xsize_hints.y = p_win->i_y;
1632             xsize_hints.flags |= PPosition;
1633         }
1634     }
1635     else
1636     {
1637         /* Fullscreen window size and position */
1638         p_win->owner_window = 0;
1639         p_win->i_x = p_win->i_y = 0;
1640         p_win->i_width =
1641             DisplayWidth( p_vout->p_sys->p_display, p_vout->p_sys->i_screen );
1642         p_win->i_height =
1643             DisplayHeight( p_vout->p_sys->p_display, p_vout->p_sys->i_screen );
1644     }
1645
1646     if( !p_win->owner_window )
1647     {
1648         /* Create the window and set hints - the window must receive
1649          * ConfigureNotify events, and until it is displayed, Expose and
1650          * MapNotify events. */
1651
1652         p_win->base_window =
1653             XCreateWindow( p_vout->p_sys->p_display,
1654                            DefaultRootWindow( p_vout->p_sys->p_display ),
1655                            p_win->i_x, p_win->i_y,
1656                            p_win->i_width, p_win->i_height,
1657                            0,
1658                            0, InputOutput, 0,
1659                            CWBackingStore | CWBackPixel | CWEventMask,
1660                            &xwindow_attributes );
1661
1662         var_Get( p_vout, "video-title", &val );
1663         if( !val.psz_string || !*val.psz_string )
1664         {
1665             XStoreName( p_vout->p_sys->p_display, p_win->base_window,
1666 #ifdef MODULE_NAME_IS_x11
1667                         VOUT_TITLE " (X11 output)"
1668 #elif defined(MODULE_NAME_IS_glx)
1669                         VOUT_TITLE " (GLX output)"
1670 #else
1671                         VOUT_TITLE " (XVideo output)"
1672 #endif
1673               );
1674         }
1675         else
1676         {
1677             XStoreName( p_vout->p_sys->p_display,
1678                         p_win->base_window, val.psz_string );
1679         }
1680         if( val.psz_string ) free( val.psz_string );
1681
1682         if( !p_vout->b_fullscreen )
1683         {
1684             /* Set window manager hints and properties: size hints, command,
1685              * window's name, and accepted protocols */
1686             XSetWMNormalHints( p_vout->p_sys->p_display,
1687                                p_win->base_window, &xsize_hints );
1688             XSetCommand( p_vout->p_sys->p_display, p_win->base_window,
1689                          p_vout->p_libvlc->ppsz_argv, p_vout->p_libvlc->i_argc );
1690
1691             if( !var_GetBool( p_vout, "video-deco") )
1692             {
1693                 Atom prop;
1694                 mwmhints_t mwmhints;
1695
1696                 mwmhints.flags = MWM_HINTS_DECORATIONS;
1697                 mwmhints.decorations = False;
1698
1699                 prop = XInternAtom( p_vout->p_sys->p_display, "_MOTIF_WM_HINTS",
1700                                     False );
1701
1702                 XChangeProperty( p_vout->p_sys->p_display,
1703                                  p_win->base_window,
1704                                  prop, prop, 32, PropModeReplace,
1705                                  (unsigned char *)&mwmhints,
1706                                  PROP_MWM_HINTS_ELEMENTS );
1707             }
1708         }
1709     }
1710     else
1711     {
1712         Window dummy1;
1713         int dummy2, dummy3;
1714         unsigned int dummy4, dummy5;
1715
1716         /* Select events we are interested in. */
1717         XSelectInput( p_vout->p_sys->p_display, p_win->owner_window,
1718                       StructureNotifyMask );
1719
1720         /* Get the parent window's geometry information */
1721         XGetGeometry( p_vout->p_sys->p_display, p_win->owner_window,
1722                       &dummy1, &dummy2, &dummy3,
1723                       &p_win->i_width,
1724                       &p_win->i_height,
1725                       &dummy4, &dummy5 );
1726
1727         /* We are already configured */
1728         b_configure_notify = VLC_TRUE;
1729
1730         /* From man XSelectInput: only one client at a time can select a
1731          * ButtonPress event, so we need to open a new window anyway. */
1732         p_win->base_window =
1733             XCreateWindow( p_vout->p_sys->p_display,
1734                            p_win->owner_window,
1735                            0, 0,
1736                            p_win->i_width, p_win->i_height,
1737                            0,
1738                            0, CopyFromParent, 0,
1739                            CWBackingStore | CWBackPixel | CWEventMask,
1740                            &xwindow_attributes );
1741     }
1742
1743     if( (p_win->wm_protocols == None)        /* use WM_DELETE_WINDOW */
1744         || (p_win->wm_delete_window == None)
1745         || !XSetWMProtocols( p_vout->p_sys->p_display, p_win->base_window,
1746                              &p_win->wm_delete_window, 1 ) )
1747     {
1748         /* WM_DELETE_WINDOW is not supported by window manager */
1749         msg_Warn( p_vout, "missing or bad window manager" );
1750     }
1751
1752     /* Creation of a graphic context that doesn't generate a GraphicsExpose
1753      * event when using functions like XCopyArea */
1754     xgcvalues.graphics_exposures = False;
1755     p_win->gc = XCreateGC( p_vout->p_sys->p_display,
1756                            p_win->base_window,
1757                            GCGraphicsExposures, &xgcvalues );
1758
1759     /* Send orders to server, and wait until window is displayed - three
1760      * events must be received: a MapNotify event, an Expose event allowing
1761      * drawing in the window, and a ConfigureNotify to get the window
1762      * dimensions. Once those events have been received, only
1763      * ConfigureNotify events need to be received. */
1764     XMapWindow( p_vout->p_sys->p_display, p_win->base_window );
1765     do
1766     {
1767         XWindowEvent( p_vout->p_sys->p_display, p_win->base_window,
1768                       SubstructureNotifyMask | StructureNotifyMask |
1769                       ExposureMask, &xevent);
1770         if( (xevent.type == Expose)
1771             && (xevent.xexpose.window == p_win->base_window) )
1772         {
1773             b_expose = VLC_TRUE;
1774             /* ConfigureNotify isn't sent if there isn't a window manager.
1775              * Expose should be the last event to be received so it should
1776              * be fine to assume we won't receive it anymore. */
1777             b_configure_notify = VLC_TRUE;
1778         }
1779         else if( (xevent.type == MapNotify)
1780                  && (xevent.xmap.window == p_win->base_window) )
1781         {
1782             b_map_notify = VLC_TRUE;
1783         }
1784         else if( (xevent.type == ConfigureNotify)
1785                  && (xevent.xconfigure.window == p_win->base_window) )
1786         {
1787             b_configure_notify = VLC_TRUE;
1788             p_win->i_width = xevent.xconfigure.width;
1789             p_win->i_height = xevent.xconfigure.height;
1790         }
1791     } while( !( b_expose && b_configure_notify && b_map_notify ) );
1792
1793     XSelectInput( p_vout->p_sys->p_display, p_win->base_window,
1794                   StructureNotifyMask | KeyPressMask |
1795                   ButtonPressMask | ButtonReleaseMask |
1796                   PointerMotionMask );
1797
1798 #ifdef MODULE_NAME_IS_x11
1799     if( XDefaultDepth(p_vout->p_sys->p_display, p_vout->p_sys->i_screen) == 8 )
1800     {
1801         /* Allocate a new palette */
1802         p_vout->p_sys->colormap =
1803             XCreateColormap( p_vout->p_sys->p_display,
1804                              DefaultRootWindow( p_vout->p_sys->p_display ),
1805                              DefaultVisual( p_vout->p_sys->p_display,
1806                                             p_vout->p_sys->i_screen ),
1807                              AllocAll );
1808
1809         xwindow_attributes.colormap = p_vout->p_sys->colormap;
1810         XChangeWindowAttributes( p_vout->p_sys->p_display, p_win->base_window,
1811                                  CWColormap, &xwindow_attributes );
1812     }
1813 #endif
1814
1815     /* Create video output sub-window. */
1816     p_win->video_window =  XCreateSimpleWindow(
1817                                       p_vout->p_sys->p_display,
1818                                       p_win->base_window, 0, 0,
1819                                       p_win->i_width, p_win->i_height,
1820                                       0,
1821                                       BlackPixel( p_vout->p_sys->p_display,
1822                                                   p_vout->p_sys->i_screen ),
1823                                       WhitePixel( p_vout->p_sys->p_display,
1824                                                   p_vout->p_sys->i_screen ) );
1825
1826     XSetWindowBackground( p_vout->p_sys->p_display, p_win->video_window,
1827                           BlackPixel( p_vout->p_sys->p_display,
1828                                       p_vout->p_sys->i_screen ) );
1829
1830     XMapWindow( p_vout->p_sys->p_display, p_win->video_window );
1831     XSelectInput( p_vout->p_sys->p_display, p_win->video_window,
1832                   ExposureMask );
1833
1834     /* make sure the video window will be centered in the next ManageVideo() */
1835     p_vout->i_changes |= VOUT_SIZE_CHANGE;
1836
1837     /* If the cursor was formerly blank than blank it again */
1838     if( !p_vout->p_sys->b_mouse_pointer_visible )
1839     {
1840         ToggleCursor( p_vout );
1841         ToggleCursor( p_vout );
1842     }
1843
1844     /* Do NOT use XFlush here ! */
1845     XSync( p_vout->p_sys->p_display, False );
1846
1847     /* At this stage, the window is open, displayed, and ready to
1848      * receive data */
1849     p_vout->p_sys->p_win = p_win;
1850
1851     return VLC_SUCCESS;
1852 }
1853
1854 /*****************************************************************************
1855  * DestroyWindow: destroy the window
1856  *****************************************************************************
1857  *
1858  *****************************************************************************/
1859 static void DestroyWindow( vout_thread_t *p_vout, x11_window_t *p_win )
1860 {
1861     /* Do NOT use XFlush here ! */
1862     XSync( p_vout->p_sys->p_display, False );
1863
1864     if( p_win->video_window != None )
1865         XDestroyWindow( p_vout->p_sys->p_display, p_win->video_window );
1866
1867     XFreeGC( p_vout->p_sys->p_display, p_win->gc );
1868
1869     XUnmapWindow( p_vout->p_sys->p_display, p_win->base_window );
1870     XDestroyWindow( p_vout->p_sys->p_display, p_win->base_window );
1871
1872     if( p_win->owner_window )
1873         vout_ReleaseWindow( p_vout, (void *)p_win->owner_window );
1874 }
1875
1876 /*****************************************************************************
1877  * NewPicture: allocate a picture
1878  *****************************************************************************
1879  * Returns 0 on success, -1 otherwise
1880  *****************************************************************************/
1881 static int NewPicture( vout_thread_t *p_vout, picture_t *p_pic )
1882 {
1883 #ifndef MODULE_NAME_IS_glx
1884
1885 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
1886     int i_plane;
1887 #endif
1888
1889     /* We know the chroma, allocate a buffer which will be used
1890      * directly by the decoder */
1891     p_pic->p_sys = malloc( sizeof( picture_sys_t ) );
1892
1893     if( p_pic->p_sys == NULL )
1894     {
1895         return -1;
1896     }
1897
1898 #ifdef MODULE_NAME_IS_xvmc
1899     p_pic->p_sys->p_vout = p_vout;
1900     p_pic->p_sys->xvmc_surf = NULL;
1901     p_pic->p_sys->xxmc_data.decoded = 0;
1902     p_pic->p_sys->xxmc_data.proc_xxmc_update_frame = xxmc_do_update_frame;
1903     p_pic->p_accel_data = &p_pic->p_sys->xxmc_data;
1904     p_pic->p_sys->nb_display = 0;
1905 #endif
1906
1907     /* Fill in picture_t fields */
1908     vout_InitPicture( VLC_OBJECT(p_vout), p_pic, p_vout->output.i_chroma,
1909                       p_vout->output.i_width, p_vout->output.i_height,
1910                       p_vout->output.i_aspect );
1911
1912 #ifdef HAVE_SYS_SHM_H
1913     if( p_vout->p_sys->b_shm )
1914     {
1915         /* Create image using XShm extension */
1916         p_pic->p_sys->p_image =
1917             CreateShmImage( p_vout, p_vout->p_sys->p_display,
1918 #   if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
1919                             p_vout->p_sys->i_xvport,
1920                             VLC2X11_FOURCC(p_vout->output.i_chroma),
1921 #   else
1922                             p_vout->p_sys->p_visual,
1923                             p_vout->p_sys->i_screen_depth,
1924 #   endif
1925                             &p_pic->p_sys->shminfo,
1926                             p_vout->output.i_width, p_vout->output.i_height );
1927     }
1928
1929     if( !p_vout->p_sys->b_shm || !p_pic->p_sys->p_image )
1930 #endif /* HAVE_SYS_SHM_H */
1931     {
1932         /* Create image without XShm extension */
1933         p_pic->p_sys->p_image =
1934             CreateImage( p_vout, p_vout->p_sys->p_display,
1935 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
1936                          p_vout->p_sys->i_xvport, 
1937                          VLC2X11_FOURCC(p_vout->output.i_chroma),
1938                          p_pic->format.i_bits_per_pixel,
1939 #else
1940                          p_vout->p_sys->p_visual,
1941                          p_vout->p_sys->i_screen_depth,
1942                          p_vout->p_sys->i_bytes_per_pixel,
1943 #endif
1944                          p_vout->output.i_width, p_vout->output.i_height );
1945
1946 #ifdef HAVE_SYS_SHM_H
1947         if( p_pic->p_sys->p_image && p_vout->p_sys->b_shm )
1948         {
1949             msg_Warn( p_vout, "couldn't create SHM image, disabling SHM" );
1950             p_vout->p_sys->b_shm = VLC_FALSE;
1951         }
1952 #endif /* HAVE_SYS_SHM_H */
1953     }
1954
1955     if( p_pic->p_sys->p_image == NULL )
1956     {
1957         free( p_pic->p_sys );
1958         return -1;
1959     }
1960
1961     switch( p_vout->output.i_chroma )
1962     {
1963 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
1964         case VLC_FOURCC('I','4','2','0'):
1965         case VLC_FOURCC('Y','V','1','2'):
1966         case VLC_FOURCC('Y','2','1','1'):
1967         case VLC_FOURCC('Y','U','Y','2'):
1968         case VLC_FOURCC('U','Y','V','Y'):
1969         case VLC_FOURCC('R','V','1','5'):
1970         case VLC_FOURCC('R','V','1','6'):
1971         case VLC_FOURCC('R','V','2','4'): /* Fixme: pixel pitch == 4 ? */
1972         case VLC_FOURCC('R','V','3','2'):
1973
1974             for( i_plane = 0; i_plane < p_pic->p_sys->p_image->num_planes;
1975                  i_plane++ )
1976             {
1977                 p_pic->p[i_plane].p_pixels = p_pic->p_sys->p_image->data
1978                     + p_pic->p_sys->p_image->offsets[i_plane];
1979                 p_pic->p[i_plane].i_pitch =
1980                     p_pic->p_sys->p_image->pitches[i_plane];
1981             }
1982             if( p_vout->output.i_chroma == VLC_FOURCC('Y','V','1','2') )
1983             {
1984                 /* U and V inverted compared to I420
1985                  * Fixme: this should be handled by the vout core */
1986                 p_pic->U_PIXELS = p_pic->p_sys->p_image->data
1987                     + p_pic->p_sys->p_image->offsets[2];
1988                 p_pic->V_PIXELS = p_pic->p_sys->p_image->data
1989                     + p_pic->p_sys->p_image->offsets[1];
1990             }
1991             break;
1992
1993 #else
1994         case VLC_FOURCC('R','G','B','2'):
1995         case VLC_FOURCC('R','V','1','6'):
1996         case VLC_FOURCC('R','V','1','5'):
1997         case VLC_FOURCC('R','V','2','4'):
1998         case VLC_FOURCC('R','V','3','2'):
1999
2000             p_pic->p->i_lines = p_pic->p_sys->p_image->height;
2001             p_pic->p->i_visible_lines = p_pic->p_sys->p_image->height;
2002             p_pic->p->p_pixels = p_pic->p_sys->p_image->data
2003                                   + p_pic->p_sys->p_image->xoffset;
2004             p_pic->p->i_pitch = p_pic->p_sys->p_image->bytes_per_line;
2005
2006             /* p_pic->p->i_pixel_pitch = 4 for RV24 but this should be set
2007              * properly by vout_InitPicture() */
2008             p_pic->p->i_visible_pitch = p_pic->p->i_pixel_pitch
2009                                          * p_pic->p_sys->p_image->width;
2010             break;
2011 #endif
2012
2013         default:
2014             /* Unknown chroma, tell the guy to get lost */
2015             IMAGE_FREE( p_pic->p_sys->p_image );
2016             free( p_pic->p_sys );
2017             msg_Err( p_vout, "never heard of chroma 0x%.8x (%4.4s)",
2018                      p_vout->output.i_chroma, (char*)&p_vout->output.i_chroma );
2019             p_pic->i_planes = 0;
2020             return -1;
2021     }
2022
2023 #endif /* !MODULE_NAME_IS_glx */
2024
2025     return 0;
2026 }
2027
2028 /*****************************************************************************
2029  * FreePicture: destroy a picture allocated with NewPicture
2030  *****************************************************************************
2031  * Destroy XImage AND associated data. If using Shm, detach shared memory
2032  * segment from server and process, then free it. The XDestroyImage manpage
2033  * says that both the image structure _and_ the data pointed to by the
2034  * image structure are freed, so no need to free p_image->data.
2035  *****************************************************************************/
2036 static void FreePicture( vout_thread_t *p_vout, picture_t *p_pic )
2037 {
2038     /* The order of operations is correct */
2039 #ifdef HAVE_SYS_SHM_H
2040     if( p_vout->p_sys->b_shm )
2041     {
2042         XShmDetach( p_vout->p_sys->p_display, &p_pic->p_sys->shminfo );
2043         IMAGE_FREE( p_pic->p_sys->p_image );
2044
2045         shmctl( p_pic->p_sys->shminfo.shmid, IPC_RMID, 0 );
2046         if( shmdt( p_pic->p_sys->shminfo.shmaddr ) )
2047         {
2048             msg_Err( p_vout, "cannot detach shared memory (%s)",
2049                              strerror(errno) );
2050         }
2051     }
2052     else
2053 #endif
2054     {
2055         IMAGE_FREE( p_pic->p_sys->p_image );
2056     }
2057
2058 #ifdef MODULE_NAME_IS_xvmc
2059     if( p_pic->p_sys->xvmc_surf != NULL )
2060     {
2061         xxmc_xvmc_free_surface(p_vout , p_pic->p_sys->xvmc_surf);
2062         p_pic->p_sys->xvmc_surf = NULL;
2063     }
2064 #endif
2065
2066     /* Do NOT use XFlush here ! */
2067     XSync( p_vout->p_sys->p_display, False );
2068
2069     free( p_pic->p_sys );
2070 }
2071
2072 /*****************************************************************************
2073  * ToggleFullScreen: Enable or disable full screen mode
2074  *****************************************************************************
2075  * This function will switch between fullscreen and window mode.
2076  *****************************************************************************/
2077 static void ToggleFullScreen ( vout_thread_t *p_vout )
2078 {
2079     Atom prop;
2080     XEvent xevent;
2081     mwmhints_t mwmhints;
2082     XSetWindowAttributes attributes;
2083
2084 #ifdef HAVE_XINERAMA
2085     int i_d1, i_d2;
2086 #endif
2087
2088     p_vout->b_fullscreen = !p_vout->b_fullscreen;
2089
2090     if( p_vout->b_fullscreen )
2091     {
2092         msg_Dbg( p_vout, "entering fullscreen mode" );
2093
2094         p_vout->p_sys->b_altfullscreen =
2095             config_GetInt( p_vout, MODULE_STRING "-altfullscreen" );
2096
2097         XUnmapWindow( p_vout->p_sys->p_display,
2098                       p_vout->p_sys->p_win->base_window );
2099
2100         p_vout->p_sys->p_win = &p_vout->p_sys->fullscreen_window;
2101
2102         CreateWindow( p_vout, p_vout->p_sys->p_win );
2103         XDestroyWindow( p_vout->p_sys->p_display,
2104                         p_vout->p_sys->fullscreen_window.video_window );
2105         XReparentWindow( p_vout->p_sys->p_display,
2106                          p_vout->p_sys->original_window.video_window,
2107                          p_vout->p_sys->fullscreen_window.base_window, 0, 0 );
2108         p_vout->p_sys->fullscreen_window.video_window =
2109             p_vout->p_sys->original_window.video_window;
2110
2111         /* To my knowledge there are two ways to create a borderless window.
2112          * There's the generic way which is to tell x to bypass the window
2113          * manager, but this creates problems with the focus of other
2114          * applications.
2115          * The other way is to use the motif property "_MOTIF_WM_HINTS" which
2116          * luckily seems to be supported by most window managers. */
2117         if( !p_vout->p_sys->b_altfullscreen )
2118         {
2119             mwmhints.flags = MWM_HINTS_DECORATIONS;
2120             mwmhints.decorations = False;
2121
2122             prop = XInternAtom( p_vout->p_sys->p_display, "_MOTIF_WM_HINTS",
2123                                 False );
2124             XChangeProperty( p_vout->p_sys->p_display,
2125                              p_vout->p_sys->p_win->base_window,
2126                              prop, prop, 32, PropModeReplace,
2127                              (unsigned char *)&mwmhints,
2128                              PROP_MWM_HINTS_ELEMENTS );
2129         }
2130         else
2131         {
2132             /* brute force way to remove decorations */
2133             attributes.override_redirect = True;
2134             XChangeWindowAttributes( p_vout->p_sys->p_display,
2135                                      p_vout->p_sys->p_win->base_window,
2136                                      CWOverrideRedirect,
2137                                      &attributes);
2138
2139             /* Make sure the change is effective */
2140             XReparentWindow( p_vout->p_sys->p_display,
2141                              p_vout->p_sys->p_win->base_window,
2142                              DefaultRootWindow( p_vout->p_sys->p_display ),
2143                              0, 0 );
2144         }
2145
2146         if( p_vout->p_sys->b_net_wm_state_fullscreen )
2147         {
2148             XClientMessageEvent event;
2149
2150             memset( &event, 0, sizeof( XClientMessageEvent ) );
2151
2152             event.type = ClientMessage;
2153             event.message_type = p_vout->p_sys->net_wm_state;
2154             event.display = p_vout->p_sys->p_display;
2155             event.window = p_vout->p_sys->p_win->base_window;
2156             event.format = 32;
2157             event.data.l[ 0 ] = 1; /* set property */
2158             event.data.l[ 1 ] = p_vout->p_sys->net_wm_state_fullscreen;
2159
2160             XSendEvent( p_vout->p_sys->p_display,
2161                         DefaultRootWindow( p_vout->p_sys->p_display ),
2162                         False, SubstructureRedirectMask,
2163                         (XEvent*)&event );
2164         }
2165
2166         /* Make sure the change is effective */
2167         XReparentWindow( p_vout->p_sys->p_display,
2168                          p_vout->p_sys->p_win->base_window,
2169                          DefaultRootWindow( p_vout->p_sys->p_display ),
2170                          0, 0 );
2171
2172 #ifdef HAVE_XINERAMA
2173         if( XineramaQueryExtension( p_vout->p_sys->p_display, &i_d1, &i_d2 ) &&
2174             XineramaIsActive( p_vout->p_sys->p_display ) )
2175         {
2176             XineramaScreenInfo *screens;   /* infos for xinerama */
2177             int i_num_screens;
2178
2179             msg_Dbg( p_vout, "using XFree Xinerama extension");
2180
2181 #define SCREEN p_vout->p_sys->p_win->i_screen
2182
2183             /* Get Information about Xinerama (num of screens) */
2184             screens = XineramaQueryScreens( p_vout->p_sys->p_display,
2185                                             &i_num_screens );
2186
2187             SCREEN = config_GetInt( p_vout,
2188                                         MODULE_STRING "-xineramascreen" );
2189
2190             /* just check that user has entered a good value */
2191             if( SCREEN >= i_num_screens || SCREEN < 0 )
2192             {
2193                 msg_Dbg( p_vout, "requested screen number invalid (%d/%d)", SCREEN, i_num_screens );
2194                 SCREEN = 0;
2195             }
2196
2197             /* Get the X/Y upper left corner coordinate of the above screen */
2198             p_vout->p_sys->p_win->i_x = screens[SCREEN].x_org;
2199             p_vout->p_sys->p_win->i_y = screens[SCREEN].y_org;
2200
2201             /* Set the Height/width to the screen resolution */
2202             p_vout->p_sys->p_win->i_width = screens[SCREEN].width;
2203             p_vout->p_sys->p_win->i_height = screens[SCREEN].height;
2204
2205             XFree(screens);
2206
2207 #undef SCREEN
2208
2209         }
2210         else
2211 #endif
2212         {
2213             /* The window wasn't necessarily created at the requested size */
2214             p_vout->p_sys->p_win->i_x = p_vout->p_sys->p_win->i_y = 0;
2215
2216 #ifdef HAVE_XF86VIDMODE
2217             XF86VidModeModeLine mode;
2218             int i_dummy;
2219
2220             if( XF86VidModeGetModeLine( p_vout->p_sys->p_display,
2221                                         p_vout->p_sys->i_screen, &i_dummy,
2222                                         &mode ) )
2223             {
2224                 p_vout->p_sys->p_win->i_width = mode.hdisplay;
2225                 p_vout->p_sys->p_win->i_height = mode.vdisplay;
2226
2227                 /* move cursor to the middle of the window to prevent
2228                  * unwanted display move if the display is smaller than the
2229                  * full desktop */
2230                 XWarpPointer( p_vout->p_sys->p_display, None,
2231                               p_vout->p_sys->p_win->base_window, 0, 0, 0, 0,
2232                               mode.hdisplay / 2 , mode.vdisplay / 2 );
2233                 /* force desktop view to upper left corner */
2234                 XF86VidModeSetViewPort( p_vout->p_sys->p_display,
2235                                         p_vout->p_sys->i_screen, 0, 0 );
2236             }
2237             else
2238 #endif
2239             {
2240                 p_vout->p_sys->p_win->i_width =
2241                     DisplayWidth( p_vout->p_sys->p_display,
2242                                 p_vout->p_sys->i_screen );
2243                 p_vout->p_sys->p_win->i_height =
2244                     DisplayHeight( p_vout->p_sys->p_display,
2245                                 p_vout->p_sys->i_screen );
2246             }
2247
2248         }
2249
2250         XMoveResizeWindow( p_vout->p_sys->p_display,
2251                            p_vout->p_sys->p_win->base_window,
2252                            p_vout->p_sys->p_win->i_x,
2253                            p_vout->p_sys->p_win->i_y,
2254                            p_vout->p_sys->p_win->i_width,
2255                            p_vout->p_sys->p_win->i_height );
2256
2257 #ifdef HAVE_XSP
2258         EnablePixelDoubling( p_vout );
2259 #endif
2260                 
2261     }
2262     else
2263     {
2264         msg_Dbg( p_vout, "leaving fullscreen mode" );
2265
2266 #ifdef HAVE_XSP
2267         DisablePixelDoubling( p_vout );
2268 #endif
2269
2270         XReparentWindow( p_vout->p_sys->p_display,
2271                          p_vout->p_sys->original_window.video_window,
2272                          p_vout->p_sys->original_window.base_window, 0, 0 );
2273
2274         p_vout->p_sys->fullscreen_window.video_window = None;
2275         DestroyWindow( p_vout, &p_vout->p_sys->fullscreen_window );
2276         p_vout->p_sys->p_win = &p_vout->p_sys->original_window;
2277
2278         XMapWindow( p_vout->p_sys->p_display,
2279                     p_vout->p_sys->p_win->base_window );
2280     }
2281
2282     /* Unfortunately, using XSync() here is not enough to ensure the
2283      * window has already been mapped because the XMapWindow() request
2284      * has not necessarily been sent directly to our window (remember,
2285      * the call is first redirected to the window manager) */
2286     do
2287     {
2288         XWindowEvent( p_vout->p_sys->p_display,
2289                       p_vout->p_sys->p_win->base_window,
2290                       StructureNotifyMask, &xevent );
2291     } while( xevent.type != MapNotify );
2292
2293     /* Be careful, this can generate a BadMatch error if the window is not
2294      * already mapped by the server (see above) */
2295     XSetInputFocus(p_vout->p_sys->p_display,
2296                    p_vout->p_sys->p_win->base_window,
2297                    RevertToParent,
2298                    CurrentTime);
2299
2300     /* signal that the size needs to be updated */
2301     p_vout->i_changes |= VOUT_SIZE_CHANGE;
2302 }
2303
2304 /*****************************************************************************
2305  * EnableXScreenSaver: enable screen saver
2306  *****************************************************************************
2307  * This function enables the screen saver on a display after it has been
2308  * disabled by XDisableScreenSaver.
2309  * FIXME: what happens if multiple vlc sessions are running at the same
2310  *        time ???
2311  *****************************************************************************/
2312 static void EnableXScreenSaver( vout_thread_t *p_vout )
2313 {
2314 #ifdef DPMSINFO_IN_DPMS_H
2315     int dummy;
2316 #endif
2317
2318     if( p_vout->p_sys->i_ss_timeout )
2319     {
2320         XSetScreenSaver( p_vout->p_sys->p_display, p_vout->p_sys->i_ss_timeout,
2321                          p_vout->p_sys->i_ss_interval,
2322                          p_vout->p_sys->i_ss_blanking,
2323                          p_vout->p_sys->i_ss_exposure );
2324     }
2325
2326     /* Restore DPMS settings */
2327 #ifdef DPMSINFO_IN_DPMS_H
2328     if( DPMSQueryExtension( p_vout->p_sys->p_display, &dummy, &dummy ) )
2329     {
2330         if( p_vout->p_sys->b_ss_dpms )
2331         {
2332             DPMSEnable( p_vout->p_sys->p_display );
2333         }
2334     }
2335 #endif
2336 }
2337
2338 /*****************************************************************************
2339  * DisableXScreenSaver: disable screen saver
2340  *****************************************************************************
2341  * See XEnableXScreenSaver
2342  *****************************************************************************/
2343 static void DisableXScreenSaver( vout_thread_t *p_vout )
2344 {
2345 #ifdef DPMSINFO_IN_DPMS_H
2346     int dummy;
2347 #endif
2348
2349     /* Save screen saver information */
2350     XGetScreenSaver( p_vout->p_sys->p_display, &p_vout->p_sys->i_ss_timeout,
2351                      &p_vout->p_sys->i_ss_interval,
2352                      &p_vout->p_sys->i_ss_blanking,
2353                      &p_vout->p_sys->i_ss_exposure );
2354
2355     /* Disable screen saver */
2356     if( p_vout->p_sys->i_ss_timeout )
2357     {
2358         XSetScreenSaver( p_vout->p_sys->p_display, 0,
2359                          p_vout->p_sys->i_ss_interval,
2360                          p_vout->p_sys->i_ss_blanking,
2361                          p_vout->p_sys->i_ss_exposure );
2362     }
2363
2364     /* Disable DPMS */
2365 #ifdef DPMSINFO_IN_DPMS_H
2366     if( DPMSQueryExtension( p_vout->p_sys->p_display, &dummy, &dummy ) )
2367     {
2368         CARD16 unused;
2369         /* Save DPMS current state */
2370         DPMSInfo( p_vout->p_sys->p_display, &unused,
2371                   &p_vout->p_sys->b_ss_dpms );
2372         DPMSDisable( p_vout->p_sys->p_display );
2373    }
2374 #endif
2375 }
2376
2377 /*****************************************************************************
2378  * CreateCursor: create a blank mouse pointer
2379  *****************************************************************************/
2380 static void CreateCursor( vout_thread_t *p_vout )
2381 {
2382     XColor cursor_color;
2383
2384     p_vout->p_sys->cursor_pixmap =
2385         XCreatePixmap( p_vout->p_sys->p_display,
2386                        DefaultRootWindow( p_vout->p_sys->p_display ),
2387                        1, 1, 1 );
2388
2389     XParseColor( p_vout->p_sys->p_display,
2390                  XCreateColormap( p_vout->p_sys->p_display,
2391                                   DefaultRootWindow(
2392                                                     p_vout->p_sys->p_display ),
2393                                   DefaultVisual(
2394                                                 p_vout->p_sys->p_display,
2395                                                 p_vout->p_sys->i_screen ),
2396                                   AllocNone ),
2397                  "black", &cursor_color );
2398
2399     p_vout->p_sys->blank_cursor =
2400         XCreatePixmapCursor( p_vout->p_sys->p_display,
2401                              p_vout->p_sys->cursor_pixmap,
2402                              p_vout->p_sys->cursor_pixmap,
2403                              &cursor_color, &cursor_color, 1, 1 );
2404 }
2405
2406 /*****************************************************************************
2407  * DestroyCursor: destroy the blank mouse pointer
2408  *****************************************************************************/
2409 static void DestroyCursor( vout_thread_t *p_vout )
2410 {
2411     XFreePixmap( p_vout->p_sys->p_display, p_vout->p_sys->cursor_pixmap );
2412 }
2413
2414 /*****************************************************************************
2415  * ToggleCursor: hide or show the mouse pointer
2416  *****************************************************************************
2417  * This function hides the X pointer if it is visible by setting the pointer
2418  * sprite to a blank one. To show it again, we disable the sprite.
2419  *****************************************************************************/
2420 static void ToggleCursor( vout_thread_t *p_vout )
2421 {
2422     if( p_vout->p_sys->b_mouse_pointer_visible )
2423     {
2424         XDefineCursor( p_vout->p_sys->p_display,
2425                        p_vout->p_sys->p_win->base_window,
2426                        p_vout->p_sys->blank_cursor );
2427         p_vout->p_sys->b_mouse_pointer_visible = 0;
2428     }
2429     else
2430     {
2431         XUndefineCursor( p_vout->p_sys->p_display,
2432                          p_vout->p_sys->p_win->base_window );
2433         p_vout->p_sys->b_mouse_pointer_visible = 1;
2434     }
2435 }
2436
2437 #if defined(MODULE_NAME_IS_xvideo) || defined(MODULE_NAME_IS_xvmc)
2438 /*****************************************************************************
2439  * XVideoGetPort: get YUV12 port
2440  *****************************************************************************/
2441 static int XVideoGetPort( vout_thread_t *p_vout,
2442                           vlc_fourcc_t i_chroma, vlc_fourcc_t *pi_newchroma )
2443 {
2444     XvAdaptorInfo *p_adaptor;
2445     unsigned int i;
2446     unsigned int i_adaptor, i_num_adaptors;
2447     int i_requested_adaptor;
2448     int i_selected_port;
2449
2450     switch( XvQueryExtension( p_vout->p_sys->p_display, &i, &i, &i, &i, &i ) )
2451     {
2452         case Success:
2453             break;
2454
2455         case XvBadExtension:
2456             msg_Warn( p_vout, "XvBadExtension" );
2457             return -1;
2458
2459         case XvBadAlloc:
2460             msg_Warn( p_vout, "XvBadAlloc" );
2461             return -1;
2462
2463         default:
2464             msg_Warn( p_vout, "XvQueryExtension failed" );
2465             return -1;
2466     }
2467
2468     switch( XvQueryAdaptors( p_vout->p_sys->p_display,
2469                              DefaultRootWindow( p_vout->p_sys->p_display ),
2470                              &i_num_adaptors, &p_adaptor ) )
2471     {
2472         case Success:
2473             break;
2474
2475         case XvBadExtension:
2476             msg_Warn( p_vout, "XvBadExtension for XvQueryAdaptors" );
2477             return -1;
2478
2479         case XvBadAlloc:
2480             msg_Warn( p_vout, "XvBadAlloc for XvQueryAdaptors" );
2481             return -1;
2482
2483         default:
2484             msg_Warn( p_vout, "XvQueryAdaptors failed" );
2485             return -1;
2486     }
2487
2488     i_selected_port = -1;
2489 #ifdef MODULE_NAME_IS_xvmc
2490     i_requested_adaptor = config_GetInt( p_vout, "xvmc-adaptor" );
2491 #else
2492     i_requested_adaptor = config_GetInt( p_vout, "xvideo-adaptor" );
2493 #endif
2494     for( i_adaptor = 0; i_adaptor < i_num_adaptors; ++i_adaptor )
2495     {
2496         XvImageFormatValues *p_formats;
2497         int i_format, i_num_formats;
2498         int i_port;
2499
2500         /* If we requested an adaptor and it's not this one, we aren't
2501          * interested */
2502         if( i_requested_adaptor != -1 && ((int)i_adaptor != i_requested_adaptor) )
2503         {
2504             continue;
2505         }
2506
2507         /* If the adaptor doesn't have the required properties, skip it */
2508         if( !( p_adaptor[ i_adaptor ].type & XvInputMask ) ||
2509             !( p_adaptor[ i_adaptor ].type & XvImageMask ) )
2510         {
2511             continue;
2512         }
2513
2514         /* Check that adaptor supports our requested format... */
2515         p_formats = XvListImageFormats( p_vout->p_sys->p_display,
2516                                         p_adaptor[i_adaptor].base_id,
2517                                         &i_num_formats );
2518
2519         for( i_format = 0;
2520              i_format < i_num_formats && ( i_selected_port == -1 );
2521              i_format++ )
2522         {
2523             XvAttribute     *p_attr;
2524             int             i_attr, i_num_attributes;
2525
2526             /* If this is not the format we want, or at least a
2527              * similar one, forget it */
2528             if( !vout_ChromaCmp( p_formats[ i_format ].id, i_chroma ) )
2529             {
2530                 continue;
2531             }
2532
2533             /* Look for the first available port supporting this format */
2534             for( i_port = p_adaptor[i_adaptor].base_id;
2535                  ( i_port < (int)(p_adaptor[i_adaptor].base_id
2536                                    + p_adaptor[i_adaptor].num_ports) )
2537                    && ( i_selected_port == -1 );
2538                  i_port++ )
2539             {
2540                 if( XvGrabPort( p_vout->p_sys->p_display, i_port, CurrentTime )
2541                      == Success )
2542                 {
2543                     i_selected_port = i_port;
2544                     *pi_newchroma = p_formats[ i_format ].id;
2545                 }
2546             }
2547
2548             /* If no free port was found, forget it */
2549             if( i_selected_port == -1 )
2550             {
2551                 continue;
2552             }
2553
2554             /* If we found a port, print information about it */
2555             msg_Dbg( p_vout, "adaptor %i, port %i, format 0x%x (%4.4s) %s",
2556                      i_adaptor, i_selected_port, p_formats[ i_format ].id,
2557                      (char *)&p_formats[ i_format ].id,
2558                      ( p_formats[ i_format ].format == XvPacked ) ?
2559                          "packed" : "planar" );
2560
2561             /* Make sure XV_AUTOPAINT_COLORKEY is set */
2562             p_attr = XvQueryPortAttributes( p_vout->p_sys->p_display,
2563                                             i_selected_port,
2564                                             &i_num_attributes );
2565
2566             for( i_attr = 0; i_attr < i_num_attributes; i_attr++ )
2567             {
2568                 if( !strcmp( p_attr[i_attr].name, "XV_AUTOPAINT_COLORKEY" ) )
2569                 {
2570                     const Atom autopaint =
2571                         XInternAtom( p_vout->p_sys->p_display,
2572                                      "XV_AUTOPAINT_COLORKEY", False );
2573                     XvSetPortAttribute( p_vout->p_sys->p_display,
2574                                         i_selected_port, autopaint, 1 );
2575                     break;
2576                 }
2577             }
2578
2579             if( p_attr != NULL )
2580             {
2581                 XFree( p_attr );
2582             }
2583         }
2584
2585         if( p_formats != NULL )
2586         {
2587             XFree( p_formats );
2588         }
2589
2590     }
2591
2592     if( i_num_adaptors > 0 )
2593     {
2594         XvFreeAdaptorInfo( p_adaptor );
2595     }
2596
2597     if( i_selected_port == -1 )
2598     {
2599         int i_chroma_tmp = X112VLC_FOURCC( i_chroma );
2600         if( i_requested_adaptor == -1 )
2601         {
2602             msg_Warn( p_vout, "no free XVideo port found for format "
2603                       "0x%.8x (%4.4s)", i_chroma_tmp, (char*)&i_chroma_tmp );
2604         }
2605         else
2606         {
2607             msg_Warn( p_vout, "XVideo adaptor %i does not have a free "
2608                       "XVideo port for format 0x%.8x (%4.4s)",
2609                       i_requested_adaptor, i_chroma_tmp, (char*)&i_chroma_tmp );
2610         }
2611     }
2612
2613     return i_selected_port;
2614 }
2615
2616 /*****************************************************************************
2617  * XVideoReleasePort: release YUV12 port
2618  *****************************************************************************/
2619 static void XVideoReleasePort( vout_thread_t *p_vout, int i_port )
2620 {
2621     XvUngrabPort( p_vout->p_sys->p_display, i_port, CurrentTime );
2622 }
2623 #endif
2624
2625 /*****************************************************************************
2626  * InitDisplay: open and initialize X11 device
2627  *****************************************************************************
2628  * Create a window according to video output given size, and set other
2629  * properties according to the display properties.
2630  *****************************************************************************/
2631 static int InitDisplay( vout_thread_t *p_vout )
2632 {
2633 #ifdef MODULE_NAME_IS_x11
2634     XPixmapFormatValues *       p_formats;                 /* pixmap formats */
2635     XVisualInfo *               p_xvisual;            /* visuals information */
2636     XVisualInfo                 xvisual_template;         /* visual template */
2637     int                         i_count, i;                    /* array size */
2638 #endif
2639
2640 #ifdef HAVE_SYS_SHM_H
2641     p_vout->p_sys->b_shm = 0;
2642
2643     if( config_GetInt( p_vout, MODULE_STRING "-shm" ) )
2644     {
2645 #   ifdef __APPLE__
2646         /* FIXME: As of 2001-03-16, XFree4 for MacOS X does not support Xshm */
2647 #   else
2648         p_vout->p_sys->b_shm =
2649                   ( XShmQueryExtension( p_vout->p_sys->p_display ) == True );
2650 #   endif
2651
2652         if( !p_vout->p_sys->b_shm )
2653         {
2654             msg_Warn( p_vout, "XShm video extension is unavailable" );
2655         }
2656     }
2657     else
2658     {
2659         msg_Dbg( p_vout, "disabling XShm video extension" );
2660     }
2661
2662 #else
2663     msg_Warn( p_vout, "XShm video extension is unavailable" );
2664
2665 #endif
2666
2667 #ifdef MODULE_NAME_IS_xvideo
2668     /* XXX The brightness and contrast values should be read from environment
2669      * XXX variables... */
2670 #if 0
2671     XVideoSetAttribute( p_vout, "XV_BRIGHTNESS", 0.5 );
2672     XVideoSetAttribute( p_vout, "XV_CONTRAST",   0.5 );
2673 #endif
2674 #endif
2675
2676 #ifdef MODULE_NAME_IS_x11
2677     /* Initialize structure */
2678     p_vout->p_sys->i_screen = DefaultScreen( p_vout->p_sys->p_display );
2679
2680     /* Get screen depth */
2681     p_vout->p_sys->i_screen_depth = XDefaultDepth( p_vout->p_sys->p_display,
2682                                                    p_vout->p_sys->i_screen );
2683     switch( p_vout->p_sys->i_screen_depth )
2684     {
2685     case 8:
2686         /*
2687          * Screen depth is 8bpp. Use PseudoColor visual with private colormap.
2688          */
2689         xvisual_template.screen =   p_vout->p_sys->i_screen;
2690         xvisual_template.class =    DirectColor;
2691         p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
2692                                     VisualScreenMask | VisualClassMask,
2693                                     &xvisual_template, &i_count );
2694         if( p_xvisual == NULL )
2695         {
2696             msg_Err( p_vout, "no PseudoColor visual available" );
2697             return VLC_EGENERIC;
2698         }
2699         p_vout->p_sys->i_bytes_per_pixel = 1;
2700         p_vout->output.pf_setpalette = SetPalette;
2701         break;
2702     case 15:
2703     case 16:
2704     case 24:
2705     default:
2706         /*
2707          * Screen depth is higher than 8bpp. TrueColor visual is used.
2708          */
2709         xvisual_template.screen =   p_vout->p_sys->i_screen;
2710         xvisual_template.class =    TrueColor;
2711 /* In some cases, we get a truecolor class adaptor that has a different
2712    color depth. So try to get a real true color one first */
2713         xvisual_template.depth =    p_vout->p_sys->i_screen_depth;
2714
2715         p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
2716                                     VisualScreenMask | VisualClassMask |
2717                                     VisualDepthMask,
2718                                     &xvisual_template, &i_count );
2719         if( p_xvisual == NULL )
2720         {
2721             msg_Warn( p_vout, "No screen matching the required color depth" );
2722             p_xvisual = XGetVisualInfo( p_vout->p_sys->p_display,
2723                                     VisualScreenMask | VisualClassMask,
2724                                     &xvisual_template, &i_count );
2725             if( p_xvisual == NULL )
2726             {
2727
2728                 msg_Err( p_vout, "no TrueColor visual available" );
2729                 return VLC_EGENERIC;
2730             }
2731         }
2732
2733         p_vout->output.i_rmask = p_xvisual->red_mask;
2734         p_vout->output.i_gmask = p_xvisual->green_mask;
2735         p_vout->output.i_bmask = p_xvisual->blue_mask;
2736
2737         /* There is no difference yet between 3 and 4 Bpp. The only way
2738          * to find the actual number of bytes per pixel is to list supported
2739          * pixmap formats. */
2740         p_formats = XListPixmapFormats( p_vout->p_sys->p_display, &i_count );
2741         p_vout->p_sys->i_bytes_per_pixel = 0;
2742
2743         for( i = 0; i < i_count; i++ )
2744         {
2745             /* Under XFree4.0, the list contains pixmap formats available
2746              * through all video depths ; so we have to check against current
2747              * depth. */
2748             if( p_formats[i].depth == (int)p_vout->p_sys->i_screen_depth )
2749             {
2750                 if( p_formats[i].bits_per_pixel / 8
2751                         > (int)p_vout->p_sys->i_bytes_per_pixel )
2752                 {
2753                     p_vout->p_sys->i_bytes_per_pixel =
2754                         p_formats[i].bits_per_pixel / 8;
2755                 }
2756             }
2757         }
2758         if( p_formats ) XFree( p_formats );
2759
2760         break;
2761     }
2762     p_vout->p_sys->p_visual = p_xvisual->visual;
2763     XFree( p_xvisual );
2764 #endif
2765
2766     return VLC_SUCCESS;
2767 }
2768
2769 #ifdef HAVE_SYS_SHM_H
2770 /*****************************************************************************
2771  * CreateShmImage: create an XImage or XvImage using shared memory extension
2772  *****************************************************************************
2773  * Prepare an XImage or XvImage for display function.
2774  * The order of the operations respects the recommandations of the mit-shm
2775  * document by J.Corbet and K.Packard. Most of the parameters were copied from
2776  * there. See http://ftp.xfree86.org/pub/XFree86/4.0/doc/mit-shm.TXT
2777  *****************************************************************************/
2778 static IMAGE_TYPE * CreateShmImage( vout_thread_t *p_vout,
2779                                     Display* p_display, EXTRA_ARGS_SHM,
2780                                     int i_width, int i_height )
2781 {
2782     IMAGE_TYPE *p_image;
2783     Status result;
2784
2785     /* Create XImage / XvImage */
2786 #ifdef MODULE_NAME_IS_xvideo
2787
2788     /* Make sure the buffer is aligned to multiple of 16 */
2789     i_height = ( i_height + 15 ) >> 4 << 4;
2790     i_width = ( i_width + 15 ) >> 4 << 4;
2791
2792     p_image = XvShmCreateImage( p_display, i_xvport, i_chroma, 0,
2793                                 i_width, i_height, p_shm );
2794 #elif defined(MODULE_NAME_IS_xvmc)
2795     p_image = XvShmCreateImage( p_display, i_xvport, i_chroma, 0,
2796                                 i_width, i_height, p_shm );
2797 #else
2798     p_image = XShmCreateImage( p_display, p_visual, i_depth, ZPixmap, 0,
2799                                p_shm, i_width, i_height );
2800 #endif
2801     if( p_image == NULL )
2802     {
2803         msg_Err( p_vout, "image creation failed" );
2804         return NULL;
2805     }
2806
2807     /* Allocate shared memory segment - 0776 set the access permission
2808      * rights (like umask), they are not yet supported by all X servers */
2809     p_shm->shmid = shmget( IPC_PRIVATE, DATA_SIZE(p_image), IPC_CREAT | 0776 );
2810     if( p_shm->shmid < 0 )
2811     {
2812         msg_Err( p_vout, "cannot allocate shared image data (%s)",
2813                          strerror( errno ) );
2814         IMAGE_FREE( p_image );
2815         return NULL;
2816     }
2817
2818     /* Attach shared memory segment to process (read/write) */
2819     p_shm->shmaddr = p_image->data = shmat( p_shm->shmid, 0, 0 );
2820     if(! p_shm->shmaddr )
2821     {
2822         msg_Err( p_vout, "cannot attach shared memory (%s)",
2823                          strerror(errno));
2824         IMAGE_FREE( p_image );
2825         shmctl( p_shm->shmid, IPC_RMID, 0 );
2826         return NULL;
2827     }
2828
2829     /* Read-only data. We won't be using XShmGetImage */
2830     p_shm->readOnly = True;
2831
2832     /* Attach shared memory segment to X server */
2833     XSynchronize( p_display, True );
2834     b_shm = VLC_TRUE;
2835     result = XShmAttach( p_display, p_shm );
2836     if( result == False || !b_shm )
2837     {
2838         msg_Err( p_vout, "cannot attach shared memory to X server" );
2839         IMAGE_FREE( p_image );
2840         shmctl( p_shm->shmid, IPC_RMID, 0 );
2841         shmdt( p_shm->shmaddr );
2842         return NULL;
2843     }
2844     XSynchronize( p_display, False );
2845
2846     /* Send image to X server. This instruction is required, since having
2847      * built a Shm XImage and not using it causes an error on XCloseDisplay,
2848      * and remember NOT to use XFlush ! */
2849     XSync( p_display, False );
2850
2851 #if 0
2852     /* Mark the shm segment to be removed when there are no more
2853      * attachements, so it is automatic on process exit or after shmdt */
2854     shmctl( p_shm->shmid, IPC_RMID, 0 );
2855 #endif
2856
2857     return p_image;
2858 }
2859 #endif
2860
2861 /*****************************************************************************
2862  * CreateImage: create an XImage or XvImage
2863  *****************************************************************************
2864  * Create a simple image used as a buffer.
2865  *****************************************************************************/
2866 static IMAGE_TYPE * CreateImage( vout_thread_t *p_vout,
2867                                  Display *p_display, EXTRA_ARGS,
2868                                  int i_width, int i_height )
2869 {
2870     byte_t *    p_data;                           /* image data storage zone */
2871     IMAGE_TYPE *p_image;
2872 #ifdef MODULE_NAME_IS_x11
2873     int         i_quantum;                     /* XImage quantum (see below) */
2874     int         i_bytes_per_line;
2875 #endif
2876
2877     /* Allocate memory for image */
2878 #ifdef MODULE_NAME_IS_xvideo
2879
2880     /* Make sure the buffer is aligned to multiple of 16 */
2881     i_height = ( i_height + 15 ) >> 4 << 4;
2882     i_width = ( i_width + 15 ) >> 4 << 4;
2883
2884     p_data = (byte_t *) malloc( i_width * i_height * i_bits_per_pixel / 8 );
2885 #elif defined(MODULE_NAME_IS_x11)
2886     i_bytes_per_line = i_width * i_bytes_per_pixel;
2887     p_data = (byte_t *) malloc( i_bytes_per_line * i_height );
2888 #endif
2889     if( !p_data )
2890     {
2891         msg_Err( p_vout, "out of memory" );
2892         return NULL;
2893     }
2894
2895 #ifdef MODULE_NAME_IS_x11
2896     /* Optimize the quantum of a scanline regarding its size - the quantum is
2897        a diviser of the number of bits between the start of two scanlines. */
2898     if( i_bytes_per_line & 0xf )
2899     {
2900         i_quantum = 0x8;
2901     }
2902     else if( i_bytes_per_line & 0x10 )
2903     {
2904         i_quantum = 0x10;
2905     }
2906     else
2907     {
2908         i_quantum = 0x20;
2909     }
2910 #endif
2911
2912     /* Create XImage. p_data will be automatically freed */
2913 #ifdef MODULE_NAME_IS_xvideo
2914     p_image = XvCreateImage( p_display, i_xvport, i_chroma,
2915                              (char *)p_data, i_width, i_height );
2916 #elif defined(MODULE_NAME_IS_x11)
2917     p_image = XCreateImage( p_display, p_visual, i_depth, ZPixmap, 0,
2918                             (char *)p_data, i_width, i_height, i_quantum, 0 );
2919 #endif
2920     if( p_image == NULL )
2921     {
2922         msg_Err( p_vout, "XCreateImage() failed" );
2923         free( p_data );
2924         return NULL;
2925     }
2926
2927     return p_image;
2928 }
2929
2930 /*****************************************************************************
2931  * X11ErrorHandler: replace error handler so we can intercept some of them
2932  *****************************************************************************/
2933 static int X11ErrorHandler( Display * display, XErrorEvent * event )
2934 {
2935     switch( event->request_code )
2936     {
2937     case X_SetInputFocus:
2938         /* Ignore errors on XSetInputFocus()
2939          * (they happen when a window is not yet mapped) */
2940         return 0;
2941
2942     case 150: /* MIT-SHM */
2943     case 146: /* MIT-SHM too, what gives? */
2944         if( event->minor_code == X_ShmAttach )
2945         {
2946             b_shm = VLC_FALSE;
2947             return 0;
2948         }
2949         break;
2950     }
2951
2952     XSetErrorHandler(NULL);
2953     return (XSetErrorHandler(X11ErrorHandler))( display, event );
2954 }
2955
2956 #ifdef MODULE_NAME_IS_x11
2957 /*****************************************************************************
2958  * SetPalette: sets an 8 bpp palette
2959  *****************************************************************************
2960  * This function sets the palette given as an argument. It does not return
2961  * anything, but could later send information on which colors it was unable
2962  * to set.
2963  *****************************************************************************/
2964 static void SetPalette( vout_thread_t *p_vout,
2965                         uint16_t *red, uint16_t *green, uint16_t *blue )
2966 {
2967     int i;
2968     XColor p_colors[255];
2969
2970     /* allocate palette */
2971     for( i = 0; i < 255; i++ )
2972     {
2973         /* kludge: colors are indexed reversely because color 255 seems
2974          * to be reserved for black even if we try to set it to white */
2975         p_colors[ i ].pixel = 255 - i;
2976         p_colors[ i ].pad   = 0;
2977         p_colors[ i ].flags = DoRed | DoGreen | DoBlue;
2978         p_colors[ i ].red   = red[ 255 - i ];
2979         p_colors[ i ].blue  = blue[ 255 - i ];
2980         p_colors[ i ].green = green[ 255 - i ];
2981     }
2982
2983     XStoreColors( p_vout->p_sys->p_display,
2984                   p_vout->p_sys->colormap, p_colors, 255 );
2985 }
2986 #endif
2987
2988 /*****************************************************************************
2989  * Control: control facility for the vout
2990  *****************************************************************************/
2991 static int Control( vout_thread_t *p_vout, int i_query, va_list args )
2992 {
2993     vlc_bool_t b_arg;
2994     unsigned int i_width, i_height;
2995     unsigned int *pi_width, *pi_height;
2996     Drawable d = 0;
2997
2998     switch( i_query )
2999     {
3000         case VOUT_GET_SIZE:
3001             if( p_vout->p_sys->p_win->owner_window )
3002                 return vout_ControlWindow( p_vout,
3003                     (void *)p_vout->p_sys->p_win->owner_window, i_query, args);
3004
3005             pi_width  = va_arg( args, unsigned int * );
3006             pi_height = va_arg( args, unsigned int * );
3007
3008             vlc_mutex_lock( &p_vout->p_sys->lock );
3009             *pi_width  = p_vout->p_sys->p_win->i_width;
3010             *pi_height = p_vout->p_sys->p_win->i_height;
3011             vlc_mutex_unlock( &p_vout->p_sys->lock );
3012             return VLC_SUCCESS;
3013
3014         case VOUT_SET_SIZE:
3015             if( p_vout->p_sys->p_win->owner_window )
3016                 return vout_ControlWindow( p_vout,
3017                     (void *)p_vout->p_sys->p_win->owner_window, i_query, args);
3018
3019             vlc_mutex_lock( &p_vout->p_sys->lock );
3020
3021             i_width  = va_arg( args, unsigned int );
3022             i_height = va_arg( args, unsigned int );
3023             if( !i_width ) i_width = p_vout->i_window_width;
3024             if( !i_height ) i_height = p_vout->i_window_height;
3025
3026 #ifdef MODULE_NAME_IS_xvmc
3027             xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
3028 #endif
3029             /* Update dimensions */
3030             XResizeWindow( p_vout->p_sys->p_display,
3031                            p_vout->p_sys->p_win->base_window,
3032                            i_width, i_height );
3033 #ifdef MODULE_NAME_IS_xvmc
3034             xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
3035 #endif
3036             vlc_mutex_unlock( &p_vout->p_sys->lock );
3037             return VLC_SUCCESS;
3038
3039        case VOUT_CLOSE:
3040             vlc_mutex_lock( &p_vout->p_sys->lock );
3041             XUnmapWindow( p_vout->p_sys->p_display,
3042                           p_vout->p_sys->original_window.base_window );
3043             vlc_mutex_unlock( &p_vout->p_sys->lock );
3044             /* Fall through */
3045
3046        case VOUT_REPARENT:
3047             vlc_mutex_lock( &p_vout->p_sys->lock );
3048             if( i_query == VOUT_REPARENT ) d = (Drawable)va_arg( args, int );
3049             if( !d )
3050 #ifdef MODULE_NAME_IS_xvmc
3051             xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
3052 #endif
3053             XReparentWindow( p_vout->p_sys->p_display,
3054                              p_vout->p_sys->original_window.base_window,
3055                              DefaultRootWindow( p_vout->p_sys->p_display ),
3056                              0, 0 );
3057             else
3058             XReparentWindow( p_vout->p_sys->p_display,
3059                              p_vout->p_sys->original_window.base_window,
3060                              d, 0, 0);
3061             XSync( p_vout->p_sys->p_display, False );
3062             p_vout->p_sys->original_window.owner_window = 0;
3063 #ifdef MODULE_NAME_IS_xvmc
3064             xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
3065 #endif
3066             vlc_mutex_unlock( &p_vout->p_sys->lock );
3067             return vout_vaControlDefault( p_vout, i_query, args );
3068
3069         case VOUT_SET_STAY_ON_TOP:
3070             if( p_vout->p_sys->p_win->owner_window )
3071                 return vout_ControlWindow( p_vout,
3072                     (void *)p_vout->p_sys->p_win->owner_window, i_query, args);
3073
3074             b_arg = va_arg( args, vlc_bool_t );
3075             vlc_mutex_lock( &p_vout->p_sys->lock );
3076 #ifdef MODULE_NAME_IS_xvmc
3077             xvmc_context_reader_lock( &p_vout->p_sys->xvmc_lock );
3078 #endif
3079             WindowOnTop( p_vout, b_arg );
3080 #ifdef MODULE_NAME_IS_xvmc
3081             xvmc_context_reader_unlock( &p_vout->p_sys->xvmc_lock );
3082 #endif
3083             vlc_mutex_unlock( &p_vout->p_sys->lock );
3084             return VLC_SUCCESS;
3085
3086        default:
3087             return vout_vaControlDefault( p_vout, i_query, args );
3088     }
3089 }
3090
3091 /*****************************************************************************
3092  * TestNetWMSupport: tests for Extended Window Manager Hints support
3093  *****************************************************************************/
3094 static void TestNetWMSupport( vout_thread_t *p_vout )
3095 {
3096     int i_ret, i_format;
3097     unsigned long i, i_items, i_bytesafter;
3098     Atom net_wm_supported;
3099     union { Atom *p_atom; unsigned char *p_char; } p_args;
3100
3101     p_args.p_atom = NULL;
3102
3103     p_vout->p_sys->b_net_wm_state_fullscreen = VLC_FALSE;
3104     p_vout->p_sys->b_net_wm_state_above = VLC_FALSE;
3105     p_vout->p_sys->b_net_wm_state_below = VLC_FALSE;
3106     p_vout->p_sys->b_net_wm_state_stays_on_top = VLC_FALSE;
3107
3108     net_wm_supported =
3109         XInternAtom( p_vout->p_sys->p_display, "_NET_SUPPORTED", False );
3110
3111     i_ret = XGetWindowProperty( p_vout->p_sys->p_display,
3112                                 DefaultRootWindow( p_vout->p_sys->p_display ),
3113                                 net_wm_supported,
3114                                 0, 16384, False, AnyPropertyType,
3115                                 &net_wm_supported,
3116                                 &i_format, &i_items, &i_bytesafter,
3117                                 (unsigned char **)&p_args );
3118
3119     if( i_ret != Success || i_items == 0 ) return;
3120
3121     msg_Dbg( p_vout, "Window manager supports NetWM" );
3122
3123     p_vout->p_sys->net_wm_state =
3124         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE", False );
3125     p_vout->p_sys->net_wm_state_fullscreen =
3126         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_FULLSCREEN",
3127                      False );
3128     p_vout->p_sys->net_wm_state_above =
3129         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_ABOVE", False );
3130     p_vout->p_sys->net_wm_state_below =
3131         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_BELOW", False );
3132     p_vout->p_sys->net_wm_state_stays_on_top =
3133         XInternAtom( p_vout->p_sys->p_display, "_NET_WM_STATE_STAYS_ON_TOP",
3134                      False );
3135
3136     for( i = 0; i < i_items; i++ )
3137     {
3138         if( p_args.p_atom[i] == p_vout->p_sys->net_wm_state_fullscreen )
3139         {
3140             msg_Dbg( p_vout,
3141                      "Window manager supports _NET_WM_STATE_FULLSCREEN" );
3142             p_vout->p_sys->b_net_wm_state_fullscreen = VLC_TRUE;
3143         }
3144         else if( p_args.p_atom[i] == p_vout->p_sys->net_wm_state_above )
3145         {
3146             msg_Dbg( p_vout, "Window manager supports _NET_WM_STATE_ABOVE" );
3147             p_vout->p_sys->b_net_wm_state_above = VLC_TRUE;
3148         }
3149         else if( p_args.p_atom[i] == p_vout->p_sys->net_wm_state_below )
3150         {
3151             msg_Dbg( p_vout, "Window manager supports _NET_WM_STATE_BELOW" );
3152             p_vout->p_sys->b_net_wm_state_below = VLC_TRUE;
3153         }
3154         else if( p_args.p_atom[i] == p_vout->p_sys->net_wm_state_stays_on_top )
3155         {
3156             msg_Dbg( p_vout,
3157                      "Window manager supports _NET_WM_STATE_STAYS_ON_TOP" );
3158             p_vout->p_sys->b_net_wm_state_stays_on_top = VLC_TRUE;
3159         }
3160     }
3161
3162     XFree( p_args.p_atom );
3163 }
3164
3165 /*****************************************************************************
3166  * Key events handling
3167  *****************************************************************************/
3168 static struct
3169 {
3170     int i_x11key;
3171     int i_vlckey;
3172
3173 } x11keys_to_vlckeys[] =
3174 {
3175     { XK_F1, KEY_F1 }, { XK_F2, KEY_F2 }, { XK_F3, KEY_F3 }, { XK_F4, KEY_F4 },
3176     { XK_F5, KEY_F5 }, { XK_F6, KEY_F6 }, { XK_F7, KEY_F7 }, { XK_F8, KEY_F8 },
3177     { XK_F9, KEY_F9 }, { XK_F10, KEY_F10 }, { XK_F11, KEY_F11 },
3178     { XK_F12, KEY_F12 },
3179
3180     { XK_Return, KEY_ENTER },
3181     { XK_KP_Enter, KEY_ENTER },
3182     { XK_space, KEY_SPACE },
3183     { XK_Escape, KEY_ESC },
3184
3185     { XK_Menu, KEY_MENU },
3186     { XK_Left, KEY_LEFT },
3187     { XK_Right, KEY_RIGHT },
3188     { XK_Up, KEY_UP },
3189     { XK_Down, KEY_DOWN },
3190
3191     { XK_Home, KEY_HOME },
3192     { XK_End, KEY_END },
3193     { XK_Page_Up, KEY_PAGEUP },
3194     { XK_Page_Down, KEY_PAGEDOWN },
3195
3196     { XK_Insert, KEY_INSERT },
3197     { XK_Delete, KEY_DELETE },
3198     { XF86XK_AudioNext, KEY_MEDIA_NEXT_TRACK},
3199     { XF86XK_AudioPrev, KEY_MEDIA_PREV_TRACK},
3200     { XF86XK_AudioMute, KEY_VOLUME_MUTE },
3201     { XF86XK_AudioLowerVolume, KEY_VOLUME_DOWN },
3202     { XF86XK_AudioRaiseVolume, KEY_VOLUME_UP },
3203     { XF86XK_AudioPlay, KEY_MEDIA_PLAY_PAUSE },
3204     { XF86XK_AudioPause, KEY_MEDIA_PLAY_PAUSE },
3205
3206     { 0, 0 }
3207 };
3208
3209 static int ConvertKey( int i_key )
3210 {
3211     int i;
3212
3213     for( i = 0; x11keys_to_vlckeys[i].i_x11key != 0; i++ )
3214     {
3215         if( x11keys_to_vlckeys[i].i_x11key == i_key )
3216         {
3217             return x11keys_to_vlckeys[i].i_vlckey;
3218         }
3219     }
3220
3221     return 0;
3222 }
3223
3224 /*****************************************************************************
3225  * WindowOnTop: Switches the "always on top" state of the video window.
3226  *****************************************************************************/
3227 static int WindowOnTop( vout_thread_t *p_vout, vlc_bool_t b_on_top )
3228 {
3229     if( p_vout->p_sys->b_net_wm_state_stays_on_top )
3230     {
3231         XClientMessageEvent event;
3232
3233         memset( &event, 0, sizeof( XClientMessageEvent ) );
3234
3235         event.type = ClientMessage;
3236         event.message_type = p_vout->p_sys->net_wm_state;
3237         event.display = p_vout->p_sys->p_display;
3238         event.window = p_vout->p_sys->p_win->base_window;
3239         event.format = 32;
3240         event.data.l[ 0 ] = b_on_top; /* set property */
3241         event.data.l[ 1 ] = p_vout->p_sys->net_wm_state_stays_on_top;
3242
3243         XSendEvent( p_vout->p_sys->p_display,
3244                     DefaultRootWindow( p_vout->p_sys->p_display ),
3245                     False, SubstructureRedirectMask,
3246                     (XEvent*)&event );
3247     }
3248
3249     /* use _NET_WM_STATE_ABOVE if window manager
3250      * doesn't handle _NET_WM_STATE_STAYS_ON_TOP */
3251     else if( p_vout->p_sys->b_net_wm_state_above )
3252     {
3253         XClientMessageEvent event;
3254
3255         memset( &event, 0, sizeof( XClientMessageEvent ) );
3256
3257         event.type = ClientMessage;
3258         event.message_type = p_vout->p_sys->net_wm_state;
3259         event.display = p_vout->p_sys->p_display;
3260         event.window = p_vout->p_sys->p_win->base_window;
3261         event.format = 32;
3262         event.data.l[ 0 ] = b_on_top; /* set property */
3263         event.data.l[ 1 ] = p_vout->p_sys->net_wm_state_above;
3264
3265         XSendEvent( p_vout->p_sys->p_display,
3266                     DefaultRootWindow( p_vout->p_sys->p_display ),
3267                     False, SubstructureRedirectMask,
3268                     (XEvent*)&event );
3269     }
3270
3271     return VLC_SUCCESS;
3272 }